【发布时间】: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