Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 560
A.K Avatar asked Mar 13 '19 08:03

A.K


1 Answers

I have been able to do something similar by following the post at https://mikeborozdin.com/post/changing-jest-mocks-between-tests/

This creates a mock and then changes it for each test.

import * as constants from './constants'

jest.mock('./constants', () => ({
  __esModule: true,
  MY_CONSTANT: 'SOME OTHER DEFAULT',
}))

it("Should do something when MY_CONSTANT === "TEST, () => {
  constant.MY_CONSTANT = 'TEST'
  expect(constant.MY_CONSTANT).toBe('TEST')
})

it("Should do something else when MY_CONSTANT !== "TEST, () => {
  constant.MY_CONSTANT = 'NOT A TEST'
  expect(constant.MY_CONSTANT).toBe('NOT A TEST')
})

If you are using typescript then the mock needs to be cast to modify the mock values:

const mockConstants = constants as { MY_CONSTANT: string }
mockConstants.MY_CONSTANT = 'TEST'
like image 141
Ben T Avatar answered Sep 28 '22 02:09

Ben T