【问题标题】:How do I mock an ES6 module in only a single test in Jest?如何在 Jest 中仅在一次测试中模拟 ES6 模块?
【发布时间】:2018-04-15 06:37:19
【问题描述】:

假设我有以下模块:

src/validators.js

export const isPositiveNumber = value => value > 0 && value < Number.MAX_SAFE_INTEGER;

我在另一个模块中使用它:

src/calculators/volume.js

import { isPositiveNumber } from '../validators';
import { InvalidArgumentException } from '../exceptions';

export const sphere = radius => {
    if (!isPositiveNumber(radius)) {
        throw new InvalidArgumentException('radius must be a positive number');
    }

    return (4/3) * Math.PI * Math.pow(radius, 3);
};

然后在我的测试中:

测试/计算器/volume.test.js

import { volume } from '../../src/calculators/volume';
import { InvalidArgumentException } from '../../src/exceptions';
import { isPositiveNumber } from '../../src/validators';

jest.mock('../../src/validators');

describe('Volume calculations', () => {
    describe('sphere()', () => {
        it('should throw an exception if the radius is invalid', () => {
            isPositiveNumber.mockReturnValue(false);
            expect(() => volume()).toThrow(InvalidArgumentException);
        });

        it('should compute the volume', () => {
            isPositiveNumber.mockReturnValue(true);
            expect(volume(3)).toBeCloseTo(113,3);
        });
    });
});

这行得通,除了,我不想在实际计算音量的第二个测试中模拟 isPositiveNumber

我希望 isPositiveNumber 模拟仅在验证测试中。

鉴于我正在使用的 ES6 模块设置,我不知道该怎么做。似乎需要在测试范围之外进行模拟拦截,这意味着我必须在套件中的每个测试中模拟返回值。

这只是一个简单测试的例子,但以后会有更复杂的测试,我想知道如何在每个测试的基础上更精确地模拟 ES6 模块。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript unit-testing jestjs es6-modules


    【解决方案1】:

    这可能是因为您使用的是babel-jest,而according to the documentation 会将jest.mock() 提升到顶层,而不管它实际放置在ES6 模块代码中的什么位置。

    使用babel-jest 时,对mock 的调用将自动提升到代码块的顶部。

    相反,您可以在 before()after() 挂钩中分别使用 jest.doMock()jest.dontMock() 方法,用于需要模拟模块定义中的函数的单独测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 2017-11-11
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      相关资源
      最近更新 更多