javascript - 用 jest/enzyme 模拟模块功能
问题描述
按照这个答案:Jest——模拟一个在 React 组件中调用的函数
我有这个测试(试图模拟fireAnalytics
导入的函数,如下所示:
mytest.test.js
`.import { fireAnalytics } from "@module/js-utils/lib";
jest.mock('@module/js-utils/lib', () => ({ fireAnalytics: jest.fn(() => 'hello!') }))`
`
it('renders component', () => {
const WrappedMyComponent = hoc(Foo);
const props = {};
const wrapper = mount(
<WrappedMyComponent {...props} />
);
const event = {
// target: {
// id: 'test'
// }
};
// simulate click should call `handleInputClick`
wrapper.find('input').props().onClick(event);`
零件
import { fireAnalytics } from "@module/js-utils/lib";
handleInputClick(e) {
// I need to mock this function. But currently the test
goes here and asks for the e.target.id
fireAnalytics({
event: "",
category: "",
action: `Clicked on the ${e.target.id} input`,
label: ""
});
// rest of the code ....
}
测试运行时出错
TypeError: Cannot read property 'id' of undefined
248 | event: "",
249 | category: "",
> 250 | action: `Clicked on the ${e.target.id} input`,
251 | label: ""
252 | });
253 |
任何帮助,将不胜感激。
解决方案
您需要使用酶模拟功能。在输入测试中模拟点击:
...
wrapper.find('input').simulate('click')
推荐阅读
- sql - BigQuery ML Standard Scaler“无法计算平均值”
- office-scripts - 当前 Javascript API 可用于所有 Excel 版本
- docker - 运行时出错 - docker-compose up for mac
- c++ - 如何让 surf2Dwrite 在 C++ CUDA 中正确编译
- ios - Xcode 测试:清理代码,即使停止
- scala - 如何在akka流中的akka客户端websocket中使用Flow.map
- python - 来自长数据格式的 Groupby 以避免夸大的计数
- c++ - 添加成员时,我的 SDL_Rect 结构出现错误 C3927、C3484、C3613、C3646、C2059 和 C2238
- html - 如何在 RWD 布局中正确使用宽度和高度属性?
- javascript - 如何将 400..900 之类的内容转换为从 400,500,600,700,800,900,1000 的数组中过滤值