【发布时间】:2022-01-10 13:01:03
【问题描述】:
我有以下 Angular 服务方法
updateStorage(): void {
this.authServiceRef = this.authService.authRequest('storage', {}).subscribe((result) => {
this.storage = this.buildStorage(result);
this.storageUpdate.emit({ ...this.storage });
});
}
并且面临测试那段代码的困难
我的测试看起来像
fit('Update Storage Status', inject([AuthService], fakeAsync((authService: AuthService) => {
spyOn(authService, 'authRequest').and.returnValue(Observable.of(storageStatus_50GB_LowUsageTest));
spyOn(storageService, 'buildStorage');
spyOn(storageService.storageUpdate, 'emit');
storageService.updateStorage();
tick(1000);
expect(authService.authRequest).toHaveBeenCalledOnceWith('files', 'storage', {});
expect(storageService.buildStorageStatus).toHaveBeenCalledTimes(1);
expect(storageService.storageStatusUpdate.emit).toHaveBeenCalledTimes(1);
// FAILS - storageService.storage is undefined
expect(storageService.storage.size).toEqual(storageStatus_50GB_LowUsageTest.size)
expect(storageService.storage.maximum).toEqual(storageStatus_50GB_LowUsageTest.maximum);
expect(storageService.storage.usedPercentage).toEqual(0.4)
expect(storageService.storage.storageUsedSafeRound).toEqual(4);
})));
所有间谍调用都很好并且它们通过了,但是 storageService.storage 是 undefined
如何测试订阅函数中的代码?
【问题讨论】:
-
这能回答你的问题吗? Unit testing an observable in Angular 2
标签: angular unit-testing testing jasmine jasmine-async