Cannot read property 'params' of undefined in angular 2

11,536

Solution 1

Change

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

to:

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

Note : this object will not refer to the component you are testing.

Solution 2

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();
  }));
Share:
11,536
Partha Sarathi Ghosh
Author by

Partha Sarathi Ghosh

AngularJS is fun

Updated on July 27, 2022

Comments

  • Partha Sarathi Ghosh
    Partha Sarathi Ghosh almost 2 years

    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();
        });
    
    }