javascript - 如何在 Jest 中模拟导出的常量

标签 javascript reactjs unit-testing jestjs

我有一个依赖于导出的 const 变量的文件。此变量设置为 true,但如果需要,可以手动将其设置为 false,以防止在下游服务请求时出现某些行为。

我不确定如何在 Jest 中模拟 const 变量,以便我可以更改它的值以测试 truefalse 条件.

例子:

//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);
    });
});

或者,您可以切换到原始的 commonjs 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);
    });
});

关于javascript - 如何在 Jest 中模拟导出的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42977961/

相关文章:

javascript - 根据环境响应不同的主页最佳实践

javascript - 如何使用 jquery 加载和验证表单?

javascript - react 选择禁用选项

javascript - React 16.3+ 从状态变化触发 onChange 的正确方法

reactjs - Webpack、React 热重载器和多个条目

java - 如何模拟模拟对象的方法调用?

javascript - Firefox 29.0.1 WebSocket 问题

javascript - 在 Android 应用程序上播放 mp3 铃声 - PhoneGap

ios - 如何在 swift 3 中专门化通用高阶函数?

c# - 测试事件驱动的行为