React Test Renderer模拟元素上的点击

时间:2016-11-21 15:40:19

标签: reactjs jestjs

我正在使用Jest v16.0.1,react-test-renderer v15.4.0和react-addons-test-utils v15.4.0测试React组件。

该组件已呈现一个按钮:

<button
    type="button"
    className="btn btn-lg btn-primary btn-danger"
    disabled={this.state.cancelButtonDisabled}
    onClick={() => this.handleCancel()}
    ref="cancelButton"
>Cancel</button>);

在我的测试中,我是这样渲染组件的:

const component = renderer.create(
    <MyComponent />
);

const instance = component.getInstance();
// This works but is ugly
component.toJSON().children[1].children[0].props.onClick();
// This doesn't work
ReactTestUtils.Simulate.click(instance.refs.cancelButton);

let tree = component.toJSON();
expect(tree).toMatchSnapshot();

模拟点击此按钮的推荐方法是什么?您可以遍历组件的JSON表示,但看起来它们应该是更好的方法。

在我使用ReactTestUtils.renderIntoDocument之前,您可以使用refs将组件的引用传递给ReactTestUtils.Simulate.click

我已经看到了这个问题 - How to interact with components rendered by ReactTestRenderer / Jest但我认为API已经改变,因为我的组件实例没有find()方法。

2 个答案:

答案 0 :(得分:6)

我找到了解决方案。由于您正在使用react,我假设onClick处理函数作为props的一部分传递给按钮。所以你可以通过按钮的道具来访问它。

component.root.findByType('button').props.onClick();

或者,如果您有多个按钮,则可以执行以下操作:

component.root.findByProps({className="btn btn-lg btn-primary btn-danger"}).props.onClick();

答案 1 :(得分:3)

可能为时已晚,但find是来自酶的API。关于您提到假定酶的问题的答案如评论中所述使用。

这样的事情应该有效。

<强> MyComponent.jsx

import React from 'react';

class MyComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      cancelButtonDisabled: false,
    };
  }
  handleCancel() {
    this.props.cancelAction();
  }
  render() {
    return (
      <button
        type="button"
        className="btn btn-lg btn-primary btn-danger"
        disabled={this.state.cancelButtonDisabled}
        onClick={() => this.handleCancel()}
        ref="cancelButton"
      >
        Cancel
      </button>
    );
  }
}

export default MyComponent;

<强> MyComponent.test.jsx

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

describe('Test MyComponent', () => {
  it('should be able to click the button', () => {
    const mockFunction = jest.fn();
    const element = mount(<MyComponent cancelAction={mockFunction} />);
    element.find('button').simulate('click');
    expect(mockFunction).toHaveBeenCalled();
  });
});
没有酶,它看起来就像这样。

<强> MyComponentWithoutEnzyme.test.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import MyComponent from './MyComponent';

describe('Test MyComponent', () => {
  it('should be able to click the button', () => {
    const mockFunction = jest.fn();
    const element = ReactTestUtils.renderIntoDocument(
      <MyComponent cancelAction={mockFunction} />,
    );
    const button = ReactDOM.findDOMNode(element);
    ReactTestUtils.Simulate.click(button);
    expect(mockFunction).toHaveBeenCalled();
  });
});
相关问题