Say that I want to simply unit test a component that takes parameters taken from a part of the route. For instance, my component's ngOnInit looks like this:
ngOnInit() {
this.route.parent.params.switchMap((params: Params) => this.service.getProject(params['projectId']))
.subscribe((project: Project) => this.update(project));
}
How can I now: 1: setup my test so that the component create works at all, so I can unit test other parts
Edited with answer - the example ActivatedRouteStub should be extended with a parent that also has an observable params, and I should have used useClass instead of useValue (forgot to change that back):
@Injectable()
export class ActivatedRouteStub {
// ActivatedRoute.params is Observable
private subject = new BehaviorSubject(this.testParams);
params = this.subject.asObservable();
// Test parameters
private _testParams: {};
get testParams() { return this._testParams; }
set testParams(params: {}) {
this._testParams = params;
this.subject.next(params);
}
// ActivatedRoute.snapshot.params
get snapshot() {
return { params: this.testParams };
}
// ActivatedRoute.parent.params
get parent() {
return { params: this.subject.asObservable() };
}
}
2: provide a value for projectId in my UnitTest?
The examples from the angular2 documentation do not seem to work for switchMap, or even at all (I've used the ActivatedRouteStub from there, but no luck with that so far - params is always undefined).
Edited with answer:
describe('ProjectDetailsComponent', () => {
let component: ProjectDetailsComponent;
let fixture: ComponentFixture<ProjectDetailsComponent>;
let activatedRoute: ActivatedRouteStub;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([{ path: 'projects/:projectId', component: ProjectDetailsComponent }])],
declarations: [ProjectDetailsComponent],
schemas: [NO_ERRORS_SCHEMA],
providers: [{ provide: ProjectsService, useClass: ProjectsServiceStub }, {provide: ActivatedRoute, useClass: ActivatedRouteStub}]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProjectDetailsComponent);
component = fixture.componentInstance;
activatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
activatedRoute.testParams = { projectId: '123'};
fixture.detectChanges();
});
fit('should create', () => {
expect(component).toBeTruthy();
});
});