当在构造函数中直接创建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测试用例在这里,一个工作,另一个不工作。当在构造函数中直接创建ES6类的实例时,为什么Jest的toThrow不起作用?
发生故障的消息为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/await
检查在expect()
而不是在expect()
内创建一个函数。
这里发生了什么事?
答
这里
expect(new TestObject()).toThrow();
new TestObject()
计算第一,然后expect(...)
,然后...toThrow()
,按照operator precedence。当new TestObject()
抛出时,其他任何东西都无关紧要。
这就是为什么toThrow
预计将抛出一个功能:
expect(() => {
new TestObject();
}).toThrow();
这样可以try..catch
在内部被称为当包裹。
它在茉莉花toThrow
和Chai to.throw
声明中的作用类似。