Having difficulty mocking a constant with Jest on a per test basis. Currently, my mock is "static" and cannot be customized for each test individually.
Code:
// allowList.ts
export const ALLOW_LIST = {
'1234': true
};
// listUtil.ts
import { ALLOW_LIST } from './allowList.ts';
export const checkList = (id: string) => {
if (ALLOW_LIST[id]) return true;
return false;
};
Test (working):
// listUtil.test.ts
import { checkList } from './listUtil';
jest.mock('./listUtil', () => {
return {
'5678': true
};
});
test('in list', () => {
expect(checkList('5678')).toBe(true);
});
test('not in list', () => {
expect(checkList('1234')).toBe(false);
});
Desired approach (not working):
// listUtil.test.ts
import { checkList } from './listUtil';
test('in list', () => {
jest.mock('./listUtil', () => {
return {
'5678': true
};
});
expect(checkList('5678')).toBe(true);
});
test('not in list', () => {
jest.mock('./listUtil', () => {
return {
'9123': true
};
});
expect(checkList('1234')).toBe(false);
});
Is it possible to achieve what I'm attempting? This post seems similar and successful when mocking functions, but I am facing the same challenges as the commenters in the accepted answer. It seems like the working version operates due to the hoisted mock that overwrites the real implementation, but I am unsure how to replicate that for each test.
One option could be exposing the ALLOW_LIST via a function:
// allowList.ts
const ALLOW_LIST = {
'1234': true
};
export const getAllowList = () => ALLOW_LIST;
Wondering if this is necessary or if there are other solutions.