I think this may give you some idea.
//Component
class Child extends React.Component { render() { return <button onClick={this.handleChildOnClick} className="t-btn">{this.props.children}</button>; } handleChildOnClick() { this.props.onChildClick('foo'); } }
//Test
import { spy, stub } from 'sinon'; import { shallow } from 'enzyme'; describe('Child Component', () => { it('should check handle click', () => { spy(Child.prototype, 'handleChildOnClick'); const onChildClick = stub(); const wrapper = shallow(<Child onChildClick={onChildClick}>); wrapper.find(".t-btn").simulate('click'); expect(Child.prototype.handleChildOnClick.callCount).to.equal(1); }); it('should check onChildClick', () => { const onChildClick = stub(); const wrapper = shallow(<Child onChildClick={onChildClick}>); wrapper.find(".t-btn").simulate('click'); expect(onChildClick.callCount).to.equal(1); }); });
To test a parent with a child component
import { stub } from 'sinon'; import { shallow } from 'enzyme'; import Child from '../Components/Child'; describe('Parent Component', () => { it('should check handle click', () => { const onParentClick = stub(); const wrapper = shallow(<Parent onParentClick={onParentClick} />); wrapper.find(".t-btn").simulate('click'); expect(Child.prototype.handleChildOnClick.callCount).to.equal(1); }); it('should check onChildClick', () => { const onChildClick = stub(); const wrapper = shallow(<Child onChildClick={onChildClick}>); wrapper.find(Child).prop('onChildClick')('foo'); expect(onParentClick.callCount).to.be.equal(1); }); });
Only one component is simply being processed on the code, but I hope this can give you some meaning. Sorry if the syntax breaks anywhere.
source share