[英]Chai not catching thrown error using async/await
Because a promise is returned Chai doesnt catch the exception, how can I resolve this?因为返回了 promise 柴没有捕捉到异常,我该如何解决这个问题?
Here is my test.这是我的测试。
describe('test.js', function() {
it('Ensures throwError() throws error if no parameter is supplied.', async function() {
expect(async function() {
const instance = new Class();
await instance.throwError();
}).to.throw(Error);
});
});
Here is my code.这是我的代码。
class Class{
async throwError(parameter) {
try {
if (!parameter) {
throw Error('parameter required');
}
} catch (err) {
console.log(err);
}
}
}
The message from Chai.柴发来的消息。
AssertionError: expected [Function] to throw Error
But I can see this message on the call stack.但我可以在调用堆栈上看到这条消息。
(node:21792) UnhandledPromiseRejectionWarning: Error: Error: parameter required
expect().to.throw()
only support sync function. expect().to.throw()
仅支持同步 function。 For async function, you need to use chai-as-promised .对于异步 function,您需要使用chai-as-promised 。
Eg例如
index.js
: index.js
:
export class Class {
async throwError(parameter) {
if (!parameter) {
throw Error('parameter required');
}
}
}
index.test.js
: index.test.js
:
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { Class } from '.';
chai.use(chaiAsPromised);
describe('62596956', function() {
it('Ensures throwError() throws error if no parameter is supplied.', async function() {
const instance = new Class();
await expect(instance.throwError(null)).to.eventually.rejectedWith(Error);
});
});
unit test result:单元测试结果:
62596956
✓ Ensures throwError() throws error if no parameter is supplied.
1 passing (9ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 50 | 100 | 100 |
index.ts | 100 | 50 | 100 | 100 | 3
----------|---------|----------|---------|---------|-------------------
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.