引发错误,但Jest的`toThrow()`不能捕获错误 [英] Error is thrown but Jest's `toThrow()` does not capture the error

查看:74
本文介绍了引发错误,但Jest的`toThrow()`不能捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的错误代码:

 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>

您可以看到错误确实发生了:函数FunctionThatThatDoesNotExistsInString在字符串中不存在..但是,在Jest中并没有将其捕获为通行证.

As you can see the error did indeed occurred: Function FunctionThatDoesNotExistsInString does not exists in string.. However it is not captured as a pass in Jest.

这是我的代码:

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

推荐答案

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

expect(fn).toThrow() expects a function fn that, when called, throws an exception.

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

However you are calling CheckFunctionExistenceByStr immediatelly, which causes the function to throw before running the assert.

替换

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

这篇关于引发错误,但Jest的`toThrow()`不能捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆