Steve Van Opstal
Steve Van Opstal

Reputation: 1111

angular 2.0.0-rc.1 + karma: provide Router

When a test needs an instance of the Router, just providing Router itself is not enough:

import {Router} from '@angular/router';

import {it, inject, beforeEachProviders} from '@angular/core/testing';
import {ComponentToTest} from './component.to.test';

describe('ComponentToTest', () => {
  beforeEachProviders(() => [
    Router,    
    ComponentToTest
  ]);


  it('should call getData() on contruct', inject([Router], (router) => {
    spyOn(ComponentToTest.prototype, 'getData');
    expect(ComponentToTest.prototype.getData).not.toHaveBeenCalled();
    let component = new ComponentToTest(router);
    expect(ComponentToTest.prototype.getData).toHaveBeenCalled();
  }));
});

Following error will occur:

Error: Cannot resolve all parameters for 'Router'(?, ?, ?, ?, ?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Router' is decorated with Injectable.

Yet I don't really know how to resolve the router.

Router parameters

_rootComponent: Object,

_rootComponentType: Type,

In alpha we had the RootRouter: import {RootRouter} from 'angular2/src/router/router';. This is gone now without any replacement.

_componentResolver: ComponentResolver,

_urlSerializer: RouterUrlSerializer,

Haven't got a clue on how to provide these.

_routerOutletMap: RouterOutletMap,

Seems like this one is already provided in the Router itself

_location: Location

This parameter can possibly still be provided by SpyLocation:

import {SpyLocation} from '@angular/common/testing';

describe('ComponentToTest', () => {
  beforeEachProviders(() => [
    provide(Location, { useClass: SpyLocation }),
  ]);
});

Upvotes: 4

Views: 1021

Answers (2)

Adrien Brunelat
Adrien Brunelat

Reputation: 4642

Another solution is to use import {RouterTestingModule} from '@angular/router/testing'; and to add RouterTestingModule to your imports in your test file.

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [
      AppComponent
    ],
    imports: [
      RouterTestingModule
    ]
  });
  TestBed.compileComponents();
});

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657406

Import @angular/router/testing and provide ROUTER_FAKE_PROVIDERS in beforeEachProviders()

beforeEachProviders(() => [
  ROUTER_FAKE_PROVIDERS,
  ComponentToTest
]);

Upvotes: 6

Related Questions