Angular2 RC5 Mock Activated Route Params

GlacialFlames picture GlacialFlames · Sep 7, 2016 · Viewed 11.8k times · Source

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.

Answer

jonrsharpe picture jonrsharpe · Sep 7, 2016

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 }]) } }