reactjs - Shallow test React branch Jest and Enzyme -


there 3 things want figure out. using shallow render. use enzyme , jest.

  1. i wondering how can test branches in react component. test both sides of if-else statement (? :). , not want pull out in own function.
  2. how can check if this.props.myfuncfromprops(value) been called when input changes?
  3. 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

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -