我尝试测试异步情况。 我的组件:
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。
感谢您的帮助。
最佳答案
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();
});
关于Angular[karma] Observable 上的异步测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55218092/