问题
I have searched all around how to solve this, but all solutions I tested don't work in my case.
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')
Here's the test I'm trying to run:
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);
}
});
});
The test is failing with:
Error: the string "Invalid value." was thrown, throw an Error :)
I tested several changes like wrapping the expect into a function
expect(async () => { ...}).to.throw(Error);
and others I found googling. But I can't get this to work.
What am I missing?
回答1:
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);
}
});
});
来源:https://stackoverflow.com/questions/50412182/using-chai-expect-throw-not-catching-promise-rejection