【发布时间】:2018-03-31 14:15:21
【问题描述】:
在我的 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:无法读取未定义的属性“参数”。
我应该如何模拟它?我是否误解了ActivatedRoute 的正确用法,应该更好地在我的组件中使用router.subscribe?我看到了一些复杂的例子,人们嘲笑快照本身,但对我来说它看起来过于复杂。
测试本身很简单:
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'];
});
}
显然我需要模拟激活的快照,但有更好的方法吗?
【问题讨论】:
-
我也尝试过类似
const fakeRoutes: Routes = [{path: 'info', data: { catalogId: '123' }, component: StatusComponent},]然后RouterTestingModule.withRoutes(fakeRoutes)。不确定是否支持这种语法。 -
你想在单元测试中使用它吗?如果是这样,您可以发布该代码
-
您得到未定义的参数,因为您的模拟正在模拟可观察的参数
this.route.params(返回一个可观察的)而不是快照this.route.snapshot.params(返回参数的对象) -
是的,谢谢。快照也使用了参数,所以我认为它应该足够聪明,可以理解我模拟了参数。这意味着如果我想同时模拟快照和参数,我需要复制和粘贴参数两次。无论如何,我昨天已经设法解决了,谢谢你的帮助。
标签: angular angular-test