Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 RC5 Mock Activated Route Params

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:

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')

Any help would be greatly appreciated.

like image 923
GlacialFlames Avatar asked Sep 07 '16 18:09

GlacialFlames


2 Answers

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.

like image 177
pbialy Avatar answered Nov 12 '22 10:11

pbialy


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 }]) } }
like image 36
jonrsharpe Avatar answered Nov 12 '22 11:11

jonrsharpe