我正在尝试使用 jasmine 为 getCurrentNavigation().extras.state 编写单元测试。
为了解决这个问题,我试图窥探这个路由器方法。
我的组件文件,
@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() { }
}
我的规格文件,
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();
});
});
但我收到以下错误,
TypeError: Cannot read property 'extras' of null
谁能帮我解决这个问题。我在用着Angular 7.2