How do you mock ActivatedRoute
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
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
.
I was facing the same problem using paramMap
instead of params
. This got it working for me, at least for the simplest case:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
import { ComponentToTest } from './component-to-test.component';
import { ActivatedRoute } from '@angular/router';
TestBed.configureTestingModule({
declarations: [ComponentToTest],
providers: [
{
provide: ActivatedRoute,
useValue: {
paramMap: Observable.of({ get: (key) => 'value' })
}
}
]
});