enzyme find and select first instance of element

Viewed 6186

I am trying to siumlate a click on the first of three boxes.

My react code looks like this

const Boxes = (props) => {

   return (
     <div className="container">
        <div onClick={props.showMessage} className="box">One</div>
        <div onClick={props.showMessage} className="box">Two</div>
        <div onClick={props.showMessage} className="box">Three</div>
     </div>
   );
}

Then my jest code looks like this

it("shows a message if Box One is selected", () => {
    let wrapper = shallow(
        <Boxes
            {...props}
        />
    );

    wrapper.find('.box').simulate('click');
    expect(wrapper.contains('Box One Clicked')).toEqual(true);

});

This gives me the following error message

Method “simulate” is only meant to be run on a single node. 3 found instead.

Then when I try the following it doesn't work either and the test fails.

wrapper.find('.box').first().simulate('click');
expect(wrapper.contains('Box One Clicked')).toEqual(true);
1 Answers

There are multiple .box items, you have to select one of them, say the first one:

wrapper.find('.box').at(0).simulate('click');
Related