繁体   English   中英

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

[英]In React, how to test the click event in child that's inside a parent element

我正在对component子元素进行单元测试,对于使用Jest的React应用程序,问题是我无法测试单击子元素时是否已调用函数。 该函数使用jest.fn()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();

但是原始函数将不会被调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM