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?
Asked
Active
Viewed 666 times
0
-
did you fix the problem? – Kamran Pervaiz Aug 09 '16 at 09:26
2 Answers
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]},
];
};

Dennis Neuendorf
- 41
- 2
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();
});
})));
-
1Thanks 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
-