How to unit test React Component shouldComponentUpdate method

后端 未结 2 658
春和景丽
春和景丽 2021-02-18 16:04

I have a React Component that implements the shouldComponentUpdate method and I\'d like to unit test it. Ideally I could change some prop or state on the component in a unit tes

2条回答
  •  無奈伤痛
    2021-02-18 16:26

    You probably dont want to test shouldComponentUpdate as isolated function when you already know what the outcome is.

    As it mentioned in the documentation you can use setProps or setState and this is probably - at least for me - a better approach to expect the exact outcome from your component when updating related values.

    In your MyComponent.test.js

    import { expect } from 'chai';
    import sinon from 'sinon-sandbox';
    import { shallow } from 'enzyme';
    
    it('updates when changing state or props', () => {
      const wrapper = shallow();
    
      const shouldComponentUpdate = sinon.spy(MyComponent.prototype, 'shouldComponentUpdate');
    
      expect(shouldComponentUpdate).to.have.property('callCount', 0);
    
      wrapper.setProps({ propThatWillUpdateTheComp: 'foo' });
    
      // or in case you are testing component update in case of state change
      // wrapper.setState({ stateThatWillUpdateTheComp: 'bar' });
    
      expect(shouldComponentUpdate).to.have.property('callCount', 1);
    
      expect(shouldComponentUpdate.returned(true)).to.be.equal(true);
    
    });
    

提交回复
热议问题