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
Test Cases for ActivatedRoute it('getDataByNameAndID test case ', () => {route.snapshot.params.id = '2';route.snapshot.params.name = 'testParamChanged';fixture = TestBed. createComponent(MyComponent);component = fixture. componentInstance;fixture. detectChanges();expect(component.name).
ParamMaplinkA map that provides access to the required and optional parameters specific to a route. The map supports retrieving a single value with get() or multiple values with getAll() .
You need to provide paramMap
instead of params
. paramMap
should be of type ParamMap
from @angular/router
, so normal object can be converted to ParamMap
using the method convertToParamMap()
from @angular/routing
.
You can provide the mock ActivatedRoute like below:
import { convertToParamMap} from '@angular/router';
....
.....
{
provide: ActivatedRoute,
useValue: { paramMap: Observable.of(convertToParamMap({id: 1})) }
}
I am using a slightly different method of getting the params in my component:
this.id = this.route.snapshot.paramMap.get('id');
And this is what worked for me in the jasmine test:
{
provide: ActivatedRoute,
useValue: {
snapshot: {
paramMap: convertToParamMap({id: 1})
}
}
}
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