【问题标题】:Module import undefined in jest test file笑话测试文件中未定义的模块导入
【发布时间】:2020-08-26 19:33:27
【问题描述】:

我正在尝试用 jest 对实用程序文件 (util.js) 进行单元测试,文件看起来像,

// utils.js

import { something } from '@whatever/nothing';

export const myMethod = (parameter) => {

    if (!something ) return 0;
    return something.length + parameter.length;
};

// utils.test.js

import { myMethod } from '../utils';

    test('myMethod', () => {
        expect(myMethod('whatever').toEqual(12);
    });

something 是模块,以“temp”值导出。

当我运行测试文件时,something 总是 undefined 并最终返回 0。在测试文件中模拟模块“something”并使其在测试运行中可用的正确方法是什么?

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    模拟something的方法是这样的:

    import { something } from '@whatever/nothing';
    import { myMethod } from '../utils';
    
    jest.mock('@whatever/nothing');
    something.mockReturnValue('temp');
    
    test('myMethod', () => {
      expect(myMethod('whatever').toEqual(12);
    });
    

    jest.mock('@whatever/nothing'); 创建模块的模拟。

    something.mockReturnValue('temp'); 创建将存在于某事物中的返回值。

    【讨论】:

    • something 不是函数,需要以其他方式模拟和测试。
    • 我刚刚使用mockReturnValue 修改了我的示例。这样,something 将成为一个字符串。
    • 不,它不会,因为 Jest 模拟不能像你期望的那样工作,JS 也不能那样工作。没有办法让something 之类的变量具有mockReturnValue 方法,使其等于something.mockReturnValue(12); expect(something).toBe(12) 之类的不同值。 Jest 间谍仅适用于函数(以及描述符访问器)。 something 不是函数。它是一个对象,用作something.length,而不是something()。尝试测试您建议的解决方案,您会看到。
    • 说我有导出函数 foo(){//something};那就是使用 es6 模块语法导入。我发现它在 jest 文件中也未定义。这个函数也应该被嘲笑吗? jest.mock("pathtofunction", () => { foo: jest.fn()});我觉得我们应该能够调用 foo() 而不必模拟它来断言输出。如果我们在模拟输出,那么模拟输出上的断言似乎毫无意义?
    猜你喜欢
    • 1970-01-01
    • 2019-01-07
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 2019-08-03
    • 2018-07-12
    • 1970-01-01
    相关资源
    最近更新 更多