Attempting to create a unit test for getCurrentNavigation().extras.state with jasmine.
To address the problem, the router method was spied on.
The component's file,
@Component({
selector: 'app-location-list',
templateUrl: './location-list.component.html',
styleUrls: ['./location-list.component.scss']
})
export class LocationListComponent implements OnInit{
locationId;
locationName;
constructor(private activatedRoute: ActivatedRoute, private router: Router) {
if (this.router.getCurrentNavigation().extras.state) {
this.locationId = this.router.getCurrentNavigation().extras.state.locationId;
}
if (this.router.getCurrentNavigation().extras.state) {
this.locationName = this.router.getCurrentNavigation().extras.state.locationName;
}
}
ngOnInit() { }
}
The Spec file,
describe('LocationListComponent ', () => {
let component: LocationListComponent ;
let fixture: ComponentFixture<LocationListComponent >;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
LocationListComponent
],
providers: []
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LocationListComponent );
component = fixture.componentInstance;
spyOn(Router.prototype, 'getCurrentNavigation').and.returnValues({ 'extras': { 'state': { 'locationId': 100, 'locationName': "UK" } } });
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Encountering the error message below:
TypeError: Cannot read property `extras` of null
In need of assistance to fix this issue. Developed using Angular 7.2