Reputation: 1111
When a test needs an instance of the Router
, just providing Router
itself is not enough:
import {Router} from '@angular/router';
import {it, inject, beforeEachProviders} from '@angular/core/testing';
import {ComponentToTest} from './component.to.test';
describe('ComponentToTest', () => {
beforeEachProviders(() => [
Router,
ComponentToTest
]);
it('should call getData() on contruct', inject([Router], (router) => {
spyOn(ComponentToTest.prototype, 'getData');
expect(ComponentToTest.prototype.getData).not.toHaveBeenCalled();
let component = new ComponentToTest(router);
expect(ComponentToTest.prototype.getData).toHaveBeenCalled();
}));
});
Following error will occur:
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.
Yet I don't really know how to resolve the router.
Router
parametersIn alpha we had the RootRouter
:
import {RootRouter} from 'angular2/src/router/router';
. This is gone now without any replacement.
Haven't got a clue on how to provide these.
Seems like this one is already provided in the Router itself
This parameter can possibly still be provided by SpyLocation
:
import {SpyLocation} from '@angular/common/testing';
describe('ComponentToTest', () => {
beforeEachProviders(() => [
provide(Location, { useClass: SpyLocation }),
]);
});
Upvotes: 4
Views: 1021
Reputation: 4642
Another solution is to use import {RouterTestingModule} from '@angular/router/testing';
and to add RouterTestingModule
to your imports in your test file.
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [
RouterTestingModule
]
});
TestBed.compileComponents();
});
Upvotes: 0
Reputation: 657406
Import @angular/router/testing
and provide ROUTER_FAKE_PROVIDERS
in beforeEachProviders()
beforeEachProviders(() => [
ROUTER_FAKE_PROVIDERS,
ComponentToTest
]);
Upvotes: 6