异步函数期望throw()sinon

问题描述 投票:0回答:1

我上课:

export class MyClass {

   public async get(name: string): Promise<string> {

     if(name == "test") throw new Error("name is eql 'test'");

    // do something
   }

}

我想检查该函数是否得到期望的抛出。

expect(myClass.get.bind(parser, "test")).to.throw("name is eql 'test'");

但是它不起作用。如何解决?

typescript unit-testing sinon throw sinon-chai
1个回答
0
投票

如果仅使用chai,则chai不支持在异步函数中引发的断言错误。相反,您可以使用try/catch + async/await。另一种方法是使用chai-as-promised插件。

例如

index.ts

export class MyClass {
  public async get(name: string): Promise<string> {
    if (name === 'test') {
      throw new Error("name is eql 'test'");
    }
    return '';
  }
}

index.test.ts

import { MyClass } from './';
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

describe('61342139', () => {
  it('should pass', async () => {
    const myClass = new MyClass();
    try {
      await myClass.get('test');
    } catch (error) {
      expect(error).to.be.instanceOf(Error);
      expect(error.message).to.be.equal("name is eql 'test'");
    }
  });

  it('should pass too', async () => {
    const myClass = new MyClass();
    await expect(myClass.get('test')).to.be.rejectedWith("name is eql 'test'");
  });
});

带有覆盖率报告的单元测试结果:

  61342139
    ✓ should pass
    ✓ should pass too


  2 passing (12ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |      75 |       50 |     100 |      75 |                   
 index.ts |      75 |       50 |     100 |      75 | 6                 
----------|---------|----------|---------|---------|-------------------
© www.soinside.com 2019 - 2024. All rights reserved.