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

时间:2017-05-05 10:26:44

标签: javascript unit-testing reactjs jestjs

我在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!
  });
});

1 个答案:

答案 0 :(得分:0)

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

来模拟它
const handleRemove = jest.spyOn(Panel.prototype, 'handleRemove');
expect(handleRemove).toHaveBeenCalled();

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

但是原来的函数不会被调用。