问题描述
我正在对用于编辑对象的组件进行单元测试.该对象具有唯一的 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 id
is 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 参数的组件进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!