【发布时间】:2020-12-30 16:25:20
【问题描述】:
我有以下课程:
@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 方法。
棘手的是,对 timer 可观察对象的订阅是直接在方法中完成的,这意味着我不能直接在单元测试中进行订阅以进行断言。
到目前为止,我想出的是以下测试失败,因为断言是在订阅之前完成的:
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 和 tick 但似乎没有任何效果。 有什么想法可以在做出断言之前等待订阅吗?
【问题讨论】: