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
To mock the return value of an imported function in Jest, you have to either call mockReturnValue or mockImplementation on a Jest mock function and then specify the return value. Which function mock function you should use depends on your situation.
You can create a namespace that you export as the default object and call b using the namespace. This way, when you call jest. mock it will replace the b function on the namespace object. const f = require('./f'); jest.
Mocking Node modules If the module you are mocking is a Node module (e.g.: lodash ), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With