如何使Jest静默测试抛出的错误

时间:2019-02-18 16:41:42

标签: reactjs typescript unit-testing testing jestjs

我正在编写一个测试,断言如果提供了一个道具而不提供了另一个道具,则组件会抛出错误。

测试本身通过了,但是控制台仍然抱怨未捕获的错误,并打印了整个堆栈跟踪。有什么办法可以使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");
}

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

断言错误时,您可以暂时删除console.error实现,并在完成后将其恢复。

function toThrowSilently(fn: Function) {
  jest.spyOn(console, "error")
  console.error.mockImplementation(() => {})
  expect(fn).toThrow()
  console.error.mockRestore()
}

test('should throw', async () => {
  const app = () => throw new Error()
  toThrowSilently(app)
})

您还可以使用beforeEachafterEach回调在测试运行时掩盖错误

beforeEach(() => {
  jest.spyOn(console, "error")
  console.error.mockImplementation(() => {})
})

afterEach(() => {
  console.error.mockRestore()
})

test('should throw', async () => {
  const app = () => throw new Error()
  expect(app).toThrow()
})

答案 2 :(得分: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 />组件中安装(我不确定...),但是我会尝试这样做^,看看您是否有运气。