抛出错误但是Jest的`toThrow()`没有捕获错误

时间:2017-11-20 16:57:29

标签: javascript unit-testing ecmascript-6 jestjs

这是我的错误代码:

 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();
  }
);

2 个答案:

答案 0 :(得分:15)

:s3_credentials => "#{Rails.root}/config/aws.yml" 需要一个函数expect(fn).toThrow()在调用时会抛出异常。

但是你正在调用fn immediatelly,这导致函数在运行断言之前抛出。

替换

CheckFunctionExistenceByStr

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

答案 1 :(得分:5)

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

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

这样做:

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