0

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$;
    }
}
hirse
  • 2,394
  • 1
  • 22
  • 24
ebakunin
  • 3,621
  • 7
  • 30
  • 49
  • You can override `Http` with a mock Http during your tests using dependency injection. Check out how [this guy](http://stackoverflow.com/q/41960768/1153681) does it. – AngularChef Jan 31 '17 at 22:03
  • 1
    Or, more thorough: https://blog.thoughtram.io/angular/2016/11/28/testing-services-with-http-in-angular-2.html – AngularChef Jan 31 '17 at 22:04
  • Possible duplicate of [Angular 2 Observable Service Karma Jasmine Unit Test not working](http://stackoverflow.com/questions/42583749/angular-2-observable-service-karma-jasmine-unit-test-not-working) – user3495469 Mar 15 '17 at 15:48

0 Answers0