Can someone please help me understand how to unit test the app component below? It's an Angular 2 application.
app.ts
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, NavigationStart, NavigationCancel, NavigationError, RoutesRecognized } from '@angular/router';
import { DataService } from '../services/data';
@Component({
selector: 'app',
template: '<messages></messages><router-outlet></router-outlet>',
providers: [DataService]
})
export class AppComponent implements OnInit {
constructor(private router: Router, private data: DataService) {}
public ngOnInit(): void {
this.router.events.subscribe((event: NavigationStart | NavigationEnd | NavigationCancel | NavigationError | RoutesRecognized) => {
if (!(event instanceof NavigationEnd)) { return; }
document.body.scrollTop = 0;
});
window.addEventListener(
"offline", () => {
if (this.data.settings.offlineEnabled) {
this.data.toggleOffline();
this.data.displayMessage("Internet connection lost, switching to offline mode.", "failure")
} else {
this.data.displayMessage("Internet connection lost", "failure")
}
}, false,
);
}
}
What I've got so far:
app.spec.ts
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app'
import { RouterTestingModule } from '@angular/router/testing';
import { MessagesComponent } from './messages/messages';
import { DataService } from '../services/data';
/* Tests */
export class MockDataService {}
describe('Component: App', () => {
let mockData = new MockDataService();
let component: AppComponent;
let dataService: DataService;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent,
MessagesComponent
],
providers: [
{ provide: DataService, useValue: mockData }
]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
dataService = TestBed.get(DataService);
}));
it('should create the component', () => {
expect(component).toBeTruthy();
});
});
I'm getting the error:
Failed: No provider for e!
But, it appears to me that I'm importing everything that this component needs for instantiation.
I'm wondering if this is 1) either RouterTestingModule
doesn't know router.events.subscribe
; or, 2) window
is not defined.
Any thoughts?
Thanks!
Edit 1:
It appears that the line that is causing my issues is this:
@Component({
...,
...,
providers: [DataService]
})
It appears that Jasmine is injecting the MockDataService
object into the app.component
constructor, but it's not injecting the object for the provider. Jasmine is providing the concrete DataService
implementation.
How do I inject the MockDataService
into the providers for the app.component
?