angular - 如何模拟 route.snapshot.params?

标签 angular angular-test

在我的 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/

相关文章:

javascript - 传单将坐标转换为街道地址

css - Bootstrap Carousel 的问题(图像显示但不滑动/改变)

Angular Material - 表骨架占位符

angular - 拥有一个自定义类型有什么好处,它只是另一个自定义类型对象的数组

javascript - 在呈现 `Page` 之前获取数据异步

angular - 如何使用可观察服务测试组件错误处理

Mat-Menu 上 Angular-Material 的 Angular Testing

javascript - 引用错误 : customElements is not defined

jasmine - 如何在Jasmine和Angular中测试ngOnInit的代码逻辑

angular - 为什么我收到此错误 : NullInjectorError: R3InjectorError(DynamicTestModule)[MedicoService?