【问题标题】:Mocha - Assert asynchronous function throws exceptionMocha - 断言异步函数抛出异常
【发布时间】:2020-08-20 18:44:40
【问题描述】:

我正在尝试测试 async 函数是否会引发异常,但我不断收到此错误:

AssertionError: expected [Function] to throw an error

我正在将 Mocha 与 Chai 的断言库一起使用。

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

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

在检查抛出的异常、异步性质或两者时,我做错了什么吗?

参考资料

我已经看过之前的问题here(其中一个答案通过三个不同的库 [断言和两个 BDD 方法]),但我无法得到一些工作。

This article 也没有多大帮助。

也不是来自 Node.js 的 documentation article

【问题讨论】:

    标签: node.js async-await mocha.js bdd chai


    【解决方案1】:

    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)
    

    【讨论】:

      【解决方案2】:

      在 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')
      })
      

      【讨论】:

        猜你喜欢
        • 2012-04-28
        • 2011-08-06
        • 1970-01-01
        • 2012-09-14
        • 2023-01-11
        • 2018-10-02
        • 2019-09-03
        • 2021-09-20
        • 2020-03-11
        相关资源
        最近更新 更多