Angular9
I want to test component using jasmine/karma. But I cannot find the way to write test on component which has routing parameter ( using getCurrentNavigation
).
actual component is as below
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;
}
}
and current test code is
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();
});
});
If I run test, I got
TypeError: Cannot read property 'extras' of null And I know it should shows up because this
myComponent
must receive params (param1,param2,param3). But I don't know how I can receive these params. On Angular official document, I couldn't find any guides for such case.
I appreciate it if someone would share knowledge to me
Aucun commentaire:
Enregistrer un commentaire