javascript - 使用 jest/enzyme 模拟模块功能

标签 javascript reactjs mocking jestjs enzyme

以下答案:Jest -- Mock a function called inside a React Component

我有这个测试(尝试模拟 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 |

如有任何帮助,我们将不胜感激。

最佳答案

您需要使用 enzyme simulate功能。在输入测试中模拟点击:

...

wrapper.find('input').simulate('click')

关于javascript - 使用 jest/enzyme 模拟模块功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55561062/

相关文章:

javascript - %% GLOBAL_CustomerGroupId %%-范围

reactjs - 无法更新 react Hook 中 setInterval 内的状态

javascript - react 减少 : Getting error 'dispatch is not a function' during 'connect'

javascript - 数据从数据库中删除成功,但未刷新 AngularJS 中的当前页面

javascript - Protractor - 如何跳转到网格中的下一行并返回找到的值

javascript - 无法通过应用程序脚本从谷歌工作表获取值

javascript - React - 用户定义的 JSX 组件不呈现

c# - 使用 SWIG 从 C++ 生成 C# 接口(interface)

c# - 模拟非接口(interface)类

.net - 为 .Net 选择模拟框架时应该考虑什么