【问题标题】:Jest mocked implementation not being called outside of test function在测试函数之外没有调用 Jest 模拟实现
【发布时间】: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.mockImplundefined

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

我一辈子都想不通为什么它在 currentSeason 的初始化中不起作用。

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 1970-01-01
      • 2021-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-18
      • 2020-05-02
      • 1970-01-01
      • 2019-12-22
      相关资源
      最近更新 更多