【发布时间】:2020-07-30 10:28:49
【问题描述】:
我有一个在 ngOnInit 中调用的方法。我想测试一下给定 ngOnInit 调用,然后触发 this.anotherService.methodToCall() 以及调用它的内容。
当我运行我的测试时,它似乎从来没有被调用过。我已经尝试了几种不同的方法来尝试这样做,但似乎没有任何效果。我是使用 Angular 和 observables 的新手,所以我可能会遗漏一些非常明显的东西。
组件的功能完全符合我的要求。因此,我基本上只是在询问有关测试此问题的最佳方法的建议。谢谢。
在component.ts中
readOnly items: Observable<TemplateItems[]> = this.itemsHandler.itemsState$;
ngOnInit(): void {
this.checkParams();
}
private checkParams() : void {
this.observableResult$ = combineLatest(this.items, this.activatedRoute.params]);
this.subscriptions.add(
this.observableResult$.subscribe(([items, params]) => {
// During tests I never get this far
this.anotherService.methodToCall(items, params);
)
)
}
在 spec.ts - 这是我想做的事情的一个例子,但再次不确定这是否是最好的方法。
...
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
...,
],
providers: [
AnotherService,
{
provide: ActivatedRoute,
useValue: {
params: of({}),
}
}
]
}).compileComponents()
});
...
describe('ngOnInit', () => {
it('should call anotherservice methodcall with filter items and params', fakeAsync (() => {
activedRoute.params = of ({ value: "TEST_VALUE"});
fixture.detectChanges();
...
tick();
expect(spyOfAnotherServiceMethodCall).toBeCalledWith(someItemsValue, { value: "TEST_VALUE"})
}
}))
【问题讨论】:
-
能否请您在
tick()之前显示代码,它可以让我们更好地了解案例。还有 - 您能否在ngOnInit方法中添加一个console.log并在activedRoute.params调用之前添加另一个console.log并分享首先调用哪个。