-
Notifications
You must be signed in to change notification settings - Fork 280
/
Copy pathspy_functions.ts
49 lines (39 loc) · 1.52 KB
/
spy_functions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
* @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);
});