本文介绍了如何对使用router.paramMap的Angular 4组件进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是角度4的新手,试图从单元测试中测试一个角度4特征router.paramMap,以下面的方式读取路径参数并在我的应用程序中按预期工作。

I m new to angular 4 and trying to test one of the angular 4 feature router.paramMap from unit tests, Reading route params in fallowing way and working as expected in my application.

constructor(private router:Router, private actRoute:ActivatedRoute) {
}

ngOnInit() {
    this.router.paramMap.subscribe(params => {
        params.get(id);
    })
......
}

但是在运行单元测试的时候,即使我通过传递路径参数,我也得到错误,表示无法调用未定义的订阅方法。

But while running unit test, i m getting error which says cannot call subscribe method of undefined even though i m passing passing route param as below.

{
  provide: ActivatedRoute,
  useValue: { params: Observable.of({id: 1}) }
}

请建议

推荐答案

您需要提供 paramMap 而不是 params paramMap 的类型应为 ParamMap 来自 @ angular / router ,所以普通对象可以使用方法 convertToParamMap() @angular转换为 ParamMap /路由

You need to provide paramMap instead of params. paramMap should be of type ParamMap from @angular/router, so normal object can be converted to ParamMap using the method convertToParamMap() from @angular/routing.

您可以提供如下的模拟ActivatedRoute:

You can provide the mock ActivatedRoute like below:

import { convertToParamMap} from '@angular/router';
....
.....

{
      provide: ActivatedRoute,
      useValue: { paramMap: Observable.of(convertToParamMap({id: 1})) }
}

这篇关于如何对使用router.paramMap的Angular 4组件进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 14:25