簡體   English   中英

Chai 沒有使用 async/await 捕獲拋出的錯誤

[英]Chai not catching thrown error using async/await

因為返回了 promise 柴沒有捕捉到異常,我該如何解決這個問題?

這是我的測試。

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

expect().to.throw()僅支持同步 function。 對於異步 function,您需要使用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                 
----------|---------|----------|---------|---------|-------------------

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM