0

Since I upgraded to Angular2 rc3 any tests that need the Router injected are now failing. Previously I was using the ROUTER_FAKE_PROVIDERS available from the router/testing file but that doesn't seem to exist any longer. Any suggestions?

HomeBrew
  • 849
  • 2
  • 12
  • 25

2 Answers2

2

I used this setup which worked to initialise the router. https://github.com/angular/angular/blob/master/modules/%40angular/router/test/router.spec.ts

Expect Angular2 provides that as a TestProvider soon.

import {Location, LocationStrategy} from '@angular/common';
import {SpyLocation} from '@angular/common/testing';
import {MockLocationStrategy} from '@angular/common/testing/mock_location_strategy';
import {Component, Injector, ComponentResolver} from '@angular/core';
import {ActivatedRoute, ActivatedRouteSnapshot, CanActivate, CanDeactivate, DefaultUrlSerializer, Event, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Params, ROUTER_DIRECTIVES,  Router, RouterConfig, RouterOutletMap, RouterStateSnapshot, RoutesRecognized, UrlSerializer} from '@angular/router';


export function provideTestRouter(RootCmp:any, config: RouterConfig):any[]{      
    return [
      RouterOutletMap,
      {provide: UrlSerializer, useClass: DefaultUrlSerializer},
      {provide: Location, useClass: SpyLocation},
      {provide: LocationStrategy, useClass: MockLocationStrategy},
      {
        provide: Router,
        useFactory: (resolver: ComponentResolver, urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, injector: Injector) => {
          return new (<any>Router)(
          RootCmp, resolver, urlSerializer, outletMap, location, injector, config);
        },
        deps: [ComponentResolver, UrlSerializer, RouterOutletMap, Location, Injector]
      },
      {provide: ActivatedRoute, useFactory: (r: Router) => r.routerState.root, deps: [Router]},
    ];
};
0

Take a look at my answer here, you seem to have a similar issue.

When unit testing, sometimes a certain service causes issues just because it's not being used in a normal environment. You can test to see if it has been called, without having the unit test run through the whole service. Do this by creating a mock class.

Based on that post, here is something you could do:

describe('foo', () => {

class MockRouter{}

beforeEachProviders(() => [
  {provide: ROUTER_PROVIDERS, useClass: MockRouter}
]);

it('should foo',
  async(inject([FooComponent, ROUTER_PROVIDERS], (foo: FooComponent, mockRouter: MockRouter) => {
  expect(mockRouter).toHaveBeenCalled();
  });
})));
Community
  • 1
  • 1
jhhoff02
  • 1,179
  • 1
  • 17
  • 24
  • 1
    Thanks man, I have tried this but I need the actual Router for the dependencies I have in my code. I could mock it all out but that would be pretty redundant. – HomeBrew Jun 29 '16 at 18:58
  • No problem, I see. What is your code dependent on from the Router? – jhhoff02 Jun 29 '16 at 19:05