I'm trying to test ngOnInit() method for the component that has a subscribe method:
Component:
import { Component, OnInit} from '@angular/core';
import { SharedDataService } from './../services/shared-data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private sharedDataService: SharedDataService,) { }
this.subscriptions = [];
ngOnInit() {
this.subscriptions.push(this.sharedDataService.getModel().subscribe(model => {
this.message=model.message
}));
}
}
}
Test Suite
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { XHRBackend } from '@angular/http';
describe('AppComponent Test', () => {
let component: any;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [SharedDataService , { provide: XHRBackend, useClass: MockBackend }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
it('test onInit function', () => {
component.ngOnInit();
spyOn(component.subscriptions,"push");
expect(component.subscriptions).toHaveBeenCalledWIth(component.sharedDataService.getModel());
});
});
But throwing error as "cannot spy on subscriptions".Is this is the procedure to test subscribe method. Please suggest.