[英]Jasmine Wait for Observable Subscription
我有以下課程:
@Injectable()
export class MyService {
private subscriptions: { [key: string]: Subscription } = {};
constructor(private otherService: OtherService) {
}
public launchTimer(order: any): void {
this.subscriptions[order.id] = timer(500, 300000).subscribe(
() => {
this.otherService.notify();
},
);
}
}
我想編寫一個單元測試,它斷言在調用 launchTimer()時,將調用OtherService的notify方法。 關於這一點的棘手之處在於,對計時器observable 的訂閱是直接在方法中完成的,這意味着我不能直接在單元測試中進行訂閱來進行斷言。
到目前為止,我想出的是以下測試失敗,因為斷言是在訂閱之前完成的:
class OtherServiceMock {
public notify(): void {}
}
describe('MyService', () => {
let otherService: OtherServiceMock;
let myService: MyService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: OtherService, useClass: OtherServiceMock },
],
});
otherService = TestBed.get(OtherService);
myService = TestBed.get(MyService);
});
it('launchTimer should call notify', () => {
spyOn(otherService, 'notify');
myService.launchTimer();
expect(otherService.notify).toHaveBeenCalled();
});
});
我試圖用async包裝函數,我還使用了帶刻度的fakeAsync但似乎沒有任何效果。 任何想法如何在做出斷言之前等待訂閱?
使用間隔和計時器測試 observables 可能很棘手,但試試這個,如果這不起作用,我也可以用不同的方式來做。
class OtherServiceMock {
public notify(): void {}
}
describe('MyService', () => {
let otherService: OtherServiceMock;
let myService: MyService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: OtherService, useClass: OtherServiceMock },
],
});
otherService = TestBed.get(OtherService);
myService = TestBed.get(MyService);
});
it('launchTimer should call notify', fakeAsync(() => {
// you're going to have to make `subscriptions` public for this to work !!
spyOn(otherService, 'notify'); // don't need to callThrough to see if it was called or not
myService.launchTimer({id: 1});
tick(501);
expect(otherService.notify).toHaveBeenCalled();
myService.subscriptions['1'].unsubscribe(); // kill the timer subscription
}));
});
==================== 編輯 ============================ ========
您要么必須公開subscriptions
要么提供一種公共方式來取消訂閱該對象中的訂閱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.