简体   繁体   中英

jest onChange Unit test - React

I have this function onChange for which i write to a unit test.

<Checkbox
          onChange={ () => {
                if (this.props.showTab) {
                      this.showBox();
                   }
                  this.props.handleChange();
        }}/>

showBox() {
        this.setState({ showBox: true });
    }

I have tried with

it('onChange', () => {
        const component = mount(<View
            showTab={true}
            handleChange= {handleChange}
            />);
        const instance = component.instance();
        const mockSetStateFn = jest.fn();
        instance.setState = mockSetStateFn;
        component.find('input').at(0).simulate('change');
        component.instance().showBox();
        expect(instance.setState).toHaveBeenCalledWith({ showBox: true });
    });

It gives error “simulate” is meant to be run on 1 node. 0 found instead." How do i test it?

In this unit test you shouldn't find the input if you render the Checkbox. You should make it like this:

component.find(Checkbox).invoke('onChange')()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM