【发布时间】:2020-09-04 23:20:18
【问题描述】:
Angular9
我想使用 jasmine/karma 测试组件。
但是我找不到在具有路由参数的组件上编写测试的方法(使用 getCurrentNavigation )。
实际组件如下
import { Router } from '@angular/router';
export class myComponent implements OnInit {
// parameters from previous page
param1: param1model;
param2: param2model;
param3: param3model;
constructor(
private router: Router,
....
) {
if (this.router.getCurrentNavigation().extras.state.data != undefined) {
this.param1 = this.router.getCurrentNavigation().extras.state.data.aaa;
this.param2 = this.router.getCurrentNavigation().extras.state.data.bbb;
this.param3 = this.router.getCurrentNavigation().extras.state.data.ccc;
}
}
当前的测试代码是
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { myComponent } from './myComponent';
import { RouterTestingModule } from '@angular/router/testing';
describe('myComponent', () => {
let component: myComponent;
let fixture: ComponentFixture<myComponent>;
let router: jasmine.SpyObj<Router>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule, RouterTestingModule],
declarations: [myComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(myComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
TestBed.resetTestingModule();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
如果我运行测试,我得到了
TypeError:无法读取 null 的属性“附加”
而且我知道它应该显示出来,因为这个 myComponent 必须接收参数 (param1,param2,param3)。
但我不知道如何接收这些参数。 在 Angular 官方文档中,我找不到任何关于这种情况的指南。
如果有人愿意与我分享知识,我将不胜感激
【问题讨论】: