最佳答案
我有一个依赖于导出 const
变量的文件。这个变量被设置为 true
,但是如果需要的话,可以手动设置为 false
,以防止下游服务请求它时出现某些行为。
我不确定如何在 Jest 中模拟 const
变量,以便更改它的值来测试 true
和 false
条件。
例如:
//constants module
export const ENABLED = true;
//allowThrough module
import { ENABLED } from './constants';
export function allowThrough(data) {
return (data && ENABLED === true)
}
// jest test
import { allowThrough } from './allowThrough';
import { ENABLED } from './constants';
describe('allowThrough', () => {
test('success', () => {
expect(ENABLED).toBE(true);
expect(allowThrough({value: 1})).toBe(true);
});
test('fail, ENABLED === false', () => {
//how do I override the value of ENABLED here?
expect(ENABLED).toBe(false) // won't work because enabled is a const
expect(allowThrough({value: 1})).toBe(true); //fails because ENABLED is still true
});
});