Reputation: 2207
In Sinon's stub it is very easy to restore functionality.
const stub = sinon.stub(fs,"writeFile",()=>{})
...
fs.writeFile.restore()
I am looking to do the same thing with Jest. The closest I get is this ugly code:
const fsWriteFileHolder = fs.writeFile
fs.writeFile = jest.fn()
...
fs.writeFile = fsWriteFileHolder
Upvotes: 40
Views: 30113
Reputation: 249
jest.spyOn()
is helpful when mocking and unmocking methods, however there might be a situation where you want to mock and unmock esModule.
I had such situation recently and I found this solution to work for me:
// Module that will be mocked and unmocked
import exampleModule from 'modules/exampleModule';
const ActualExampleModule = jest.requireActual('modules/exampleModule');
describe('Some tests that require mocked module', () => {
// Tests on mock
});
describe('Some tests that require original module', () => {
it('Test with restored module', async () => {
const restoredModule = await import('modules/exampleModule');
restoredModule.default = ActualExampleModule .default;
// Now we can assert on original module
});
});
Upvotes: 0
Reputation: 2207
Finally I found a workable solution thanks to @nbkhope's contribution.
So the following code work as expected, i.e. it mocks the code and then it restore the original behavior:
const spy = jest.spyOn(
fs,
'writeFile'
).mockImplementation((filePath,data) => {
...
})
...
spy.mockRestore()
Upvotes: 45
Reputation: 7474
If you want to clear all the calls to the mock function, you can use:
const myMock = jest.fn();
// ...
myMock.mockClear();
To clear everything stored in the mock, try instead:
myMock.mockReset();
Upvotes: 19