问题描述
我正在尝试使用茉莉花来编写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() { }
}
我的Spec文件,
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();
});
});
但是我遇到了以下错误,
But I'm getting the following error,
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进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!