反应性笑话酶功能称为test

问题描述 投票:1回答:1

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

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
    });
});

尝试过两种类型的期望,我的控制台日志值即将到来

console.log('clicked'); comes 

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

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

Expected: 1
Received: 0
reactjs testing jestjs enzyme
1个回答
0
投票

因此,代码的问题是当您模拟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。>>

© www.soinside.com 2019 - 2024. All rights reserved.