【问题标题】:Error is thrown but Jest's `toThrow()` does not capture the error抛出错误,但 Jest 的 `toThrow()` 没有捕获错误
【发布时间】:2018-05-03 23:29:29
【问题描述】:

这是我的错误代码:

 FAIL  build/__test__/FuncOps.CheckFunctionExistenceByString.test.js
  ● 
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();


    Function FunctionThatDoesNotExistsInString does not exists in string.

      at CheckFunctionExistenceByStr (build/FuncOps.js:35:15)
      at Object.<anonymous> (build/__test__/FuncOps.CheckFunctionExistenceByString.test.js:12:51)
          at new Promise (<anonymous>)
          at <anonymous>

如您所见,确实发生了错误:Function FunctionThatDoesNotExistsInString does not exists in string.。但是,它不会在 Jest 中被捕获为传递。

这是我的代码:

test(`
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  `, () => {
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  }
);

【问题讨论】:

    标签: javascript unit-testing ecmascript-6 jestjs


    【解决方案1】:

    expect(fn).toThrow() 需要一个函数 fn在调用时会引发异常。

    但是,您立即调用CheckFunctionExistenceByStr,这会导致函数在运行断言之前抛出。

    替换

    test(`
        expect(CheckFunctionExistenceByStr(
          'any string', 'FunctionThatDoesNotExistsInString'
        )).toThrow();
      `, () => {
        expect(CheckFunctionExistenceByStr(
          'any string', 'FunctionThatDoesNotExistsInString'
        )).toThrow();
      }
    );
    

    test(`
        expect(() => {
          CheckFunctionExistenceByStr(
            'any string', 'FunctionThatDoesNotExistsInString'
          )
        }).toThrow();
      `, () => {
        expect(() => {
          CheckFunctionExistenceByStr(
            'any string', 'FunctionThatDoesNotExistsInString'
          )
        }).toThrow();
      }
    );
    

    【讨论】:

    【解决方案2】:

    是的,这只是 Jest 很奇怪。而不是这样做:

    expect(youFunction(args)).toThrow(ErrorTypeOrErrorMessage)
    

    这样做:

    expect(() => youFunction(args)).toThrow(ErrorTypeOrErrorMessage)
    

    【讨论】:

    • 谢谢!这帮助我拔掉了我所有的头发!
    • 我认为他们应该将此添加到他们的文档中。
    猜你喜欢
    • 2014-06-30
    • 2023-03-28
    • 2019-07-01
    • 2016-02-24
    • 2020-11-21
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2011-09-07
    相关资源
    最近更新 更多