为什么在构造函数中直接创建 ES6 类的实例时 Jest 的 toThrow 不起作用? [英] Why Jest's toThrow won't work when create an instance of a ES6 class directly in the constructor?

查看:17
本文介绍了为什么在构造函数中直接创建 ES6 类的实例时 Jest 的 toThrow 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class TestObject {
  constructor(value) {
    if (value === null || value === undefined) {
      throw new Error('Expect a value!');
    }
  }
}

describe('test the constructor', () => {
  test('it works', () => {
    expect(() => {
      new TestObject();
    }).toThrow();
  });

  test('not work', () => {
    expect(new TestObject()).toThrow();
  });
});

这里有 2 个测试用例,一个有效,另一个无效.

2 Test cases here, one works and the other not.

not work 的失败消息如下:

● 测试构造函数 › 不工作

● test the constructor › not work

期待值!

 at new TestObject (tests/client/utils/aaa.test.js:4:11)
 at Object.<anonymous> (tests/client/utils/aaa.test.js:17:12)
     at Promise (<anonymous>)
     at <anonymous>
 at process._tickCallback (internal/process/next_tick.js:188:7)

为什么我需要将那个调用包装在一个函数调用中,当函数只返回一个普通值,甚至是一个 promise 时,我们不需要包装,我们可以使用 async/awaitexpect() 中检查,而不是在 expect() 中创建一个函数.

Why do I need to wrap that call in a function call, we don't need to wrap when the function just return a plain value, or even a promise, we can use async/await to check that in expect() rather than create a function inside expect().

这里发生了什么?

推荐答案

这里

expect(new TestObject()).toThrow();

new TestObject() 先求值,然后 expect(...),然后 ...toThrow(),按照使用 运算符优先级.当 new TestObject() 抛出时,其他任何事情都无关紧要.

new TestObject() is evaluated first, then expect(...), then ...toThrow(), in accordance with operator precedence. When new TestObject() throws, anything else doesn't matter.

这就是为什么 toThrow 需要一个应该抛出的函数:

This is why toThrow expects a function that is supposed to throw:

expect(() => {
  new TestObject();
}).toThrow();

这样就可以在被调用时在内部用 try..catch 包裹起来.

This way it can be wrapped with try..catch internally when being called.

它在 Jasmine toThrow 和 Chai to.throw 断言中的工作方式也类似.

It works similarly in Jasmine toThrow and Chai to.throw assertions as well.

这篇关于为什么在构造函数中直接创建 ES6 类的实例时 Jest 的 toThrow 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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