I m new to angular 4 and trying to test one of the angular 4 feature router.paramMap from unit tests, Reading route params in fallowing way and working as expected in my application.
constructor(private router:Router, private actRoute:ActivatedRoute) {
}
ngOnInit() {
this.router.paramMap.subscribe(params => {
params.get(id);
})
......
}
But while running unit test, i m getting error which says cannot call subscribe method of undefined even though i m passing passing route param as below.
{
provide: ActivatedRoute,
useValue: { params: Observable.of({id: 1}) }
}
Please suggest
Your code has a problem, in order to get a param from the URL, you have to write things in a different way.
For anyone needing tests on a component for when it does have a certain route param, and when it does not have it (as in
/product
and/product/:id
), the following works for me:The component:
The tests:
You need to provide
paramMap
instead ofparams
.paramMap
should be of typeParamMap
from@angular/router
, so normal object can be converted toParamMap
using the methodconvertToParamMap()
from@angular/routing
.You can provide the mock ActivatedRoute like below:
we're currently using this:
I am using a slightly different method of getting the params in my component:
And this is what worked for me in the jasmine test: