I'm trying to mock a module's function. I want it to return a specific value every time until the point that I'm firing a function that should change that value to something else. Assume you can't have any expectations of how many times the module's mocked function will fire before, or after the changing function fires.
What I've tried so far is:
import * as module from 'module';
jest.mock('module', () => ({
...jest.requireActual('module'),
targetFunction: jest.fn(),
}));
test('targetFunction returns a different value after changingFunction has fired', async () => {
jest
.spyOn(module, 'targetFunction')
.mockReturnValue('a');
module.start();
// other assertions
jest
.spyOn(module, 'targetFunction')
.mockReturnValue('b');
module.changingFunction();
// other assertions
});
But it keeps returning a after my second mock.
Obviously the above is just a demonstration of the expected behaviour. Before changingFunction fires, I want targetFunction to return a every time it fires. After changingFunction fires, I want targetFunction to return b every time it fires.
If I'm using mockReturnValueOnce, and continue to chain them it works, but I wouldn't like to rely on specific times. I want to change the return value in a specific place in the code.