问题
I have a component which when created extracts a parameter from url
and launches a query.
ngOnInit() {
....
this.id = this.route.snapshot.paramMap.get("my-id");
console.log("will query db for question with id " + this.id);
this.myService.getId(this.id)
}
I want to unit-test the component but I can't figure out how to set the url
before TestBed
creates this component.
The url should be of format
{
path:'id-details;my-id=:id',// for eg id-details;my-id=1
component:MyComponent
},
I thought I could set the route in beforeEach
but that isn't working
beforeEach((done) => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
let router = TestBed.get(Router);
let location = TestBed.get(Location);
router.navigateByUrl("/id-details;my-id=1");
});
fit('should create', () => {
expect(component).toBeTruthy();
});
In above spec, the component gets created but I don't get id. I tried extracting params in the followinng two ways but I always get null
this.id = this.route.snapshot.paramMap.get("my-id"); //get null
and
this.id = this.route.snapshot.paramMap.get("id-details"); //get null
I also see the following error in the console
context.js:1972 Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?
Unhandled Promise rejection: Cannot match any routes. URL Segment: 'question-details;question-id=1' ; Zone: ProxyZone ; Task: Promise.then ; Value: Error: Cannot match any routes. URL Segment: 'question-details;question-id=1'
回答1:
Try this:
spyOn(component.route.snapshot.paramMap,"get").and.returnValue("some_id")
Or:
let fake_value = "value";
spyOn(component.route.snapshot.paramMap,"get").and.callFake(()=>{
return fake_value;
});
fake_value = "another";
component.someMethod();
expect(...).toBe("another");
fake_value = "then_";
component.someMethod();
expect(...).toBe("then_");
来源:https://stackoverflow.com/questions/54753695/how-to-set-a-route-before-a-component-is-created-in-unit-test