I have the following foo and bar modules:
bar.mjs
:
<code>export const BAR = 'production'
</code>
<code>export const BAR = 'production'
</code>
export const BAR = 'production'
foo.mjs
:
<code>import { BAR } from "./bar.mjs";
export const FOO = () => BAR
</code>
<code>import { BAR } from "./bar.mjs";
export const FOO = () => BAR
</code>
import { BAR } from "./bar.mjs";
export const FOO = () => BAR
I want to test FOO
mocking bar
and having another value for the constant BAR
.
I have read this question and the answer doesn’t work (the solution relied on the constant being defined as var
rather than const
).
baz.test.js
:
<code>import { FOO } from "./foo.mjs";
import { jest } from '@jest/globals'
test('Mock test', () => {
jest.mock('./bar.mjs', () => ({
BAR: 'mocked'
}))
console.log(FOO())
})
</code>
<code>import { FOO } from "./foo.mjs";
import { jest } from '@jest/globals'
test('Mock test', () => {
jest.mock('./bar.mjs', () => ({
BAR: 'mocked'
}))
console.log(FOO())
})
</code>
import { FOO } from "./foo.mjs";
import { jest } from '@jest/globals'
test('Mock test', () => {
jest.mock('./bar.mjs', () => ({
BAR: 'mocked'
}))
console.log(FOO())
})
I think this doesn’t work because FOO
‘s closure captures the value of BAR
at the moment the foo
module is imported.
What is the correct solution to mocking a constant?
1