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();
});
});
You need to create a jasmine spy object for the router. AppComponent has a constructor that takes in a Router.
import { AppComponent } from './app.component';
import {Router, ROUTER_PROVIDERS} from "@angular/router";
describe('app component', () => {
let component: AppComponent;
let router: Router;
beforeAll(() => {
router = jasmine.createSpyObj("Router", ['navigate']);
component = new AppComponent(router);
});
it("should be defined", () => {
expect(component).toBeDefined();
});
});
Using anonymous ES 6 class and jasmine:
beforeEach(() => addProviders([
{
provide: Router,
useClass: class { navigate = jasmine.createSpy("navigate"); }
}]));
Some modifications... this simple solution works for me:
import {MyComp} from "./MyComp";
import {RootRouter} from 'angular2/src/router/router';
import {provide} from 'angular2/core';
import {Router} from 'angular2/router';
describe("MyComp", () => {
let myComp: MyComp,
router;
beforeEach(() => {
provide(Router, {useClass: RootRouter})
myComp = new MyComp(router);
})
it("should be defined", () => {
expect(myComp).toBeDefined();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With