如何对依赖ActivatedRoute参数的组件进行单元测试? [英] How to unit test a component that depends on parameters from ActivatedRoute?

查看:113
本文介绍了如何对依赖ActivatedRoute参数的组件进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对用于编辑对象的组件进行单元测试。该对象具有唯一的 id ,用于从服务中托管的对象数组中捕获特定对象。特定的 id 是通过通过路由传递的参数(特别是通过 ActivatedRoute 类)获得的。

I am unit testing a component that is used to edit an object. The object has an unique id that is used in order to grab the specific object from an array of objects that are hosted in a service. The specific idis procured through a parameter that is passed via routing, specifically through the ActivatedRoute class.

构造函数如下:

 constructor(private _router:Router, private _curRoute:ActivatedRoute, private _session:Session) {
}

ngOnInit() {
    this._curRoute.params.subscribe(params => {
        this.userId = params['id'];
        this.userObj = this._session.allUsers.filter(user => user.id.toString() === this.userId.toString())[0];

我想对该组件运行基本的单元测试,但是我不确定关于如何注入 id 参数以及组件需要该参数。

I want to run basic unit tests on this component. However, I am not sure as to how I can inject the id parameter, and the component needs this parameter.

顺便说一句:我已经为 Session 服务提供了一个模拟,所以在那里不用担心。

By the way: I already have a mock for the Session service, so no worries there.

推荐答案

最简单的方法是使用 useValue 属性,并提供要模拟的值的Observable。

The simplest way to do this is to just use the useValue attribute and provide an Observable of the value you want to mock.

RxJS< 6

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
...
{
  provide: ActivatedRoute,
  useValue: {
    params: Observable.of({id: 123})
  }
}

RxJS> = 6

import { of } from 'rxjs';
...
{
  provide: ActivatedRoute,
  useValue: {
    params: of({id: 123})
  }
}

这篇关于如何对依赖ActivatedRoute参数的组件进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆