Jest 嘲笑没有在测试函数之外调用实现



我有一个第三方模块需要模拟(moment.js(。 我想在需要我正在测试的文件之前将实现设置为默认实现。 我模拟的唯一函数是模块的默认导出,因此我也将原型和静态成员分配给实际实现的原型和静态成员。

季节.js

import moment from 'moment';
export var currentSeason = getCurrentSeason();
export function currentSeasion() {
const diff = moment().diff(/* ... */);
// ...
return /* a number */;
}

__tests__/季节.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()返回 undefined。 当我进入moment()模拟功能时,mockConfig.mockImplundefined.

在导入季节之前,在测试文件中运行expect(moment()).toBeUndefined()但在任何测试之外.js也会运行模拟实现。

我一辈子都无法弄清楚为什么它仅在currentSeason初始化中不起作用.

我不知道这对其他人有多大用处,但我的解决方案是将我的模拟代码拉入它自己的/__mocks__/moment.js文件中。

const actual = jest.requireActual('moment'),
moment = jest.fn((...args) => actual(...args));
export default Object.assign(moment, actual);

最新更新