Which is a Jest way to restore a funny feature

In a Sinon stub, it’s very easy to restore functionality.

const stub = sinon.stub(fs,"writeFile",()=>{}) ... fs.writeFile.restore() 

I want to do the same with Jest. The closest I get is this ugly code:

 const fsWriteFileHolder = fs.writeFile fs.writeFile = jest.fn() ... fs.writeFile = fsWriteFileHolder 
+12
source share
2 answers

If you want to clear all calls from the layout function, you can use:

 const myMock = jest.fn(); // ... myMock.mockClear(); 

To clear everything stored in the layout, try instead:

 myMock.mockReset(); 
+10
source

Finally, I found a workable solution thanks to the contribution of @nbkhope.

So, the following code works as expected, that is, it mocks the code and then restores the original behavior:

 const spy = jest.spyOn( fs, 'writeFile' ).mockImplementation((filePath,data) => { ... }) ... spy.mockRestore() 
+12
source

Source: https://habr.com/ru/post/1015716/


All Articles