In Jest, you can change the mock implementation on a per-test basis using jest.fn()
and providing a new implementation as the first argument in your test case.
Here’s an example:
const myModule = require('./myModule');
describe('myModule', () => {
it('uses the default implementation', () => {
expect(myModule.getData()).toBe('default');
});
it('uses a custom implementation', () => {
myModule.getData = jest.fn(() => 'custom');
expect(myModule.getData()).toBe('custom');
});
});
In the first test case, the default implementation is used, while in the second test case, the mock function is replaced with a new implementation. Note that you can only replace the mock implementation within the scope of the test case, and it won’t affect other test cases.
+ There are no comments
Add yours