David
David

Reputation: 4847

Configure Jest to reset mocks between tests with Create React App

When I add the following code to my package.json I get an error saying it is not supported:

"jest": {
    "resetMocks": true
},
  1. I am confused why this is not working as it seems to have been added in this pull request
  2. Is there another way of doing this?

Thanks in advance!

Upvotes: 3

Views: 3346

Answers (1)

Brian Adams
Brian Adams

Reputation: 45810

Solution

Add the following to src/setupTests.js:

beforeEach(() => {
  jest.resetAllMocks()
})

Details

The documentation for the resetMocks option states that setting it to true is "Equivalent to calling jest.resetAllMocks() between each test."

Looking at the Jest source shows that the check for config.resetMocks happens within a beforeEach() and if true it calls jest.resetAllMocks().

Apps bootstrapped with create-react-app that are using react-scripts version 0.4.0 or higher will automatically run src/setupTests.js to initialize the test environment before each test runs.

So adding the above code to src/SetupTests.js is equivalent to setting the resetMocks option to true for a non-create-react-app app.

Upvotes: 7

Related Questions