具有笑话/酶的模拟模块功能

时间:2019-04-07 16:12:10

标签: 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 |

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

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

...

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