无法阅读财产' params'未定义的角度2

时间:2017-04-05 14:08:52

标签: unit-testing angular karma-jasmine karma-coverage routeparams

我们在代码中使用了路由参数。但是在茉莉因果报中进行单元测试时,我们会遇到以下错误。

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

}

2 个答案:

答案 0 :(得分:4)

更改

CharSet

为:

ByteBuffer

注意:this.route.params.subscribe((params) => { this.instanceNumber = params['12345']; }); 对象不会引用您正在测试的组件。

答案 1 :(得分:2)

我使用下面的代码及其工作对我进行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();
  }));