Search code examples
javascriptangularunit-testingjasminehttpclient

Testing HttpClient call with callFake()


I am trying to create a spec to test a method in my Angular service that makes a GET request. The difficulty I am having is mocking the method to get it to return an error instead of the response. If I cannot get it to return an error (such a 400 or 500 for example) I cannot provide full code coverage...

Code being tested:

maingrid.service.ts:

 async loadAccountListPromise(id: string) {
     let queryParams = `?emailAddress=${id}`;
     let promise = new Promise((resolve, reject) => {
          this.http.get(`${this.baseUrl}` + queryParams, { responseType: 'json' })
             .toPromise()
             .then(
             (data) => {
                 this.results = this.formatData(data);
                 resolve(this.results);
             },
             (err) => {
                 this.logService.error('loadAccountListPromise() exception:', err);
                 this.setError(this.message[0], err);
                 reject('loadAccountListPromise() exception');
             }
         );
     });
     return promise;
 }

 setError(errorMessage: string, errorCode?: string): void {
     this._error.next(new NxpError(errorMessage, 'AccountListService', 
     errorCode));
 }

 clearError(): void {
     this._error.next(null);
 }

This is the spec I have attempted to write to mock the method using callFake():

maingrid.service.spec.ts

    it('logs and sets a local error for system errors/exceptions', () => {

            let id: string = '[email protected]';
            let myUrl = 'https://localhost:9999/...';
            let queryParams = `?emailAddress=${id}`;

            spyOn(httpClient, 'get').and.callFake( loadAccountListPromise( (response) => {
                // need to return error here...somehow
            }));

            spyOn(logService, 'error');

            spyOn(maingridService, 'setError');

            maingridService.loadAccountListPromise(id);

            let request = httpMock.expectOne(myUrl + queryParams);

            expect(request.request.method).toEqual('GET');

            httpMock.verify();

            expect(logService.error).toHaveBeenCalled();
            expect(maingridService.setError).toHaveBeenCalled();
        });

I am not sure what I need to do to properly mock the loadAcountListPromise() method so that it enters the error block and calls the setError() and logService.error() methods.


Solution

  • Try to use the 'spyOn()' and return a throw like this:

    spyOn(httpClient, 'get').and.returnValue(Observable.throw({status: 404}));
    //Observable.throw(new Error(`Error: ${error}`));