在 React 中,如何在父元素内的子元素中测试点击事件



我正在对component元素进行单位测试,对于使用jest的React应用程序,问题是我无法测试当子元素是时是否调用函数点击。使用jest.fn()模拟该功能。但是我仍然会遇到此错误Expected mock function to have been called.

组件:

import React, { Component } from 'react';
class Panel extends Component {
  static defaultProps = {
    title: 'No data',
    info: 'Please add some info!.'
  }
  handleRemove() {
    alert('Panel should be removed!');
  }
  handleShare(e) {
    e.preventDefault();
    alert('Panel info can shared on social media.');
  }
  render() {
    return (
      <div className="panel col-md-4 col-xs-6">
        <a href="#" className="panel-remove-btn" onClick={this.handleRemove}>Remove</a>
        <div>
          <h3 className="panel-title">{this.props.panel.title}</h3>
          <p className="panel-info">{this.props.panel.info}</p>
        </div>
        <div>
          <a className="panel-share-btn btn btn-primary" onClick={this.handleShare}>Share</a>
        </div>
      </div>
    );
  }
}
export default Panel;

组件单位测试:

import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import { shallow, mount } from 'enzyme';
import Panel from '../Panel/Panel';
describe('Panel', () => {
  let panel,
    panelData = {
      title: 'Sabrina girls!!',
      info: 'Some Sabrina best kitchen dishes'
    };
  beforeEach(() => {
    panel = shallow(<Panel panelDate={panelData} />);
  });
  it('renders as intended', () => {
    const component = renderer.create(<Panel panelData={panelData} />),
      json = component.toJSON();
    expect(json).toMatchSnapshot();
  });
  it('renders Panel title', () => {
    expect(panel.find('.panel-title').text()).toEqual('Sabrina girls!!');
  });
  it('renders Panel information', () => {
    expect(panel.find('.panel-info').text()).toEqual('Some Sabrina best kitchen dishes');
  });
  it('should remove the Panel', () => {
    const handleRemove = jest.fn();
    expect(panel.find('.panel-remove-btn').length).toEqual(1);
    // accessing the child element and simulate a click
    panel.first().find('.panel-remove-btn').simulate('click');
    expect(handleRemove).toHaveBeenCalled(); // <= "handleRemove" is not called even though I've defined it above and simulated a click event!
  });
});

问题是您创建了从未使用过的间谍。您需要测试Panel.prototype.handleRemove。因此,在渲染之前,您需要使用jest.spyOn

进行模拟。
const handleRemove = jest.spyOn(Panel.prototype, 'handleRemove');
expect(handleRemove).toHaveBeenCalled();

Panel.prototype.handleRemove = jest.spy()
expect(handleRemove).toHaveBeenCalled();

,但是原始功能将不会被调用。

最新更新