Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a Angular 4 component which uses router.paramMap

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

like image 542
Tatarao voleti Avatar asked Oct 19 '17 05:10

Tatarao voleti


People also ask

How do you write test cases for ActivatedRoute?

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).

What is Parammap in Angular?

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() .


2 Answers

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})) }
}
like image 126
Preethi Avatar answered Sep 16 '22 14:09

Preethi


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})
        }
      }
}
like image 35
333Matt Avatar answered Sep 17 '22 14:09

333Matt