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 }) })
source share