【发布时间】:2019-12-29 17:13:12
【问题描述】:
我想测试该方法,shouldComponentUpdate,但我编写的测试没有捕捉到副作用。我该如何测试?
我已经尝试过这里提出的解决方案,但存在一些问题,我将在代码中显示:How to unit test React Component shouldComponentUpdate method
我尝试过使用shallow 而不是mount,但是当我这样做时,我的测试在这一点上失败了:
expect(shouldComponentUpdate).to.have.property("callCount", 1);
// AssertionError: expected [Function: proxy] to have a property 'callCount' of 1, but got 0
这是我的组件的shouldComponentUpdate 函数:
shouldComponentUpdate(nextProps, nextState) {
if (this.props.storageValue !== nextProps.storageValue) {
localStorage.setItem(constantFile.storageKey, nextProps.storageValue);
localStorage.setItem(constantFile.timestampKey, now());
this.setState({
newStorage: nextProps.storageValue
});
return true;
}
...
return false;
}
这是我的测试:
it("Test shouldComponentUpdate", () => {
/* eslint-disable one-var */
const wrapper = mount(
<Provider store={store}>
<MyComponent />
</Provider>),
shouldComponentUpdate = sinon.spy(CapitalHomeAccessPointContainer.prototype, "shouldComponentUpdate");
wrapper.setProps({
storageValue: true
});
expect(shouldComponentUpdate).to.have.property("callCount", 1);
expect(shouldComponentUpdate.returned(true)).to.be.equal(true);
expect(localStorage.getItem(constantFile.timestampKey)).to.equal(someExpectedTimestamp);
});
expect(shouldComponentUpdate).to.have.property("callCount", 1);
失败
AssertionError: expected false to equal true
为什么会这样?我认为shouldComponentUpdate 应该返回true?后来,我希望测试状态和本地存储的副作用,但我不明白这个错误。
【问题讨论】:
-
需要进行状态更改才能触发
shouldComponentUpdate。您还应该测试函数的结果,而不是如果它被调用。 -
我认为文档说,“使用 shouldComponentUpdate() 让 React 知道组件的输出是否不受当前状态或道具变化的影响。默认行为是在每个状态上重新渲染更改,并且在绝大多数情况下,您应该依赖默认行为”。
https://reactjs.org/docs/react-component.html#shouldcomponentupdate所以我认为如果在shouldComponentUpdate中指定,道具的变化也应该触发 true? -
您还提到要测试该功能的副作用。我也尝试这样做。 ```expect(wrapper.find("MyComponent").state("newStorage")).to.be.true; ``` 导致这个错误:``` AssertionError: expected false to be true ```
标签: javascript reactjs testing enzyme sinon