首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >async函数,期望throw() sinon

async函数,期望throw() sinon
EN

Stack Overflow用户
提问于 2020-04-21 19:10:38
回答 1查看 262关注 0票数 0

我有课:

代码语言:javascript
复制
export class MyClass {

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

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

    // do something
   }

}

我想要检查函数get expects抛出。

代码语言:javascript
复制
expect(myClass.get.bind(parser, "test")).to.throw("name is eql 'test'");

但它不起作用。它是如何修复的?

EN

回答 1

Stack Overflow用户

发布于 2020-04-22 12:18:14

如果您只使用chai,则chai不支持在异步函数中抛出assert error。相反,您可以使用try/catch + async/await。另一种方法是使用chai-as-promised插件。

例如。

index.ts

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

index.test.ts

代码语言:javascript
复制
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'");
  });
});

单元测试结果和覆盖率报告:

代码语言:javascript
复制
  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                 
----------|---------|----------|---------|---------|-------------------
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61342139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档