I'm writing my ng2 tests, and I'm running into some trouble injecting Router into my component for my test. The constructor for my component only takes one argument-- private router: Router
.
But, when I run my test case, I'm getting an error while it's trying to inject the Router. What am I doing wrong? Can anyone provide a working example?
I'm using angular2-RC.1
Here's the error I'm getting:
No provider for ComponentResolver! (Router -> ComponentResolver)
Here's my test:
import {describe, it, expect, beforeEach, afterEach, beforeEachProviders, inject} from "@angular/core/testing";
import {ReflectiveInjector, provide} from "@angular/core";
import {HTTP_PROVIDERS} from "@angular/http";
import {Router, ROUTER_PROVIDERS} from "@angular/router";
import {ROUTER_FAKE_PROVIDERS} from "@angular/router/testing";
import {Location} from "@angular/common";
import {SpyLocation} from "@angular/common/testing/location_mock";
import {Observable} from "rxjs/Observable";
import {MyComp} from "./MyComp";
describe("MyComp", () => {
let injector: ReflectiveInjector,
myComp: MyComp,
router: Router;
beforeEach(() => {
injector = ReflectiveInjector.resolveAndCreate([
HTTP_PROVIDERS,
ROUTER_FAKE_PROVIDERS,
provide(Location, {useClass: SpyLocation})
]);
router = injector.get(Router);
myComp = new MyComp(router);
});
afterEach(() => {
injector = null;
myComp = null;
router = null;
});
it("should be defined", () => {
expect(myComp).toBeDefined();
});
});
Using anonymous ES 6 class and jasmine:
Well, I came up with a solution. It's not ideal, but it works. Basically, I'm creating a
MockRouter
class that implements the methods I need.MockRouter:
Now, in my test case, all I have to do is provide the mock implementation for router:
provide(Router, {useClass: MockRouter})
It would be really nice if the NG2 docs would show how you can properly inject
Router
into your Jasmine test cases. Mocking their objects seems like it should be an unnecessary step.(FYI, I tried using the
ROUTER_FAKE_PROVIDERS
and still got theComponentResolver
error above)After countless of suggestions that didn't work: This was one solution that worked for me in Angular4 and Karma:
It's based on Andriy Tolstoy's Answer and reading through the Angular Manual.
Here is an alternative solution which is a bit more verbose but allows us to use SpyLocation in order to check the route changes. First we create generic test router providers.
router-test-providers.ts
The corresponding jasmine test is provided below.
navigation.spec.ts
You need to create a jasmine spy object for the router. AppComponent has a constructor that takes in a Router.
Some modifications... this simple solution works for me: