I have a hard time understanding when to use jest.fn, jest.mock or jest.spyOn.
This seems to be the summary:
- Use
fnwhen mocking a function - Use
mockwhen mocking a module - Use
spyOnwhen you want to observe things about a real module or function
But I see code examples like this:
test('creates Contract on correct date', () => {
const NOW = '2019-05-03T08:00:00.000Z';
const mockDateNow = jest
.spyOn(global.Date, 'now')
.mockImplementation(() => new Date(NOW).getTime());
...stuff...
expect(result).toEqual(NOW);
mockDateNow.mockRestore();
});
Is there any advantage to that over the simpler code below (excuse me if I have made any syntax errors).
test('creates Contract on correct date', () => {
const NOW = '2019-05-03T08:00:00.000Z';
const mockDateNow = global.Date.now.mockImplementation(() => new Date(NOW).getTime());
...stuff...
expect(result).toEqual(NOW);
mockDateNow.mockRestore();
});
So,
why is spyOn used to mock a single function that then get's a mock implementation? Is my understanding of when to use fn, mock, spyOn wrong? Please show me how I am wrong.