-
Notifications
You must be signed in to change notification settings - Fork 12
/
lib.jest-test.js
39 lines (33 loc) · 1.04 KB
/
lib.jest-test.js
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
jest.mock('./db', () => ({
get: jest.fn()
}));
const lib = require('./lib');
const mockDb = require('./db');
const {getTodo} = lib;
// Using const means we can't re-assign
let {makeKey} = lib;
beforeEach(() => {
jest.clearAllMocks();
});
test('CommonJS > Mocking destructured makeKey doesn’t work', async () => {
const mockMakeKey = jest.fn(() => 'mock-key');
makeKey = mockMakeKey;
await getTodo(1);
expect(makeKey).not.toHaveBeenCalled();
expect(mockDb.get).not.toHaveBeenCalledWith('mock-key');
});
test('CommonJS > Mocking lib.makeKey works', async () => {
const mockMakeKey = jest.fn(() => 'mock-key');
lib.makeKey = mockMakeKey;
await getTodo(1);
expect(mockMakeKey).toHaveBeenCalledWith(1);
expect(mockDb.get).toHaveBeenCalledWith('mock-key');
});
test('CommonJS > Spying lib.makeKey works', async () => {
const makeKeySpy = jest
.spyOn(lib, 'makeKey')
.mockImplementationOnce(() => 'mock-key');
await getTodo(1);
expect(makeKeySpy).toHaveBeenCalled();
expect(mockDb.get).toHaveBeenCalledWith('mock-key');
});