【发布时间】:2018-11-16 10:59:45
【问题描述】:
我是 React 单元测试的新手。我对 if 语句有疑问。我需要测试componentwillreceiveprops的功能,我知道我可以使用spy = sinon.stub(component.props,"componentwillreceiveprops") 方法让spy被调用。
但是在我的组件中,有一个if语句,比如
componentwillreceiveprops(nextProps){
if(this.props.name!==nextProps.name) {
this.setState({
oldstate: newstate
})
}
}
我可以调用componentWillReceiveProps 函数。如果我删除 if 语句,也可以调用 setState 函数。但是我的组件中包含一个 if 语句,当我运行单元测试时它不会被调用。有什么方法可以调用这个 if 语句吗?提前谢谢你。
【问题讨论】:
-
对不起我的错字,应该是:this.setState({ oldstate: newstate });里面。
-
请注意 componentWillReceiveProps 已被弃用。应该替换它的 getDerivedStateFromProps 更容易测试。
标签: reactjs unit-testing if-statement triggers react-lifecycle