在ngOnInit中测试可观察的依赖模式

时间:2018-10-31 18:25:49

标签: angular unit-testing jasmine karma-jasmine

我一直遇到这个测试场景,其中我的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' });
}

那我们该如何测试

  • form.valueChanges有效
  • 已设置网址参数
  • updateUrl();每次都被调用
  • 使用'/ search'调用导航功能

我已经尝试了很多事情,对我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']);
    });
}));

0 个答案:

没有答案