使用柴期望抛出无法捕获承诺拒绝 [英] Using Chai expect throw not catching promise rejection
问题描述
我一直在寻找如何解决此问题的方法,但我测试过的所有解决方案均不适用于我的情况.
I have searched all around how to solve this, but all solutions I tested don't work in my case.
我有一个返回诺言的函数,我正在尝试使用Mocha和Chai进行测试.
I have a function that returns a promise, which I'm trying to test using Mocha and Chai.
我正在模糊参数,因此函数始终返回:
I'm fuzzing the parameter so the function always returns:
拒绝(拒绝原因")
reject('Rejection reason')
这是我要运行的测试:
describe('fuzzing tokenization with 1000 invalid values', () => {
it('should throw an error - invalid value', async () => {
for(var i=0; i <= 1000; i++){
var req = {
body: {
value: fuzzer.mutate.string('1000000000000000')
},
user: {
displayName: user
}
};
expect(await tokenizer.tokenize(req)).to.throw(Error);
}
});
});
测试失败:
错误:字符串无效值".被抛出,抛出一个错误:)
Error: the string "Invalid value." was thrown, throw an Error :)
我测试了一些更改,例如将Expect包装到函数中
I tested several changes like wrapping the expect into a function
expect(async()=> {...}).to.throw(Error);
expect(async () => { ...}).to.throw(Error);
和其他我发现的谷歌搜索.但是我无法使它正常工作.
and others I found googling. But I can't get this to work.
我想念什么?
推荐答案
expect().to.throw(Error)
仅适用于同步功能.如果您想要使用异步功能的类似功能,请查看 chai-as-promised
expect().to.throw(Error)
will only work for sync functions. If you want a similar feature using async functions take a look at chai-as-promised
import chaiAsPromised from 'chai-as-promised';
import chai from 'chai';
chai.use(chaiAsPromised)
var expect = chai.expect;
describe('fuzzing tokenization with 1000 invalid values', () => {
it('should throw an error - invalid value', async () => {
for (var i = 0; i <= 1000; i++) {
var req = {
body: {
value: fuzzer.mutate.string('1000000000000000')
},
user: {
displayName: user
}
};
await expect(tokenizer.tokenize(req)).to.eventually.be.rejectedWith(Error);
}
});
});
这篇关于使用柴期望抛出无法捕获承诺拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!