Angular2 RC5 Mock Activated Route Params

最后都变了- 提交于 2019-11-30 08:47:24

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:

import { Observable } from 'rxjs/Rx';

...

{ provide: ActivatedRoute, useValue: { 'params': Observable.from([{ 'id': 1 }]) } }

Answer given by @jonrsharpe allows you to mock params, but those params would be the same in every test.

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:

At the top:

describe('SomeComponent', () => {
  (...)
  let params: Subject<Params>;
  (...)

in beforeEach (the async one - where you have imports, providers etc.):

beforeEach(async(() => {
  params = new Subject<Params>();
  (...)

in 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.

This means you should remove fixture.detectChanges from beforeEach and add it to every test.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!