Chai 未使用 async/await 捕获抛出的错误

Chai not catching thrown error using async/await

因为返回了一个 promise,Chai 没有捕获异常,我该如何解决这个问题?

这是我的测试。

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);
    });
});

这是我的代码。

class Class{
    async throwError(parameter) {
        try {
            if (!parameter) {
                throw Error('parameter required');
            }
        } catch (err) {
            console.log(err);
        }
    }
}

Chai 的消息。

AssertionError: expected [Function] to throw Error

但我可以在调用堆栈上看到这条消息。

(node:21792) UnhandledPromiseRejectionWarning: Error: Error: parameter required

expect().to.throw()只支持同步功能。对于异步功能,您需要使用 chai-as-promised.

例如

index.js:

export class Class {
  async throwError(parameter) {
    if (!parameter) {
      throw Error('parameter required');
    }
  }
}

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);
  });
});

单元测试结果:

  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                 
----------|---------|----------|---------|---------|-------------------