I\'d like to change the implementation of a mocked dependency on a per single test basis by extending the default mock\'s
Vanilla JS
Use mockFn.mockImplementation(fn).
import { funcToMock } from './somewhere';
jest.mock('./somewhere');
beforeEach(() => {
funcToMock.mockImplementation(() => { /* default implementation */ });
});
test('case that needs a different implementation of funcToMock', () => {
funcToMock.mockImplementation(() => { /* implementation specific to this test */ });
// ...
});
TypeScript
In addition to the Vanilla JS solution:
To prevent the message mockImplementation is not a property of funcToMock, you will need to specify the type, e.g. by changing the top line from above to the following:
import { (funcToMock as jest.Mock) } from './somewhere';
A question addressing this issue can be found here: jest typescript property mock does not exist on type