typescript - Angular[karma] 对 Observable 的异步测试
我尝试测试一个异步情况。我的组件:
ngOnInit(private service: MyService) {
this.isLoading = true;
this.service.getData().subscribe((data) => {
this.data = data;
this.isLoading = false;
});
}
如你所见,我将 loading 设置为 true,当数据被检查后,isLoading 变为 false。这就是我想要测试的。我尝试了 tick(),whenStable……我监视了 MyService 以返回带有 mockData 的 Observable,但我无法捕捉到 isLoading 为 true。
谢谢你的帮助。
答案#1
it('should ...', done => {
const dataMock = {};
spyOn(component['service'], 'getData').and.returnValue(of(dataMock);
component['service'].getData().pipe(delay(500)).subscribe(data => {
expect(component.data).toBe(dataMock));
expect(component.isLoading).toBeFalsy();
done();
});
expect(component.isLoading).toBeTruthy();
});
