【发布时间】:2019-07-12 02:27:10
【问题描述】:
我正在编写一个测试来断言如果提供了一个 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");
}
【问题讨论】:
-
我相信你的 toThrowError 你需要在字符串前面加上 new Error('string')
-
toThrow和toThrowError不接受Error作为参数。 -
如果您还没有,我会在这里查看这些文档:jestjs.io/docs/en/expect.html#tothrowerror
-
啊,所以他们确实接受了
Error;否则,Visual Studio 告诉我,感谢您提供链接。不幸的是,虽然没有运气。测试仍在通过,但仍在控制台中打印错误的堆栈跟踪。
标签: reactjs typescript unit-testing testing jestjs