How to unit test a component that depends on parameters from ActivatedRoute?

The simplest way to do this is to just use the useValue attribute and provide an Observable of the value you want to mock. RxJS < 6 import { Observable } from ‘rxjs/Observable’; import ‘rxjs/add/observable/of’; … { provide: ActivatedRoute, useValue: { params: Observable.of({id: 123}) } } RxJS >= 6 import { of } from ‘rxjs’; … Read more

Testing error case with observables in services

You can simply mock Observable throw error object like Observable.throw({status: 404})and test error block of observable. const xService = fixture.debugElement.injector.get(SomeService); const mockCall = spyOn(xService, ‘method’).and.returnValue(Observable.throw({status: 404})); Update 2019 : Since some people are lazy to read comment let me put this here : It’s a best practice to use errors for Rxjs import { throwError … Read more

Angular 2 unit testing components with routerLink

You need to configure all the routing. For testing, rather than using the RouterModule, you can use the RouterTestingModule from @angular/router/testing, where you can set up some mock routes. You will also need to import the CommonModule from @angular/common for your *ngFor. Below is a complete passing test import { Component } from ‘@angular/core’; import … Read more

tech