问题描述
我正在尝试使用 jasmine 为 getCurrentNavigation().extras.state 编写单元测试.
I am trying to write unit test for getCurrentNavigation().extras.state using jasmine.
为了解决这个问题,我尝试了窥探这个路由器的方法.
To solve the issue, I have tried to spy this router method.
我的组件文件,
@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
Can anyone help me to resolve this issue. I'm using Angular 7.2
推荐答案
你可以使用 stub
&useClass
也可以在其他 spec
文件中重复使用,如果您可以在单独的文件和 export class RouterStub
中创建它,请尝试:
You can easily do it using stub
& useClass
which can be reused at other spec
files as well if you can create it in separate file and export class RouterStub
, try:
在 spec
文件中创建一个 stub
,它的方法与 Router
相同:
In spec
file create a stub
which will have same method as Router
:
class RouterStub{
getCurrentNavigation(){
return {
extras: {
state:{
locationId: 'someId',
locationName: 'someName'
}
}
}
}
}
并在 beforeEach()
块中:
describe('LocationListComponent ', () => {
let component: LocationListComponent ;
let fixture: ComponentFixture<LocationListComponent >;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
LocationListComponent
],
providers: [ {provide: Router, useClass: RouterStub}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LocationListComponent );
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
这篇关于如何在角度 7 中对 getCurrentNavigation().extras.state 进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!