首页 > 解决方案 > 如何在单元测试的componentwillreceiveprops中触发if(this.props!==nextProps)?

问题描述

我是 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 语句?先感谢您。

标签: reactjsunit-testingif-statementtriggersreact-lifecycle

解决方案


componentwillreceiveprops应该componentWillReceiveProps


推荐阅读