Home:ALL Converter>Angular 2 testing with Router - Cannot resolve all parameters for 'Router'

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

Ask Time:2016-01-28T08:56:19         Author:AlexB

Json Formatter

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.

Author:AlexB,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/35051053/angular-2-testing-with-router-cannot-resolve-all-parameters-for-router
AlexB :

ok, with the help from angular team I got it working:\n\nimport { SpyLocation } from 'angular2/src/mock/location_mock';\nimport {RootRouter} from 'angular2/src/router/router';\nimport {Router, RouterOutlet, RouterLink, RouteParams, RouteData, Location, ROUTER_PRIMARY_COMPONENT} from 'angular2/router';\nimport {\n RouteConfig,\n Route,\n AuxRoute,\n AsyncRoute,\n Redirect\n} from 'angular2/src/router/route_config_decorator';\nimport {RouteRegistry} from 'angular2/src/router/route_registry';\nimport {DirectiveResolver} from 'angular2/src/core/linker/directive_resolver';\n\nbeforeEachProviders(() => {\n return [\n RouteRegistry,\n provide(Location, { useClass: SpyLocation }),\n provide(ROUTER_PRIMARY_COMPONENT, { useValue: YourComponentWithRouteConfig }),\n provide(Router, {useClass: RootRouter}),\n FormBuilder,\n SomeInfoEdit\n ];\n });\n",
2016-01-28T14:23:11
yy