Search code examples
angularjasminekarma-jasmine

How do I test the response of this service function in Angular?


I have the following function in my service

import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { APP_CONST } from '../app-const';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private http: HttpClient) { }
  getLandingData(): Observable<any> {
   return this.http.get(this.landingApiEndPoint+this.api.landing_uri).pipe(
        map((response: any) => {
          console.log('Res ', response);
          return response;
        })
   );
}

And for this function, I've written this test case:

it('should get Landing Data', (done: DoneFn) => {
    const names = [{name: 'a'}, {name: 'b'}];
    service.getLandingData().subscribe((res)=>{
      expect(res).toEqual(names);
      console.log("Landing "+res);
      console.log("Landing names"+names);
      done();
    })
  });

But I keep getting this error: Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL) I tried setting the default timeout interval, but no luck. I'm using jasmine 4.2.0. Please do let me know how I can test this correctly.


Solution

  • You need to import HttpClientTestingModule module in your tests. And then you need either mock httpClient or use HttpTestingController to mock the requests.

    For example:

    describe('TestSuite', () => {
      let service: Service;
      let httpMock: HttpTestingController;
      
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [HttpClientTestingModule],
          providers: [Service]
        });
        service = TestBed.inject(Service);
        httpMock = TestBed.inject(HttpTestingController);
      });
    
      it('should get Landing Data', (done: DoneFn) => {
        const names = [{ name: 'a' }, { name: 'b' }];
    
        service.updateAlias().subscribe((res)=>{
          expect(res).toEqual(names);
          console.log("Landing ", res);
          console.log("Landing names", names);
          done();
        });
    
        httpMock
          .expectOne('http://landing-page.com/url')
          .flush(names);
      });
    });