Looking to write a unit test for my component file that subscribes to a method in the service layer
Homecomponent.ts
import { Data } from './../model/data.model';
import { DataService } from './../services/data.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
data: Data[];
constructor(private service: DataService) {}
ngOnInit() {
this.getData();
}
getData() {
this.service.getData().subscribe(
(data) => {
console.log(data);
this.data = data;
},
(err) => {
console.log(err);
},
);
}
}
HomeComponent.spec.ts
import { Data } from './../model/data.model';
import { HttpClientModule } from '@angular/common/http';
import { HomeComponent } from './home.component';
import { ComponentFixture, async, TestBed } from '@angular/core/testing';
import { DataService } from '../services/data.service';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { results } from '../model/home';
class MockMyService {
public data: Data[];
public getData(): Observable<Data[]> {
this.data = results;
return Observable.of(this.data);
}
}
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
let mockSomeService: MockMyService;
describe('Async', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent],
providers: [
{
provide: DataService,
useValue: mockSomeService,
},
],
imports: [HttpClientModule],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
});
TestBed.compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
mockSomeService = fixture.debugElement.injector.get(DataService);
spyOn(mockSomeService, 'getData').and.returnValue(Observable.of(results));
component.ngOnInit();
fixture.detectChanges();
}));
});
// afterEach(() => {
// fixture = undefined;
// });
it('method should be called', async () => {
component.ngOnInit();
mockSomeService.getData();
expect(fixture.debugElement.componentInstance.data.length).toEqual(2);
});
});
When I use component.ngOnInit(); it gives an error as
TypeError: Cannot read property 'ngOnInit' of undefined
When I'm not using component.ngOnInit() it gives me an error as
TypeError: Cannot read property 'getData' of undefined
How can I solve this issue? Appreciate any help in advance.