Mocha-断言异常的断言功能 参考文献

问题描述

我正在尝试测试异步函数是否要抛出异常,但是我一直收到此错误

AssertionError: expected [Function] to throw an error

我在Chai的Assertion库中使用Mocha。

it('Throw an error',async () => {
    assert.throws(async () => {
        await retrieveException();
    },Error);

    const retrieveException = async () => {
        // code snippit
        throw new Error('This is an error');
    }
}

在检查抛出的异常,异步性质或同时检查两者时是否出错?

参考文献

我已经看过先前的问题here(其中一个答案通过了三个不同的库[assert和两个BDD方法]),但我无法解决问题。

This article也无济于事。

也没有来自Node.js的documentation article

解决方法

expect().to.throw(Error)仅适用于同步功能。如果您想要使用异步功能的类似功能,请查看chai-as-promised

例如

import chai,{ assert } from 'chai';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

describe('63511399',() => {
  it('Throw an error',async () => {
    const retrieveException = async () => {
      throw new Error('This is an error');
    };
    return assert.isRejected(retrieveException(),Error);
  });
});

单元测试结果:

  63511399
    ✓ Throw an error


  1 passing (29ms)
,

在 Node JS sins v10.0.0 中有:

assert.rejects(asyncFn[,error][,message])

用于检查异步函数中的异常,

使用 Mocha 将如下所示:

it('should tests some thing..',async function () {
  await assert.rejects(async () => {
    throw new Error('This is an error')
  },'Error: This is an error')
})