Может кто-нибудь помочь мне разобраться, как провести модульное тестирование компонента приложения ниже?Это приложение Angular 2.
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,
);
}
}
Что у меня есть до сих пор:
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();
});
});
Я получаю сообщение об ошибке: Failed: No provider for e!
Но мне кажется, что я импортирую все, что нужно этому компоненту для создания экземпляра.
Мне интересно, если это1) либо RouterTestingModule
не знает router.events.subscribe
;или 2) window
не определено.
Есть мысли?
Спасибо!
Редактировать 1:
Похоже, что строкау меня возникают следующие проблемы:
@Component({
...,
...,
providers: [DataService]
})
Похоже, что Жасмин вводит объект MockDataService
в конструктор app.component
, но не вводит объект для провайдера.Жасмин предоставляет конкретную реализацию DataService
.
Как мне внедрить MockDataService
в провайдеров для app.component
?