AlexB
AlexB

Reputation: 4538

Angular 2 testing with Router - Cannot resolve all parameters for 'Router'

I'm trying to test my component which injects Router in the constructor (TypeScript):

constructor(
    private _router: Router,
    private dispatcher: Observer<Action>,
    fb: FormBuilder
) { ... }

And I have the following test(s):

import {
it,
inject,
injectAsync,
beforeEachProviders,
TestComponentBuilder
} from "angular2/testing";

import {provide} from "angular2/core";
import {FormBuilder} from 'angular2/common';
import {Subject} from 'rxjs/Subject';
import {Router, RouteParams} from 'angular2/router';
// other imports ...

describe("SomeInfoEdit form", () => {

    const actions = new Subject<Action>(null);

    // provide our implementations or mocks to the dependency injector
    beforeEachProviders(() => {

        return [
            Router,
            FormBuilder,
            provide(dispatcher, { useValue: actions }),
            SomeInfoEdit
        ];
    });

    it('should have default data', inject([SomeInfoEdit], (component) => {
        expect(component.galtitle.value).toEqual("");
        expect(component.friendlyUrl.value).toEqual("");
        expect(component.isVisible.value).toBe(false);
    }));
...

When the test runs I get the 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.

I would love to read about it to get an explanation of what's going on (I read articles on DI, so).

I should add that the code itself works, no problems. Just the test doesn't.

Upvotes: 2

Views: 3610

Answers (2)

rbnzdave
rbnzdave

Reputation: 91

The issue remains when you have a component (directive) which doesn't have a route config in it (such as a menu directive that is fed from a service). What happens when there is no routeconfig ?

Upvotes: 1

AlexB
AlexB

Reputation: 4538

ok, with the help from angular team I got it working:

import { SpyLocation } from 'angular2/src/mock/location_mock';
import {RootRouter} from 'angular2/src/router/router';
import {Router, RouterOutlet, RouterLink, RouteParams, RouteData, Location, ROUTER_PRIMARY_COMPONENT} from 'angular2/router';
import {
  RouteConfig,
  Route,
  AuxRoute,
  AsyncRoute,
  Redirect
} from 'angular2/src/router/route_config_decorator';
import {RouteRegistry} from 'angular2/src/router/route_registry';
import {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';

beforeEachProviders(() => {
        return [
            RouteRegistry,
            provide(Location, { useClass: SpyLocation }),
            provide(ROUTER_PRIMARY_COMPONENT, { useValue: YourComponentWithRouteConfig }),
            provide(Router, {useClass: RootRouter}),
            FormBuilder,
            SomeInfoEdit
        ];
    });

Upvotes: 1

Related Questions