Вы должны смоделировать маршрутизатор и предоставить объект события.
Примерно так:
describe('YourComponent', () => {
let component: YourComponent;
let fixture: ComponentFixture<YourComponent>;
let eventsStub = new BehaviorSubject<any>(null);
let routerStub = {
events: eventsSub,
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
YourComponent,
],
providers: [
// merge the two mocks like this !!
{ provide: Router, useValue: routerStub },
{
provide: ActivatedRoute,
useValue: {
snapshot: {
queryParams: of({})
},
queryParams: of({}),
queryParamMap: of({}),
params: of({id: 'something'})
},
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
let mockNav = new NavigationEnd(1, 'any', 'any');
// make events have the mockNav listed above
eventsSub.next(mockNav);
// this detectChanges will make ngOnInit be called
fixture.detectChanges();
});
it('calls window.scrollTo', () => {
expect(component).toBeDefined();
expect(spyScrollTo).toHaveBeenCalled();
// your other tests
});
});
При выполнении этих тестов поместите журнал в subscribe
, чтобы обеспечить тест прошел это:
ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0);
console.log('After scrollTo!!!'); // !! remove when done but make sure you see this
if (this.object.attribut1) {
this.loadSomething();
}
if (this.object.attribut2) {
this.loadSomething2();
}
});
}