Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Test Renderer Simulating Clicks on Elements

Tags:

I'm testing a React component using Jest v16.0.1, react-test-renderer v15.4.0 and react-addons-test-utils v15.4.0.

The component has rendered a button:

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

And in my test I'm rendering the component like so:

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

What is the recommended way to simulate a click on this button? You can traverse the JSON representation of the component but it seems like their should be a better way.

Before when I was using ReactTestUtils.renderIntoDocument you could pass in a reference to the component using refs to ReactTestUtils.Simulate.click

I've seen this question - How to interact with components rendered by ReactTestRenderer / Jest but I assume the API has changed as my component instance has no find() method.

like image 317
Aaron Kalair Avatar asked Nov 21 '16 15:11

Aaron Kalair


People also ask

How can you simulate clicking on an element using react testing utilities?

Simulate a Click Event The onClick should pass through to the component's underlying <button /> element because we're spreading ( {... props} ) that props through to it. In the test, we create a ref so that we can pass it to the rendered Button and later to the Simulate. click call.

How do you simulate onClick in Jest?

To simulate a button click in Jest, we can call the simulate method. to call shallow to mount the Button component. Then we call find with 'button' to find the button element. And then we call simulate with 'click' to simulate a click on it.

Which is better enzyme or react testing library?

Enzyme allows you to access the internal workings of your components. You can read and set the state, and you can mock children to make tests run faster. On the other hand, react-testing-library doesn't give you any access to the implementation details.


1 Answers

I have found a solution. Since you are using react, I assume that the onClick handler function is passed to the button as a part of the props. So you can access it through button's props.

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

Or if you have more than one button, you can do this:

component.root.findByProps({ className: "btn btn-lg btn-primary btn-danger" }).props.onClick();
like image 56
Bohan Liu Avatar answered Sep 20 '22 09:09

Bohan Liu