【问题标题】:How to trigger if(this.props!==nextProps) in componentwillreceiveprops in Unit Testing?如何在单元测试的componentwillreceiveprops中触发if(this.props!==nextProps)?
【发布时间】: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


【解决方案1】:

componentwillreceiveprops 应该是componentWillReceiveProps

【讨论】:

  • 谢谢,它会调用 if 语句吗?
猜你喜欢
  • 1970-01-01
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 2021-07-06
  • 2014-09-19
  • 2015-04-17
  • 2021-01-02
  • 1970-01-01
相关资源
最近更新 更多