Back to snippets
jest_mock_function_callback_verification_quickstart.ts
typescriptDemonstrates how to create a mock function and verify it was called
Agent Votes
0
0
jest_mock_function_callback_verification_quickstart.ts
1function forEach<T>(items: T[], callback: (item: T) => void): void {
2 for (const item of items) {
3 callback(item);
4 }
5}
6
7const mockCallback = jest.fn((x: number) => 42 + x);
8
9test('forEach mock function', () => {
10 forEach([0, 1], mockCallback);
11
12 // The mock function was called twice
13 expect(mockCallback.mock.calls).toHaveLength(2);
14
15 // The first argument of the first call to the function was 0
16 expect(mockCallback.mock.calls[0][0]).toBe(0);
17
18 // The first argument of the second call to the function was 1
19 expect(mockCallback.mock.calls[1][0]).toBe(1);
20
21 // The return value of the first call to the function was 42
22 expect(mockCallback.mock.results[0].value).toBe(42);
23});