Unit testing 单元测试如何反应组件shouldComponentUpdate方法

Unit testing 单元测试如何反应组件shouldComponentUpdate方法,unit-testing,reactjs,enzyme,Unit Testing,Reactjs,Enzyme,我有一个React组件来实现这个方法,我想对它进行单元测试。理想情况下,我可以在单元测试中更改组件的某些属性或状态,并验证它是否重新呈现。我正在使用if,如果有帮助的话。我可能会直接调用shouldComponentUpdate 差不多 const comp = shallow(<Comp {...props} />) const shouldUpdate = comp.instance().shouldComponentUpdate(nextProps, nextState) ex

我有一个React组件来实现这个方法,我想对它进行单元测试。理想情况下,我可以在单元测试中更改组件的某些属性或状态,并验证它是否重新呈现。我正在使用if,如果有帮助的话。

我可能会直接调用shouldComponentUpdate

差不多

const comp = shallow(<Comp {...props} />)
const shouldUpdate = comp.instance().shouldComponentUpdate(nextProps, nextState)
expect(shouldUpdate).toBe(true/false)
const comp=shallow()
const shouldUpdate=comp.instance().shouldComponentUpdate(nextProps,nextState)
expect(shouldUpdate).toBe(真/假)
试图通过确定组件是否实际渲染/未渲染来进行测试可能比它的价值更麻烦;我甚至不知道用酶怎么做。您不能真正停止渲染输出,因为您可能不会从shouldComponentUpdate返回false,除非渲染输出与以前相同。因此,确定渲染是否发生不能仅从输出来进行


直接调用它进行测试对我来说似乎很好。只要您相信React将正确使用您的shouldComponentUpdate返回值(如果它不正确,我们会有更大的问题),它是安全的。

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

如中所述,您可以使用
setProps
setState
,至少对我来说,这可能是一种更好的方法,可以在更新相关值时从组件中获得准确的结果

在您的
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);

});
从'chai'导入{expect};
从“sinon sandbox”进口sinon;
从“酶”导入{shall};
它('更改状态或道具时更新',()=>{
常量包装器=浅();
const shouldComponentUpdate=sinon.spy(MyComponent.prototype,“shouldComponentUpdate”);
expect(shoulldcomponentupdate).to.have.property('callCount',0);
setProps({propThatWillUpdateTheComp:'foo'});
//或者,如果您正在测试状态更改情况下的组件更新
//setState({statethawillupdatethecomp:'bar'});
expect(shoulldcomponentupdate).to.have.property('callCount',1);
expect(shoulldcomponentupdate.returned(true)).to.be.equal(true);
});

我不认为你说的是单元测试,是吗?理想情况下,您应该能够单独测试
shouldComponentUpdate
。是否可以使用mount监视shouldComponentUpdate@我不知道。mount并不是真正用于单元测试的。如果逻辑在shouldComponentUpdate中特别复杂/重要,则shouldComponentUpdate始终可以从文件中导出函数并单独测试它,然后shouldComponentUpdate也将调用该函数。