reactjs - Shallow test React branch Jest and Enzyme -
there 3 things want figure out. using shallow render. use enzyme , jest.
- i wondering how can test branches in react component. test both sides of if-else statement (? :). , not want pull out in own function.
- how can check if this.props.myfuncfromprops(value) been called when input changes?
- what best practice test mapstatetoprops , mapdispatchtoprops?
here example of how component like:
import react 'react'; import mychildcomponent 'wherever'; // component input field in example export class mycomponent extends react.component { render() { const myfunc(value) { this.props.myfuncfromprops(value); } return ( <div> { this.props.istrue ? <mychildcomponent value={this.props.value} onchange={(value) => myfunc(value)} /> : null } </div> ); } }
to test different states render component different attributes , make snapshot (note, have check first time snapshot created). test event callback, have pass spy function (jest.fn()
) component , use simulate
call event, test spy called.
describe('mycomponent', () => { describe('with istrue true', () => { let mycomponent let myfuncfromprops beforeeach(() => { myfuncfromprops = jest.fn() mycomponent = shallow( <mycomponent istrue myfuncfromprops={myfuncfromprops} /> ) }) it('renders correct', () => { expect(mycomponent).matchsnapshot() }) it('onchange call myfuncfromprops', () => { mycomponent .find('mychildcomponent') .simulate('onchange', 'somevalue') expect(myfuncfromprops).tohavebeencalledwith('somevalue') }) }) it('with istrue false renders correct', () => { const mycomponent = shallow(<mycomponent />) expect(mycomponent).matchsnapshot() }) })
Comments
Post a Comment