【问题标题】:React jest enzyme function called testReact jest 酶功能称为测试
【发布时间】:2020-09-14 17:01:49
【问题描述】:

您好,我有一个简单的组件需要测试:

MyComponent.js-----

import React from 'react';
const MyComponent = (props) => {

  onClickHandler = () => {
     console.log('clicked');
     props.outsideClickHandler();
  }

  return (
     <div>
        <span className='some-button' onClick={onClickHandler}></span>
     </div>
  );
}

MyComponent.test.js----

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
    const onClickHandler = jest.fn();

    it('calls click event', () => {
      const wrapper = shallow(<MyComponent />);
      wrapper.find('.some-button').simulate('click');
      expect(onClickHandler.mock.calls.length).toEqual(1);  // tried this first
      expect(onClickHandler).toBeCalled(); // tried this next
    });
});

尝试了上面两种expect,我的控制台日志值来了

console.log('clicked'); comes 

但我的测试失败了,我得到了这个:

expect(received).toEqual(expected) // deep equality

Expected: 1
Received: 0

【问题讨论】:

  • 你能做一个codesandbox吗?
  • 您的onClickHandler&lt;MyComponent /&gt; 没有任何关联,因此不会被调用。

标签: reactjs testing jestjs enzyme


【解决方案1】:

因此,您的代码的问题在于,当您模拟click 事件时,您希望调用一个完全独立的模拟函数。您需要将模拟功能附加到组件。最好的方法是使用prototype。像这样:

it('calls click event', () => {
  MyComponent.prototype.onClickHandler = onClickHandler; // <-- add this line
  const wrapper = shallow(<MyComponent />);
  wrapper.find('.some-button').simulate('click');
  expect(onClickHandler.mock.calls.length).toEqual(1);
  expect(onClickHandler).toBeCalled();
  expect(onClickHandler).toHaveBeenCalledTimes(1); // <-- try this as well
});

更多潜在解决方案请参考this issue

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2020-09-21
    • 2020-07-15
    • 1970-01-01
    • 2019-04-21
    • 2020-02-25
    • 2021-08-30
    • 2017-11-26
    • 2018-02-24
    相关资源
    最近更新 更多