I am writing unit test case and trying to spy a service function but got stuck with converting array to observable i tried similar question on stack-overflow but nothing worked. Please help how do i call service function
I am working on latest version of angular and ngrx
Options i tried
1)
spyOn(service, 'getData').and.returnValue(Observable.of(data));
2) This one didn't covered subscribe part in unit test component
spyOn(service, 'getData').and.returnValue(of(data));
whole code: testcase never enter subscribe part of this.dataService.getState()
// component:
getState(){
this.dataService.getState().subscribe(s => s.forEach(element => {
this.data.push(element.name);
}));
}
//test case
beforeEach(() => {
fixture = TestBed.createComponent(DataComponent);
component = fixture.componentInstance;
service = TestBed.inject(DataService);
fixture.detectChanges();
});
it('should call get data Function', () => {
spyOn(service, 'getData').and.returnValue(of(data));
});
When you setup a test, the component instantiates when you call fixture.detectChanges
. Since instantiation invokes lifecycle hooks, any code in the ngOnInit
function executes before your first test spec.
If data
is a constant, do:
beforeEach(() => {
fixture = TestBed.createComponent(DataComponent);
component = fixture.componentInstance;
service = TestBed.get(DataService);
spyOn(service, 'getData').and.returnValue(of(data));
fixture.detectChanges();
});
If data
is a variable, do:
beforeEach(() => {
fixture = TestBed.createComponent(DataComponent);
component = fixture.componentInstance;
service = TestBed.get(DataService);
});
// test method
it('should call get data Function', () => {
spyOn(service, 'getData').and.returnValue(of(data));
// other required setup
fixture.detectChanges();
// test stuff
});