typescript Angular2 RC5 模拟激活路由参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39376840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 RC5 Mock Activated Route Params
提问by GlacialFlames
I need to be able to mock the activated route parameters to be able to test my component.
我需要能够模拟激活的路由参数才能测试我的组件。
Here's my best attempt so far, but it doesn't work.
这是我迄今为止最好的尝试,但它不起作用。
{ provide: ActivatedRoute, useValue: { params: [ { 'id': 1 } ] } },
The ActivatedRoute is used in the actual component like this:
ActivatedRoute 在实际组件中使用,如下所示:
this.route.params.subscribe(params => {
this.stateId = +params['id'];
this.stateService.getState(this.stateId).then(state => {
this.state = state;
});
});
The error I get with my current attempt is simply:
我当前尝试得到的错误很简单:
TypeError: undefined is not a constructor (evaluating 'this.route.params.subscribe')
TypeError: undefined is not a constructor (evaluating 'this.route.params.subscribe')
Any help would be greatly appreciated.
任何帮助将不胜感激。
回答by jonrsharpe
Your mock must reflect the object it's replacing. You .subscribe
because it returns an observable, not just the object, so your mock value should too:
您的模拟必须反映它正在替换的对象。你.subscribe
因为它返回一个可观察的对象,而不仅仅是对象,所以你的模拟值也应该:
import { Observable } from 'rxjs/Rx';
...
{ provide: ActivatedRoute, useValue: { 'params': Observable.from([{ 'id': 1 }]) } }
回答by pbialy
Answer given by @jonrsharpe allows you to mock params
, but those params would be the same in every test.
@jonrsharpe 给出的答案允许您模拟params
,但这些参数在每个测试中都是相同的。
If you want to be able to change the params
, to set it at the start of a test, you can do it like this:
如果您希望能够params
在测试开始时更改, 设置它,您可以这样做:
At the top:
在顶部:
describe('SomeComponent', () => {
(...)
let params: Subject<Params>;
(...)
in beforeEach
(the async
one - where you have imports
, providers
etc.):
在beforeEach
(async
一个 - 你有的地方imports
,providers
等等):
beforeEach(async(() => {
params = new Subject<Params>();
(...)
in providers
:
在providers
:
(...)
{
provide: ActivatedRoute,
useValue: {
params: params
}
}
(...)
and then in test:
然后在测试中:
it('someTest', () => {
params.next({'id': '123'});
fixture.detectChanges();
(...)
IMPORTANT NOTE
重要的提示
Be sure to call fixture.detectChanges
after params.next
.
请务必在fixture.detectChanges
之后致电params.next
。
This means you should remove fixture.detectChanges
from beforeEach
and add it to every test.
这意味着您应该fixture.detectChanges
从beforeEach
每个测试中删除它并将其添加到每个测试中。