Angular 9
我有一个函数async
,用wait调用另一个函数,如下所示。
async hoge() {
for (let i = 0; i < 10; i++) {
this.piyo(i);
}
for (let i = 0; i < 10; i++) {
await this.fuga(i);
}
}
fuga(idx: number) {
return new Promise((resolve, reject) => {
if (idx < 5) {
resolve();
} else {
reject();
}
});
}
piyo(idx: number) {
return;
}
我尝试为函数async hoge()
添加单元测试,以检查piyo()
和fuga()
在执行时被调用了10次。
piyo()
,正常功能测试正常,但fuga()
不正常;显示错误
预计特务fuga已被呼叫10次。它被调用了1次。
it("fuga called 10 times from hoge func", () => {
// spy function which will return Promise
const spyObj = spyOn(component, "fuga").and.callFake(() => {
return Promise.resolve();
});
component.hoge();
expect(spyObj).toHaveBeenCalledTimes(10);
});
it("piyo called 10 times from hoge func", () => {
const spyObj = spyOn(component, "piyo");
component.hoge();
expect(spyObj).toHaveBeenCalledTimes(10);
});
考虑到这种情况,async
使该测试失败。但是我不知道如何修改这个测试代码。如果有人能给我任何想法,我将不胜感激。
这是堆栈上的全部代码
https://stackblitz.com/edit/angular-unit-tests-uxwzw1?file=src%2Fapp%2Fapp.component.spec.ts
谢谢
您的测试不起作用,因为代码是异步执行的(在本例中是因为promise(。
Angular拥有测试异步代码fakeAsync
和tick
的工具。您可以用fakeAsync
包装测试,然后使用tick
来指示异步执行。
it("fuga called 10 times from hoge func", fakeAsync(() => {
// spy function which will return Promise
const spyObj = spyOn(component, "fuga").and.callFake(() => {
return Promise.resolve();
});
component.hoge();
tick();
expect(spyObj).toHaveBeenCalledTimes(10);
}));