我有一个组件,该组件在创建时会从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)
}
我想对组件进行单元测试,但是在url
创建此组件之前我不知道如何设置TestBed
。
网址应为格式
{
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'
答案 0 :(得分:0)
尝试一下:
spyOn(component.route.snapshot.paramMap,"get").and.returnValue("some_id")
或者:
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_");