我们在代码中使用了路由参数。但是在 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();
});
}