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

查看:99
本文介绍了当直接在构造函数中创建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)

为什么我需要在函数调用中包装该调用,而当该函数仅返回一个简单值甚至是一个承诺时,我们就不需要包装,我们可以使用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() 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天全站免登陆