【问题标题】:How to write a test case for a function where there is a if condition using jest如何使用 jest 为存在 if 条件的函数编写测试用例
【发布时间】:2018-12-16 05:20:50
【问题描述】:

我有一个像下面这样的 onUpdate 函数

onUpdate = data => {
    if (parseInt(data.quantity) < 1) {
        this.props.setErrorPopUp({
            message: 'You cannot set quantity to zero.Use delete actions',
            action: 'danger',
            time: '5000'
        })
    } else {
        this.props.formSubmitAttempt({
            product: data.id,
            quantity: data.quantity
        })
    }
}

我想用 jest 写一个测试来测试这两个场景。 由于我是开玩笑的新手,我该如何测试这种情况 谢谢

【问题讨论】:

  • 你有什么尝试吗?
  • 完全不是这个,我在教程中尝试了一些基本示例
  • 我不知道如何测试 if 条件
  • 你需要为它写2个单元测试。一个传递参数通过 if 路径,第二个传递参数通过 else 路径。我在我的回答中给出了例子

标签: reactjs jestjs


【解决方案1】:

您可以使用实例获取 onUpdate 函数并将 setErrorPopup 和 formSubmitAttempt 作为模拟传递。

const props = {
    setErrorPopUp: jest.fn();
    formSubmitAttempt: jest.fn();

}
const wrapper = shallow(<Component {...props} />
wrapper.instance().onUpdate({ quantity: 0});
expect(props.setErrorPopUp).toHaveBeenCalled();

wrapper.instance().onUpdate({ quantity: 3 });
expect(props.formSubmitAttempt).toHaveBeenCalled();

【讨论】:

猜你喜欢
  • 2019-04-24
  • 2023-02-01
  • 1970-01-01
  • 2021-08-06
  • 2021-06-20
  • 2019-05-26
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多