【问题标题】:Mock module function with jest/enzyme用 jest/enzyme 模拟模块功能
【发布时间】:2019-08-28 20:57:04
【问题描述】:

按照这个答案: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 |

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs mocking jestjs enzyme


    【解决方案1】:

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

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

    【讨论】:

    • 不知道为什么,但我必须评论这一行:wrapper.find('input').props().onClick();,以便simulate 工作。
    • 这是因为simulate('click') 已经调用了onClick()。直接调用onClick 不要注入事件(您的e)对象,simulate('click') 调度一个类型为“点击”的“事件”,在您的情况下有一个target (“输入”)。
    猜你喜欢
    • 2019-07-16
    • 2018-03-28
    • 2019-01-29
    • 2018-01-18
    • 2019-10-27
    • 2019-09-24
    • 2019-08-17
    • 2019-04-10
    • 2021-02-04
    相关资源
    最近更新 更多