如何模拟route.snapshot.params? [英] How to mock route.snapshot.params?
问题描述
在Angular 4组件中,我有类似的东西:
In my Angular 4 component I have something like:
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.myId = this.route.snapshot.params['myId'];
}
我正在尝试创建一个看起来像这样的模拟:
And I'm trying to create a mock that suppose to look like follows:
class MockActivatedRoute extends ActivatedRoute {
public params = Observable.of({ myId: 123 });
}
我的测试失败:
TypeError:无法读取未定义的属性"params".
TypeError: Cannot read property 'params' of undefined.
我该如何模拟呢?我是否误解了ActivatedRoute
的正确用法,应该在组件中更好地使用router.subscribe
吗?我看到了一些复杂的示例,人们嘲笑了快照本身,但是对我来说,它看起来太复杂了.
How do I suppose to mock it? Have I misunderstood the proper usage of ActivatedRoute
and should better use router.subscribe
in my component? I saw some complicated examples where people mocked snapshot itself, however for me it looks overcomplicated.
测试本身非常简单:
describe('ngOnInit', () => {
it('should set up initial state properly',
() => {
const component = TestBed.createComponent(MyComponent).componentInstance;
component.ngOnInit();
expect(component.myId).toEqual('123');
});
});
如果我只是简单地将测试中的方法更改为如下所示,则测试有效:
If I simply change a method under the test to something like follows - the test works:
ngOnInit() {
//this.myId = this.route.snapshot.params['myId'];
this.route.params.subscribe(params => {
this.myId = params['myId'];
});
}
显然我需要模拟激活的快照",但是有更好的方法吗?
Obviously I need to mock Activated snapshot, but is there a better approach?
推荐答案
好,我发现了如何以简单的方式模拟ActivatedRoute快照.像这样的东西对我有用:
Ok, I've found how to mock ActivatedRoute snapshot in the simple way. Something like this works for me:
providers: [MyComponent, {
provide: ActivatedRoute,
useValue: {snapshot: {params: {'myId': '123'}}}
}
谢谢:)
这篇关于如何模拟route.snapshot.params?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!