Unit test: simulate a click event of a child component in the parent state using an enzyme

I have a parent component and a child component that is just a label element. When I click on a child, I need to call a function in the parent component. I expect it to be called, but the state will not change, and when I saw the coverage file, the function is not called.

** Updated: ** Code works for development. This is just a unit test that fails.

Here is my parent component

parent.js

export default class Parent extends Component { constructor(props) { super(props) this.state={clickedChild: false} this.handleChildClick = this.handleChildClick.bind(this) } handleChildClick(index) { this.setState({clickedChild:true}) } render(){ const self = this return( const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}] <div> {items.map(function(item,index){ return <ChildComponent onChildClick ={ self.handleChildClick.bind(null,index)} childItem={item} /> })} </div> )} } 

child component

 export default class ChildComponent extends Component { constructor(props) { super(props)} render(){ return( <label onClick={this.props.onChildClick}>{this.props.childItem.text} </label> ) } } 

unit test

 import chai from 'chai' import React from 'react' import ReactDOM from 'react-dom' import { mount, shallow } from 'enzyme'; import sinon from 'sinon' import Parent from '../Parent' import ChildComponent from '../ChildComponent' let expect = chai.expect describe('check click event on child()',()=>{ it('clicking menu item',()=>{ const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}] const wrapper = mount(<Parent items={items} />) console.log(wrapper.state('clickedChild')) // prints false wrapper.find(ChildComponent).last().simulate('click',1) // tried the following // wrapper.find(ChildComponent).last().simulate('click') console.log(wrapper.state('clickedChild')) // still prints false }) }) 
+6
source share
1 answer

I changed the binding in my parent component to

 <ChildComponent onChildClick ={() => self.handleChildClick(index)} childItem={item} /> 

There was also a function that I called in my parent component that called its method. (parent.js)

 handleChildClick(index) { this.setState({clickedChild:true}) this.props.handleClick(index) // i had forgotten to see the line. } 

As soon as I missed the above comment line in my test. everything worked as expected.

 it('clicking menu item', () => { const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}] const handleClickStub = sinon.spy() const wrapper = mount(<Parent items={items} handleClick={handleClickStub} />) console.log(wrapper.state('clickedChild')) // prints false wrapper.find(ChildComponent).last().simulate('click') expect(handleClickStub.calledOnce).to.be.true // successful console.log(wrapper.state('clickedChild')) // prints true }) 
+5
source

All Articles