I'm learning Angular and I want to do tests, but I'm stuck. I've got a function:
ngOnInit(): void { this.route.paramMap .switchMap((params: ParamMap) => this.SomethingService.getSomething(params.get('id'))) .subscribe(something => { this.something = something; this.doSomethingElse(); }); }
where
route: ActivatedRoute
and I want to test it but I don't know how to mock ActivatedRoute
It is pretty straightforward to mock the ActivatedRoute in the User component test file. All we have to do is to edit the providers list as follows: beforeEach(async(() => { TestBed. configureTestingModule({ declarations: [ UserComponent ], imports: [ RouterTestingModule, HttpClientTestingModule // ...
It carries the information about a route linked to a component loaded into the Angular app template. An ActivatedRoute contains the router state tree within the angular app's memory. Make sure to remove strict type warnings or error make sure to set “strict”: false under compilerOptions property in tsconfig. json file.
Router does redirecting, don't call APIs about "getting the route information". If you needed to subscribe to changes in route, use this. router . ActivatedRoute does all "get the query params, get current URL, etc".
The ActivatedRoute is the API that holds observable data that you can use to react to events with. You can subscribe to specific observable properties to get data from it asynchronously. The ActivatedRoute also contains ActivatedRouteSnapshot.
A simple way to mock ActivatedRoute
is this one:
TestBed.configureTestingModule({ declarations: [YourComponenToTest], providers: [ { provide: ActivatedRoute, useValue: { params: Observable.from([{id: 1}]), }, }, ] });
Then in your test it will be available and your function should work with this (at least the ActivatedRoute part)
You can get it with TestBed.get(ActivatedRoute)
in your it
functions if you want to stock it in a variable.
Don't forget to import Observable from rxjs/Rx
and not from rxjs/Observable
For anyone interested on how to properly do it with multiple properties, this is the way you define your mock class:
import { convertToParamMap } from '@angular/router'; import { Observable } from 'rxjs/Observable'; export class ActivatedRouteMock { public paramMap = Observable.of(convertToParamMap({ testId: 'abc123', anotherId: 'd31e8b48-7309-4c83-9884-4142efdf7271', })); }
This way you can subscribe to your paramMap
and retrieve multiple values - in this case testId
and anotherId
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With