为什么 Jest 不应该抛出错误? [英] Why does Jest throw an error when it should not?

查看:24
本文介绍了为什么 Jest 不应该抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的功能:

const test = (match) => {
   if (match !== 'cat') {
     throw new TypeError()
   }
}

我的测试是:

describe('test', () => {
  it('must throw error'() => {
    try {
      test('cat')
    catch(err){
      expect(err).toStrictEqual(new TypeError())
    }
  }
}

但是测试通过了.它应该失败.为什么通过了?

But the test passed. It should fail. Why did it pass?

推荐答案

只有在未满足预期的情况下,测试才会失败.在您的情况下,因为没有抛出错误,所以甚至没有评估任何期望.因此测试通过.

Tests only fail if there is an unmet expectation. In your case, because no error is thrown, no expectation is ever even evaluated. Therefore the test passes.

要解决这个问题,要么:

To deal with this, either:

  1. 确保使用 expect.assertions 评估一个期望:

describe('test', () => {
  it('must throw error'() => {
    expect.assertions(1);
    try {
      test('cat')
    catch(err){
      expect(err).toStrictEqual(new TypeError())
    }
  }
}

使用 .toThrow 处理错误 期望而不是自己抓住它:

handle the error with a .toThrow expectation rather than catching it yourself:

describe('test', () => {
  it('must throw error'() => {
    expect(() => test('cat')).toThrow(TypeError)
  }
}

请注意,作为 Estus Flask 指出,这只能在构造函数或错误消息上断言.

Note that, as Estus Flask pointed out, this can only assert on either the constructor or the message of the error.

这篇关于为什么 Jest 不应该抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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