在Angular应用程序中,我在Error
中扔了Observable.subscribe()
。但是,在我的单元测试中,错误并没有被发现,而只是冒出气泡而使测试失败。
这是我要测试的代码:
ngOnInit() {
this.activatedRoute.queryParamMap
.subscribe(params => {
this.productType = params.get('auftragTyp');
if (!this.productType) {
this.router.navigate(['/conversations']);
throw new Error(`Missing product type!`);
}
});
}
这里是单元测试:
describe('TaskComponent', () => {
let component: TaskComponent;
let fixture: ComponentFixture<TaskComponent>;
let activatedRouteMock = { queryParamMap: new Subject<any>() };
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TaskComponent],
imports: [
RouterTestingModule,
BrowserAnimationsModule
],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteMock}
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TaskComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should NOT navigate to Conversations', fakeAsync(() => {
activatedRouteMock.queryParamMap.next(convertToParamMap({
order: 'tool',
partnerNr: '123'
}));
tick(); // wait for resolution
fixture.detectChanges();
expect(routerMock.navigate).toHaveBeenCalledWith(['/conversations']);
expect(component.ngOnInit).toThrowError('Missing product type!');
}));
});
我使用fakeAsync
和tick()
,因为我需要在测试中模拟来自ActivateRoute的不同的queryParams,因此使用Subject
然后使用fixture.detectChanges()
发出新的查询参数。
更新
尝试使用throwError
,但结果相同:
ngOnInit() {
this.activatedRoute.queryParamMap
.pipe(
map((p: ParamMap) => {
if (p.get('auftragTyp') !== null) {
return p;
} else {
this.router.navigate(['/conversations']);
throw new Error('Missing product type!');
}
})
)
.subscribe({
next: (params: ParamMap) => {
this.productType = params.get('auftragTyp');
// ...
}
});
}