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

not*_*eek 12 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>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,确实发生了错误:Function FunctionThatDoesNotExistsInString does not exists in string..然而,它并没有被捕获为Jest中的传球.

这是我的代码:

test(`
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  `, () => {
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  }
);
Run Code Online (Sandbox Code Playgroud)

小智 17

expect(fn).toThrow()需要一个功能fn是,调用时,抛出异常.

但是,您正在调用CheckFunctionExistenceByStrimmediatelly,这会导致函数在运行assert之前抛出.

更换

test(`
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  `, () => {
    expect(CheckFunctionExistenceByStr(
      'any string', 'FunctionThatDoesNotExistsInString'
    )).toThrow();
  }
);
Run Code Online (Sandbox Code Playgroud)

test(`
    expect(() => {
      CheckFunctionExistenceByStr(
        'any string', 'FunctionThatDoesNotExistsInString'
      )
    }).toThrow();
  `, () => {
    expect(() => {
      CheckFunctionExistenceByStr(
        'any string', 'FunctionThatDoesNotExistsInString'
      )
    }).toThrow();
  }
);
Run Code Online (Sandbox Code Playgroud)


小智 9

有类似的问题,但我要测试的函数是异步的,因此您的期望必须如下所示:

await expect(async () => {await myFunctionToBeTested();}).rejects.toThrow('My Error message')

我从这里得到的解决方案

笔记:

我添加了预期之前的等待,因为 Eslint 正在抱怨,但没有它也可以工作。


leo*_*ess 6

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

expect(youFunction(args)).toThrow(ErrorTypeOrErrorMessage)
Run Code Online (Sandbox Code Playgroud)

做这个:

expect(() => youFunction(args)).toThrow(ErrorTypeOrErrorMessage)
Run Code Online (Sandbox Code Playgroud)

  • 我认为他们应该将其添加到他们的文档中。 (2认同)