简体   繁体   中英

Test prevProps in componentDidUpdate in React via Jest

Having following code:

componentDidUpdate(prevProps: JsonInputProps) {
  if (prevProps.value !== this.props.value) {
    this.validateJsonSchema(this.props.value || '');
  }
}

and test code:

  it('componentDidUpdate should mount', () => {
    const onChange = jest.fn();
    const event = { target: { value: 'simulate-event' } };
    const wrapper = enzyme
      .shallow(<JsonInput onChange={onChange} onValueChange={mockOnValueChange}/>)
      .simulate('change', event);
    wrapper.setProps({ value: 'example' });
    expect(onChange).toBeCalled;
  });

and test coverage:

在此处输入图像描述

I got 'else path not taken' and I do NOT want to ignore the else path but dunno how to change props. Any idea?

To cover else case you can pass in same prop value along with possibly something else along with it so that it covers else case upon update.

  it('componentDidUpdate should mount', () => {
    const onChange = jest.fn();
    const event = { target: { value: 'simulate-event' } };
    const wrapper = enzyme
      .shallow(<JsonInput onChange={onChange} onValueChange={mockOnValueChange}/>)
      .simulate('change', event);
    wrapper.setProps({ foo: 'something' });
    expect(onChange).toBeCalled;
  });

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