【发布时间】:2019-09-16 19:29:58
【问题描述】:
我有一个需要模拟的第 3 方模块 (moment.js)。在需要我正在测试的文件之前,我想将实现设置为默认实现。我要模拟的唯一功能是模块的默认导出,因此我也将原型和静态成员分配给实际实现的那些。
season.js
import moment from 'moment';
export var currentSeason = getCurrentSeason();
export function currentSeasion() {
const diff = moment().diff(/* ... */);
// ...
return /* a number */;
}
__tests__/season.js
import moment from 'moment';
jest.mock('moment');
const actualMoment = jest.requireActual('moment');
moment.mockImplementation((...args) => actualMoment(...args));
Object.assign(moment, actualMoment);
const { getCurrentSeason } = require('../season');
test('getCurrentSeason()', () => {
moment.mockReturnValue(actualMoment(/* ... */));
expect(getCurrentSeason()).toBe(1);
});
我通过调试确认mockImpelementation() 被正确调用,并且在测试中,它也被正确调用。但是,在currentSeason 的初始化中,moment() 返回未定义。当我进入 moment() 模拟函数时,mockConfig.mockImpl 是 undefined。
在测试文件中运行expect(moment()).toBeUndefined(),但在导入 season.js 之前的任何测试之外运行模拟实现。
我一辈子都想不通为什么它在 currentSeason 的初始化中不起作用。
【问题讨论】:
标签: javascript unit-testing jestjs