【问题标题】:Chai not catching thrown error using async/awaitChai 没有使用 async/await 捕获抛出的错误
【发布时间】:2020-10-17 04:28:03
【问题描述】:

由于返回了一个 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);
        }
    }
}

柴发来的消息。

AssertionError: expected [Function] to throw Error

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

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

【问题讨论】:

  • 你弄明白了吗?我遇到了完全相同的问题,尝试了一些解决方案,但没有一个适合我。

标签: javascript node.js async-await try-catch chai


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-02-07
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2020-06-02
    • 2013-01-28
    • 2014-06-30
    • 2020-11-13
    相关资源
    最近更新 更多