Issue with Angular service method retrieving data from database during testing
In myservice.ts, I have a method named getEvents() that creates an array, fetches data from the database using http.get, fills the array, and returns it. However, when I try to call this method in myservice.spec.ts, it returns undefined.
myservice.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { MyComponent } from './mycomponent.component.ts';
@Injectable({
providedIn: 'root'
})
export class MyService {
getEvents(): string[] {
const events = [];
this.http.get<MyClass[]>('http://localhost:3001/getEvents')
.subscribe(subscribedEvents => {
for (const event of subscribedEvents ) {
events.push(event);
}
});
return events;
}
constructor(private http: HttpClient) { }
}
myservice.service.spec.ts:
import { async, TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { MyService } from './myservice.service';
describe('MyService', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ HttpClientModule ],
providers: [ MyService ]
})
.compileComponents();
}));
it('getEvents', () => {
const service: MyService = TestBed.get(MyService);
expect(service.getEvents()[0]).toEqual('FirstEvent');
});
});
The getEvents() function sends a request to the backend server, retrieves data successfully (verified by the component and Postman), populates an array with the data received through .subscribe(), and then returns the filled array. While this works fine in the component, it seems to be returning undefined in the service spec.
I apologize for the generic naming of variables; I prefer not to share my original code.
Error Message:
Expected undefined to equal 'FirstEvent'.