我正在为我的应用程序编写单元测试用例。有一个函数写在 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/