So I have a weird issue where I can't mock modules if they're not on the global scope.
Eg:
// constants.js
exports.SUPPORTED_LANGUAGES = ['en', 'de']
// file-to-test.js
const { SUPPORTED_LANGUAGES } = require('./constants')
exports.asyncFnToTest = async () => {
const something = SUPPORTED_LANGUAGES.map(() => {
// do stuff...
});
}
And here is the catchy part:
// file-to-test.test.js
const { asyncFnToTest } = require('./file-to-test')
it('should test asyncFnToTest', async () => {
jest.mock('./constants', () => ({
SUPPORTED_LANGUAGES: ['mock', 'lang'];
}));
const { SUPPORTED_LANGUAGES } = require('./constants');
console.log(SUPPORTED_LANGUAGES); // OUTPUT is: ['en', 'de'] instead of ['mock', 'lang']
});
BUT if the mock is on the global scope like this:
// file-to-test.test.js
const { asyncFnToTest } = require('./file-to-test');
const { SUPPORTED_LANGUAGES } = require('./constants');
jest.mock('./constants', () => ({
SUPPORTED_LANGUAGES: ['mock', 'lang'];
}));
it('should test asyncFnToTest', async () => {
console.log(SUPPORTED_LANGUAGES); // OUTPUT is: ['mock', 'lang']
});
The second approach works okay for functions as I can .mockReturnValue() or .mockImplementation() them, so I can set test scenarios, however SUPPORTED_LANGUAGES is an array so I cannot change the initial mocked value.
Can someone tell me why can't I mock modules inside my test cases or if there's a way to overwrite the array on the global scope for a specific test case?