【问题标题】:How can I make Jest test for a thrown error silently如何让 Jest 静默测试抛出的错误
【发布时间】: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')
  • toThrowtoThrowError 不接受 Error 作为参数。
  • 如果您还没有,我会在这里查看这些文档:jestjs.io/docs/en/expect.html#tothrowerror
  • 啊,所以他们确实接受了Error;否则,Visual Studio 告诉我,感谢您提供链接。不幸的是,虽然没有运气。测试仍在通过,但仍在控制台中打印错误的堆栈跟踪。

标签: reactjs typescript unit-testing testing jestjs


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以在断言错误时暂时删除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()
    })
    

    【讨论】:

      【解决方案3】:

      根据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)
      });
      

      您可能需要在 &lt;ErrorBoundary /&gt; 组件内挂载(我不确定...),但我会试试这个^,看看您有没有运气。

      【讨论】:

      • 投反对票,因为.simulateError 模拟组件内的错误(用于测试错误是否被componentDidCatch 正确捕获)。 OP 正在询问是否测试组件引发的错误
      猜你喜欢
      • 2020-12-07
      • 1970-01-01
      • 2020-07-31
      • 2020-10-22
      • 2019-09-26
      • 1970-01-01
      • 2020-11-21
      • 2019-08-02
      • 2018-09-24
      相关资源
      最近更新 更多