如何对 React Component 的 shouldComponentUpdate 方法进行单元测试

How to unit test React Component shouldComponentUpdate method

如果有帮助,我有一个实现 shouldComponentUpdate method and I'd like to unit test it. Ideally I could change some prop or state on the component in a unit test and verify it either re-rendered or not. I am using enzyme 的 React 组件。

我可能会直接调用 shouldComponentUpdate。

类似

const comp = shallow(<Comp {...props} />)
const shouldUpdate = comp.instance().shouldComponentUpdate(nextProps, nextState)
expect(shouldUpdate).toBe(true/false)

尝试通过确定组件是否实际 rendered/didn 不渲染来进行测试可能比它的价值更麻烦;我什至不确定您将如何使用酶来做到这一点。您不能真正脱离渲染输出,因为您可能不会从 shouldComponentUpdate return false 除非渲染输出与以前相同。因此,无法仅通过输出来确定是否发生了渲染。

不过,通过直接调用它进行测试对我来说似乎没问题。只要您相信 React 会正确使用您的 shouldComponentUpdate return 值(如果不正确,我们就会遇到更大的问题),它就是安全的。

当您已经知道结果是什么时,您可能不想将 shouldComponentUpdate 作为孤立函数进行测试。

正如在 documentation 中提到的,您可以使用 setPropssetState 这可能是 - 至少对我而言 - 一种更好的方法来期望组件的确切结果更新相关值时。

在你的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(<MyComponent />);

  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);

});