如何对依赖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 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})
}
}