Which is Jest way for restoring mocked function
22,877
Solution 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
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();
Comments
-
Dejan Toteff over 4 years
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