Jest - Mock a constant property from a module for a specific test

A.K picture A.K · Mar 13, 2019 · Viewed 14.5k times · Source

So, I'm attempting to do something which on the surface should be very simple...

I have some constants defined in: ` //constants.js

module.exports = {
 MY_CONSTANT: "TEST"
}

` I have a file which I'm trying to test which has a branching statement like this:

`

//file to test
//...

if(CONSTANTS.MY_CONSTANT === "TEST")
{...}
...

`

And I have a test like this: `

//test


 it("Should do something when MY_CONSTANT === "TEST, () => {
    //This is fine as it is exported as TEST
    })


 it("Should do something else when MY_CONSTANT !== "TEST, () => {
    //This seems annoyingly difficult to get working...
    })

`

I've tried this - With no luck, it doesn't change the actual value

I've tried changing the constant export to export an object instead (that didn't work)

I've tried adding a jest.mock(..) for the constants in my test file and doing an unmock in the tests I don't need them mocked.

I've tried adding a jest.doMock(...) within the test function I need to change the value. (along with jest.resetModules and another require)

I've tried adding a jest.doMock(...) to a tests beforeEach (along with jest.resetModules and another require)

I'm at a loss really...literally all I want to do is change a property value before a test runs 😂

Update So I've done some of the suggestions made:

I now have a mocks folder adjacent to the constant folder It contains a file named the same as the actual constants file and a custom export

I've then added jest.mock("../constants); inside the test.

I've then also added a const funcImTesting = require("../../file").testFunction inside the test.

Still the constant remains unchanged and the test fails

Answer

Hitmands picture Hitmands · Mar 13, 2019

To mock for one test only:

jest.mock('./constants.js', () => ({
  MY_CONSTANT: 'something fake'
}));

https://jestjs.io/docs/en/manual-mocks


To provide a mock for every test:

  1. create a __mocks__ directory adiacent to the module you desire to mock
  2. provide implementation
  3. call jest.mock('./moduleName') in your test

https://jestjs.io/docs/en/manual-mocks#mocking-user-modules