問題:
I have a file that relies on an exported const
variable.我有一個依賴於導出的const
變量的文件。 This variable is set to true
but if ever needed can be set to false
manually to prevent some behavior if downstream services request it.此變量設置爲true
但如果需要,可以手動設置爲false
以防止下游服務請求時出現某些行爲。
I am not sure how to mock a const
variable in Jest so that I can change it's value for testing the true
and false
conditions.我不知道如何嘲笑一個const
開玩笑變量,這樣我可以改變它的值,用於測試true
和false
條件。
Example:例子:
//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
});
});