Uns*_*Sam 6 jasmine rxjs angular
我有以下课程:
@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();
},
);
}
}
Run Code Online (Sandbox Code Playgroud)
我想编写一个单元测试,断言当调用launchTimer()时,将调用OtherService的notification方法。棘手的是,对计时器可观察值的订阅是直接在方法中完成的,这意味着我无法直接在单元测试中进行订阅来进行断言。
到目前为止,我想到的是以下测试,该测试失败了,因为断言是在订阅之前完成的:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
我尝试用async包装该函数,并且还使用了fakeAsync和勾选,但似乎没有任何效果。有什么想法我可以在做出断言之前等待订阅吗?
使用间隔和计时器测试可观察量可能很棘手,但试试这个,如果这不起作用,我也许也可以用不同的方式来做。
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
}));
});
Run Code Online (Sandbox Code Playgroud)
=====================编辑============================== =======
您要么必须公开subscriptions,要么提供一种公开方式来取消订阅该对象中的订阅。
| 归档时间: |
|
| 查看次数: |
11282 次 |
| 最近记录: |