我有一个依赖于导出const变量的文件。此变量设置为,true但是如果需要,可以将其设置为false手动设置,以防止下游服务请求时出现某些行为。
const
true
false
我不确定如何const在Jest中模拟变量,以便更改测试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 }); });
如果将ES6模块语法编译为ES5,则此示例将起作用,因为最后,所有模块导出都属于同一对象,可以对其进行修改。
import { allowThrough } from './allowThrough'; import { ENABLED } from './constants'; import * as constants from './constants'; describe('allowThrough', () => { test('success', () => { constants.ENABLED = true; expect(ENABLED).toBe(true); expect(allowThrough({ value: 1 })).toBe(true); }); test('fail, ENABLED === false', () => { constants.ENABLED = false; expect(ENABLED).toBe(false); expect(allowThrough({ value: 1 })).toBe(false); }); });
另外,您可以切换到raw commonjs require函数,并借助以下方法做到这一点jest.mock(...):
require
jest.mock(...)
const mockTrue = { ENABLED: true }; const mockFalse = { ENABLED: false }; describe('allowThrough', () => { beforeEach(() => { jest.resetModules(); }); test('success', () => { jest.mock('./constants', () => mockTrue) const { ENABLED } = require('./constants'); const { allowThrough } = require('./allowThrough'); expect(ENABLED).toBe(true); expect(allowThrough({ value: 1 })).toBe(true); }); test('fail, ENABLED === false', () => { jest.mock('./constants', () => mockFalse) const { ENABLED } = require('./constants'); const { allowThrough } = require('./allowThrough'); expect(ENABLED).toBe(false); expect(allowThrough({ value: 1 })).toBe(false); }); });