Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  
like image 255
Dejan Toteff Avatar asked Mar 13 '17 22:03

Dejan Toteff


People also ask

How do I return a mock function to Jest?

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.

How do you call a mocked function in Jest?

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.

What is __ mocks __ in 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.


1 Answers

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() 
like image 86
Dejan Toteff Avatar answered Oct 08 '22 04:10

Dejan Toteff