如何以静默方式对抛出的错误进行Jest测试

问题描述 投票:1回答:2

我正在编写一个测试来声明如果提供一个prop而不是另一个prop,组件会抛出错误。

测试本身通过,但控制台仍然抱怨未捕获的错误并打印整个堆栈跟踪。有没有办法让Jest停止打印这些信息,因为它会污染测试运行器并使其看起来像是失败了。

作为参考,这是我的测试:

it("throws an error if showCancel is set to true, but no onCancel method is provided", () => {
    // Assert that an error is thrown
    expect(() => mount(<DropTarget showCancel={ true }/>)).toThrowError("If `showCancel` is true, you must provide an `onCancel` method");
});

错误本身在这里抛出:

if(props.showCancel && !props.onCancel) {
    throw new Error("If `showCancel` is true, you must provide an `onCancel` method");
}
reactjs typescript unit-testing testing jestjs
2个回答
2
投票

我找到了我的问题here的一行答案。

添加spyOn(console, "error");(在期望错误的测试中)可以防止记录错误。


0
投票

基于Enzyme docs中的示例,看起来你应该断言组件抛出一个错误,如下所示:

it("throws an error if showCancel is set to true, but no onCancel method is provided", () => {
    // Assert that an error is thrown
    const wrapper = mount(<DropTarget showCancel={ true }/>))
    const error = new Error("If `showCancel` is true, you must provide an `onCancel` method") 
    expect(wrapper).simulateError(error)
});

您可能需要在<ErrorBoundary />组件中安装(我不确定...)但我会尝试这个^并查看您是否有运气。

© www.soinside.com 2019 - 2024. All rights reserved.