我一直遇到这个测试场景,其中我的ngOnInit
设置了触发某些内容的订阅。但是测试错误
Failed: You provided 'undefined' where a stream was expected
ngOnInit() {
this.form = this.fb.group({
search: this.fb.control(null),
location: this.fb.control(null)
});
// test that valueChanges works
this.form.valueChanges.pipe(
debounceTime(500),
switchMap((form) => {
// test that url params are set
this.queryParams['search'] = form.search;
return this.updateUrl('/search');
})
).subscribe((ret) => {
// how to test this: expect(updateUrl).toHaveBeenCalled();
updateUrl();
});
}
public updateUrl(url: string) {
return this.router.navigate([url], { queryParams: this.queryParams, queryParamsHandling: 'merge' });
}
那我们该如何测试
我已经尝试了很多事情,对我valueChanges
进行监视是没有意义的,因为我要测试的大多数代码都在switchmap中。但是,这就是我目前所拥有的:
const router = {
navigate: jasmine.createSpy('navigate')
};
providers: [
{ provide: Router, useValue: router }
]
it('update URL when the search input get a value', async(() => {
updateUrl = spyOn(component, 'updateUrl').and.callThrough();
fixture.detectChanges();
const input = fixture.nativeElement.querySelector('[formcontrolname=search]');
input.value = testTerms.search;
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(updateUrl).toHaveBeenCalled();
expect(router.navigate).toHaveBeenCalledWith(['/search']);
});
}));