无法读取 angular 中未定义的 属性 'params' 2

Cannot read property 'params' of undefined in angular 2

我们在代码中使用了路由参数。但是在 jasmine karma 中执行单元测试时,我们遇到了以下错误。

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)

请在下面找到我们的 ts 文件:

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

}

请在下面找到我们的规范文件:

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

}

改变

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

至:

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

注意:this对象不会引用您正在测试的组件。

我使用下面的代码及其对我的 angular2 单元测试的工作。

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