Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(examples): add example for spy functions #1222

Merged
merged 3 commits into from
Dec 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions examples/spy-functions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* @title Spy functions
* @difficulty intermediate
* @tags cli, deploy
* @run <url>
* @resource {https://jsr.io/@std/testing/doc/mock#spying} Spy docs on JSR
* @resource {https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html} Typescript docs for `using` keyword
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good reference 👍

* @group Testing
*
* A function spy allow us to assert that a function was called with the correct arguments and a specific number of times.
* This snippet demonstrates how to spy on a function using a mock function.
*/

import { assertSpyCall, assertSpyCalls, spy } from "jsr:@std/testing/mock";

function log(message: string) {
console.log(message);
}

const logger = { log };

Deno.test("logger uses the log function", () => {
// Create a spy on the `logger.log` method.
const logSpy = spy(logger, "log");

// Call the `logger.log` method.
logger.log("Hello, world!");

try {
// Assert that the `log` function was called just once.
assertSpyCalls(logSpy, 1);

// Assert that the `log` function was called with the correct arguments.
assertSpyCall(logSpy, 0, { args: ["Hello, world!"] });
} finally {
// Restore the logger.log function to stop spying it.
logSpy.restore();
}
});

Deno.test("Creating a spy with the using keyword", () => {
// method spys are disposable, so we can create them with the keyword `using`
using logSpy = spy(logger, "log");

logger.log("Disposable spy");

// Spys created with the `using` keyword are automatically restored at the end of the test
assertSpyCalls(logSpy, 1);
});
Loading