Angular 2.0.0-rc.1 + karma: provide a router

When an instance is required for testing Router, simply providing Routeryourself 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();
  }));
});

The following error will occur:

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

But I really don't know how to enable the router.

Router parameters

_rootComponent: Object,

_rootComponentType: Type,

In alpha, we had RootRouter: import {RootRouter} from 'angular2/src/router/router';. It disappeared without any replacement.

_componentResolver: ComponentResolver,

_urlSerializer: RouterUrlSerializer,

I don’t know how to provide them.

_routerOutletMap: RouterOutletMap,

It seems that this is already provided in the router itself

_location:

- SpyLocation:

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

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

@angular/router/testing ROUTER_FAKE_PROVIDERS beforeEachProviders()

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

import {RouterTestingModule} from '@angular/router/testing'; RouterTestingModule .

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

All Articles