问题描述
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
的失败消息如下:
期望值!
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()
中创建一个函数.
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()
抛出时,其他任何都无所谓.
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无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!