我有一个如下的函数:
async foo() : Promise<Object> {
if(...) throw new Error
}我该如何测试错误是否被抛出呢?目前我正在做这件事:
it("testing for error thrown", async function () {
expect(async() => await foo()).to.throw(Error)
})发布于 2021-09-15 15:09:55
您可以这样做,如果抛出错误,测试将失败。
const foo = async (): Promise<Object> => {
// If you want the test to fail increase x to 11
const x = 0
if (x > 10) {
throw Error('Test will fail')
}
// Add meaningful code this is just an example
return { some: 'object' }
}
it('testing for error thrown', async () => {
const object = await foo()
expect(object).toEqual({ some: 'object' })
})发布于 2021-09-15 16:26:11
试试这个:
it("testing for error thrown", async function () {
await expect(foo()).rejects.toThrow(Error)
})发布于 2021-09-15 17:45:00
由于您提到了chai-as-promised,因此您可以使用以下两种方法之一:
expect(promise).to.eventually.be.rejected
或者:
promise.should.be.rejected
还有rejectedWith(),它可以让你指定错误类/构造函数。
下面是一个演示:
mocha.setup('bdd');
mocha.checkLeaks();
let { expect } = chai;
chai.should();
let chaiAsPromised = module.exports; /* hack due to lack of UMD file, only for SO */
chai.use(chaiAsPromised);
async function foo(){
throw new Error();
}
describe('Asynchronous Function', function(){
it('Expect and Eventually', function(){
return expect(foo()).to.eventually.be.rejected;
})
it('With Should', function(){
return foo().should.be.rejected;
});
});
mocha.run();.as-console {
display: none !important;
}<script>
window.module = {}; function require(){ return {} }; /* hack due to lack of UMD file, only for SO */
</script>
<script src="https://cdn.jsdelivr.net/npm/chai-as-promised@7.1.1/lib/chai-as-promised.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/9.1.1/mocha.min.js"></script>
<script src="https://unpkg.com/chai@4.3.4/chai.js"></script>
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<div id="mocha"></div>
https://stackoverflow.com/questions/69195258
复制相似问题