'Which is Jest way for restoring mocked function
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
Solution 1:[1]
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()
Solution 2:[2]
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();
Solution 3:[3]
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
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | nbkhope |
| Solution 3 | DharmanBot |
