I am using Angular 2.31. I want to setup a unit test for a service that calls an API. To do this I need to fake the HTTP response from the API call.
In the following example I have a thin ExampleService that extends APIService which in turn handles all the backend complexity. I would subscribe to ExampleService.exampleData$ to get the information from the API call. I need to somehow override the HTTP request during the unit test so I can inject fake data.
Pseudo-code:
class ExampleService extends APIService {
private _dataForTheAPI: {} = { ...stuff... };
constructor(private _http: Http) {
super(_http, this._dataForTheAPI);
}
get exampleData$(): BehaviorSubject<any> {
return this.data$;
}
}
class APIService {
private _apiUrl: string = 'http://somewhere';
private _storage$: BehaviorSubject<any[]>;
constructor(private _http: Http, private _dataForTheAPI: any) {
this._getDataFromApi(_dataForTheAPI);
}
private _getDataFromApi(data: any): void {
this._http
.post(this._apiUrl, JSON.stringify(data))
.map(response => {
this._storage$.next(response.json());
});
}
get data$(): BehaviorSubject<any> {
return this._storage$;
}
}