【发布时间】:2019-02-18 18:57:26
【问题描述】:
我有一个组件,它在创建时会从 url 中提取一个参数并启动一个查询。
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)
}
我想对组件进行单元测试,但在TestBed 创建此组件之前,我不知道如何设置url。
网址应该是格式
{
path:'id-details;my-id=:id',// for eg id-details;my-id=1
component:MyComponent
},
我以为我可以在beforeEach 中设置路线,但那行不通
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();
});
在上面的规范中,组件被创建但我没有得到 id。我尝试通过以下两种方式提取参数,但我总是得到null
this.id = this.route.snapshot.paramMap.get("my-id"); //get null
和
this.id = this.route.snapshot.paramMap.get("id-details"); //get null
我还在控制台中看到以下错误
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'
【问题讨论】:
标签: angular6