unit-testingreactjsreactjs-testutils

React Test Utils - Spy not called when a simulated click is performed -


I'm trying to simulate a click on a dom element in a react component and assert that a spy is called based on this. Here's the relevant part of the test (using karma, mocha, chai, sinon but I'm fairly sure that's irrelevant here):

const selectSpy = sinon.spy();
const component = TestUtils.renderIntoDocument(<SomeComponent onSelect={selectSpy} />);
TestUtils.Simulate.click(TestUtils.scryRenderedDOMComponentsWithTag(component, 'li'));
expect(selectSpy.called).to.be.ok;

and here's the react component:

render() {
    let { title , data, onSelect }  = this.props;
    console.log(this.props.onSelect); // This correctly logs out the spy
    return (
      <div>
        <ul>{data.map((row, i) => {
          return <li onClick={this.handle.bind(this,row)} key={i}>{row.title}</li>; })}
        </ul>
      </div>
    )
}

handle(row) {
    this.props.onSelect(row);
}

The test runs but the result is a failed test with the message "Expected false to be truthy". I can't see much wrong with the code - there are no errors and my spy is correctly passed. Is there something else I need to be doing?


Solution

  • TestUtils.Simulate.click expects a DOM element, but scryRenderedDOMComponentsWithTag returns an array of DOM elements.

    Try changing

    TestUtils.Simulate.click(TestUtils.scryRenderedDOMComponentsWithTag(component, 'li'));
    

    to

    TestUtils.Simulate.click(TestUtils.scryRenderedDOMComponentsWithTag(component, 'li')[0]);