A Jest mock function can be set to return a specific value for all calls, or just once.
Note that if we define a return value with mockReturnValueOnce, the mock function will return undefined for all subsequent calls.
It will not throw an error and may go unnoticed, causing undesirable behaviour.
If a Jest mock returns undefined incorrectly check to make sure how it was defined and how many times it was called.
The code below shows the different behaviours:
describe('mock once tests', () => { test('many returns', () => { const f = jest.fn() f.mockReturnValueOnce('result') const result1 = f() console.log(result1) const result2 = f() console.log(result2) const result3 = f() console.log(result3) }) test('one return', () => { const f = jest.fn() f.mockReturnValue('result') const result1 = f() console.log(result1) const result2 = f() console.log(result2) const result3 = f() console.log(result3) }) })
Output:
result undefined undefined result result result