I have a file that relies on an exported const
variable. This variable is set to true
but if ever needed can be set to false
manually
Thanks to @Luke I was able to expand on his answer for my needs. I had the requirements of:
Turns out that doMock()
is like mock()
but doesn't get hoisted. In addition requireActual()
can be used to grab original data.
My config.js
file - I need to mock only part of it
export const SOMETHING = 'blah'
export const OTHER = 'meh'
My test file
// import { someFunc } from 'some/file' // This won't work with doMock - see below
describe('My test', () => {
test('someFunc() does stuff', async () => {
// Here I mock the config file which gets imported somewhere deep in my code
jest.doMock('config.js', () => {
// Grab original
const originalModule = jest.requireActual('config')
// Return original but override some values
return {
__esModule: true, // Depends on your setup
...originalModule,
SOMETHING: 'boom!'
}
})
// Because `doMock` doesn't get hoisted we need to import the function after
const { someFunc } = await import(
'some/file'
)
// Now someFunc will use the original config values but overridden with SOMETHING=boom!
const res = await someFunc()
})
})
Depending on other tests you may also need to use resetModules()
somewhere such as beforeAll
or afterAll
.
Docs: