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

2024-05-22

我的 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 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'));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Jasmine:期望在异步函数中抛出错误 的相关文章

随机推荐