Cannot read property 'params' of undefined in angular 2

Partha Sarathi Ghosh picture Partha Sarathi Ghosh · Apr 5, 2017 · Viewed 10.5k times · Source

We have used route param in our code. But while performing unit testing in jasmine karma we are getting following error.

TypeError: Cannot read property 'params' of undefined
TypeError: Cannot read property 'params' of undefined
    at Object.<anonymous> (http://localhost:9876/base/src/test.ts:38586:20)
    at ZoneDelegate.713.ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1599:26)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts:82238:39)
    at ZoneDelegate.713.ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1598:32)
    at Zone.713.Zone.run (http://localhost:9876/base/src/polyfills.ts:1359:43)
    at Object.<anonymous> (http://localhost:9876/base/src/test.ts:81952:34)
    at attemptSync (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1950:24)
    at ZoneQueueRunner.QueueRunner.run (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1938:9)
    at http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1962:16
    at http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1905:9
    at http://localhost:9876/base/src/test.ts:14790:17
    at ZoneDelegate.713.ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1599:26)
    at AsyncTestZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts:81547:39)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/base/src/test.ts:82235:39)
    at ZoneDelegate.713.ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts:1598:32)

Please find our ts file below:

import { Component, OnInit, AfterViewInit, EventEmitter, Output } from '@angular/core';

export class MyComponent implements OnInit, AfterViewInit {


    constructor(private route: ActivatedRoute) {

  }

    ngOnInit(){
        this.route.params.subscribe(params => {
      this.instanceNumber = params['instanceNumber'];
      // console.log(`this.instanceNumber--- QS`, this.instanceNumber);
    });
    }

}

Please find our spec file below:

import { MyComponent } from './MyComponent.component';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute, Route, ActivatedRouteSnapshot, UrlSegment, Params, Data } from '@angular/router';

describe('MyComponent', () => {
    let id: string[] = ['123', '456'];
    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;


     beforeEach(async(() => {
        // let route: any = new MockActivatedRoute();
        // route.parent = new MockActivatedRoute();
        // route.parent.params = Observable.of({ id: 'testId' });

        TestBed.configureTestingModule({
            imports: [],
            providers: [{ provide: ActivatedRoute }],
            declarations: [MyComponent],
            schemas: [NO_ERRORS_SCHEMA],
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;

        this.route.params.subscribe((params) => {
            this.instanceNumber = params['12345'];
        });
        fixture.detectChanges();
    });

}

Answer

Mansur Haider picture Mansur Haider · Jan 11, 2018

I used the below code and its work for me for angular2 Unit Testing.

import { RouterTestingModule } from '@angular/router/testing';
import { ActivatedRoute, Route, ActivatedRouteSnapshot, Params} from '@angular/router';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Observable } from 'rxjs/Rx';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [....],
      imports: [RouterTestingModule.withRoutes([])],
      providers: [{
        provide: ActivatedRoute, useValue: {
          params: Observable.of({ id: 3 }),
          snapshot: {
            parent: {
              params: {
                id: 1
              }
            },
            paramMap: {
              get(name: string): string {
                return '';
              }
            }
          },
        }
      }],
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents();
  }));