我的 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/