To demonstrate the issue with jest.mock()
After calling jest.mock()
to mock a module, how can we restore that module?
I have 2 different tests in App.test.js
file. I want to use the mocked module in one test and use the original module in the other test. How to achieve this scenario? Already tried jest.resetAllMocks()
and mockClear()
without success.
- Clone this repo.
- Run
yarn
to install dependencies. - Run
yarn test
to run test. - In
App.test.js
, if there isjest.mock()
, the test "1 - with mocked module" will pass but the test "2 - with original module" will fail. - On the other hand, if there is not
jest.mock()
, the test "1 - with mocked module" will fail but the test "2 - with original module" will pass.
From this issue
-
Add this code into the beginning of the test that we want to restore
mockMyModule
to the original formmockMyModule.mockImplementationOnce(require.requireActual('./myModule').myModule)
Or using
mockImplementation()
insteadmockMyModule.mockImplementationOnce(require.requireActual('./myModule').myModule)
-
Don't forget to
mockReset()
if we want other test cases to use the initialjest.mock()
versionmockMyModule.mockReset()
https://stackoverflow.com/a/53166827/6568503
Just make a separate test file. One that uses the mock and the other that doesn't.