javascript - 从另一个文件模拟一个函数 - Jest

标签 javascript reactjs unit-testing jestjs

我正在为我的应用程序编写单元测试用例。有一个函数写在 Utils 部分并在所有文件中使用。我想在需要时模拟此 Utils 函数,但我无法这样做。

这是我的代码设置:

实用程序.js

> const getData = (name) => "Hello !!! " + name;
> 
> const getContact = ()=> return Contacts.mobile;
> 
> export {
>     getData,
>     getContact }

Login.js(使用 Utils.js)

    const welcomeMessage = (name) => {

    return getData(name);
    }

我的测试文件(Login.spec.js)

import { getData } from '../../src/utils';


jest.mock('getData', () => jest.fn())


describe('User actions', () => {

    it('should get username', () => {
        const value = 'Hello !!! Jest';
        expect(welcomeMessage('Jest')).toEqual(value);
    });

});

当我运行测试用例时出现此错误:

 Cannot find module 'getData' from 'Login.spec.js'

我试图在官方 Jest 文档和 SO 上找到解决方案,但找不到任何东西。我无法修复此错误并模拟此功能。

最佳答案

jest.mock(...) 的第一个参数必须是模块路径:

jest.mock('../../src/utils');

因为 utils 模块是您的代码,而不是第三个库,所以您必须学习 jest 的手动模拟: https://facebook.github.io/jest/docs/en/manual-mocks.html

如果你有这个文件:src/utils.js

你可以通过创建一个文件来模拟它:src/__mocks__/utils.js

此文件的内容是原始文件的复制,但将实现替换为 getData = jest.fn()

在您的测试文件上,只需调用:jest.mock('../../src/utils'); 在文件开头。

然后当你熟悉之后,你可以在 beforeEach() 中调用那个函数并调用它的计数器 jest.unmock('../../src/utils') ; 内幕 afterEach()

一个简单的思考方式是:

当你调用jest.mock('../../src/utils');时,这意味着你告诉jest:

hey if the running test meets the line require('../../src/utils'), don't load it, let load ../../src/__mocks__/utils.

关于javascript - 从另一个文件模拟一个函数 - Jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49359476/

相关文章:

reactjs - Redux Toolkit 问题,获取 Cannot destruct 属性,因为它未定义

reactjs - 打包应用程序时,带有Reactjs execFile的Electron错误

unit-testing - Grails 单元测试 "CreateAlias"不起作用

python - 在模拟中修补生成器

javascript - 选择自动完成建议后如何停止页面重新加载

JavaScript splice() 迭代时未定义索引

javascript - 我在哪里初始化 React 应用程序中的 Firebase 应用程序?

c# - 有没有办法计算忽略初始化时间的测试方法的运行时间?

javascript - 对象不是函数,在 jspdf 调用中

javascript - 在 firefox 附加面板中显示远程图像