在我的 Angular 4 组件中,我有类似的东西:
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.myId = this.route.snapshot.params['myId'];
}
我正在尝试创建一个假设如下所示的模拟:
class MockActivatedRoute extends ActivatedRoute {
public params = Observable.of({ myId: 123 });
}
我的测试失败了:
TypeError: Cannot read property 'params' of undefined.
我应该如何模拟它?我是否误解了 ActivatedRoute
的正确用法,应该更好地在我的组件中使用 router.subscribe
?我看到一些复杂的例子,人们 mock 快照本身,但对我来说它看起来过于复杂。
测试本身非常简单:
describe('ngOnInit', () => {
it('should set up initial state properly',
() => {
const component = TestBed.createComponent(MyComponent).componentInstance;
component.ngOnInit();
expect(component.myId).toEqual('123');
});
});
如果我只是将测试下的方法更改为如下所示 - 测试有效:
ngOnInit() {
//this.myId = this.route.snapshot.params['myId'];
this.route.params.subscribe(params => {
this.myId = params['myId'];
});
}
显然我需要模拟 Activated 快照,但是有更好的方法吗?
最佳答案
好的,我已经找到了如何以简单的方式模拟 ActivatedRoute 快照。这样的事情对我有用:
providers: [MyComponent, {
provide: ActivatedRoute,
useValue: {snapshot: {params: {'myId': '123'}}}
}
谢谢:)
关于angular - 如何模拟 route.snapshot.params?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46831630/