When a component is injected with RouteSegment, just providing the RouteSegment in the test is not enough:
component.ts:
export class ComponentToTest {
private param: string;
constructor(routeSegment: RouteSegment) {
this.param = routeSegment.getParam('param');
this.getData();
}
}
component.spec.ts:
import {Router, RouteSegment} from '@angular/router';
import {it, inject, beforeEachProviders} from '@angular/core/testing';
import {ROUTER_FAKE_PROVIDERS} from '@angular/router/testing';
import {ComponentToTest} from './component';
describe('ComponentToTest', () => {
beforeEachProviders(() => [
ROUTER_FAKE_PROVIDERS,
RouteSegment,
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 'RouteSegment'(?, ?, ?, ?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RouteSegment' is decorated with Injectable.
I have no idea on how to provide the RouteSegment parameters.
I had the same issue, I had to look at the angular router code and the specs they have in there repo. You should be able to provide the routeSegment like this:
or you can just mock out a new RouteSegment similar to how you did with RouteParams:
Is now this:
To create it you just have to pass it a couple of extra parameters.
Solution 1
See the answer of HomeBrew
Didn't work for me, still not sure why.
Solution 2
A mock implementation of RouteSegment:
Provide it like this: