angular - Jasmine:期望在异步函数中抛出错误

标签 angular unit-testing typescript jasmine angular2-services

我的 angular2 应用程序中有一个异步函数,我想为其编写单元测试。想象一下我的功能是这样的:

myFunc(a: int): Promise<void> {
    if (a == 1)
        throw new Error('a should not be 1');

    let body = {
        value: a
    };
    return apiService.patch('/url/', JSON.stringify(body)).toPromise();
}

现在,我正在考虑检查 if 条件。我尝试了以下代码;但是,这个测试总是失败,因为我的代码实际上不等待任何结果:

it('should throw error if a = 1', () => {
    expect(() => {
        mySerivce.myFunc(1);
    }).toThrow(new Error('a should not be 1'));
})

我不知道我应该如何为这些类型的逻辑编写单元测试...

最佳答案

现在 jasmine (3.3+) 原生支持:

https://jasmine.github.io/api/3.4/async-matchers.html

it('should...', async () => {
  await expectAsync(myService.myFunc(1))
    .toBeRejectedWith(new Error('a should not be 1'));
});

关于angular - Jasmine:期望在异步函数中抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44876306/

相关文章:

c# - 使用高级加密标准算法 (AES) 在 Typescript 中加密字符串并在 C# 中解密

Angular2 : Property 'controls' does not exist on type 'AbstractControl' . 通过索引访问格式数组中对象的 .control 时出错

angular - 如何检测 Material 菜单打开事件

angular - 如何加入angularfire2数据库

c# - 如何使用 HttpContext 创建单元测试以在方法内进行授权?

java - 单元测试什么

java - 安卓单元测试 : How to mock a listener that is sent as argument to an asynchronous method?

html - MySQL 到 InnerHtml Angular 7

javascript - 如何从文本区域元素中选择某些文本

javascript - 需要 Angular 部署应用程序服务器吗?