DEV Community

Cover image for HTTP requests in Angular.
MD ASHRAF
MD ASHRAF

Posted on • Edited on

HTTP requests in Angular.

Without any essay or blog writing lets jump on to very first step to integrate HTTP call in Angular application.

  1. Defining *HttpClientModule * in your module.

module.ts

import { HttpClientModule } from'@angular/common/http'; 
   @NgModule({
     imports: [
       BrowserModule,
       HttpClientModule // Add this line
     ],
     ...
   })
   export class AppModule { }

Enter fullscreen mode Exit fullscreen mode

** * In case of standalone component define this inside imports array of component itself.**

  1. Creating service file to make HTTP calls from there

service.ts

 import { HttpClient } from '@angular/common/http';

   @Injectable({
     providedIn: 'root'
   })
   export class MyService {
     // Injecting httpClient dependency
     constructor(private http: HttpClient) {}

     getData() {
       return this.http.get('https://api.example.com/data');
       // we can use desired rxjs operator here to modify data based on our requirement, for now keeping it simple.
     }
   }

Enter fullscreen mode Exit fullscreen mode
  1. Creating test cases for service file

service.spec.ts

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { MyService } from './my.service';

describe('MyService', () => {
  let service: MyService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [MyService]
    });
    service = TestBed.inject(MyService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should return data from API', () => {
    // test case to test success scenario
    const testData = { data: 'example data' };
    service.getData().subscribe(data => {
      expect(data).toEqual(testData);
    });

    const req = httpMock.expectOne('(sample link)');
    expect(req.request.method).toBe('GET');
    req.flush(testData);
  });

  it('should handle error', () => {
// test case to test error scenario
    service.getData().subscribe(
      data => {
        fail('should not be called');
      },
      error => {
        expect(error).toBeTruthy();
      }
    );

    const req = httpMock.expectOne('(link unavailable)');
    req.error(new ErrorEvent('Test Error'));
  });
});

Enter fullscreen mode Exit fullscreen mode

OMG !!! what is this **httpMock.verify()** here, seems like alien 👽👽👽.

  1. Checks for outstanding requests: Verifies that all expected requests were made and that there are no outstanding requests.
  2. Verifies request count: Checks that the number of requests made matches the number of expectations set up.
  3. Verifies request URLs and methods: Checks that the URLs and HTTP methods of the requests made match the expectations.

4. Setting request headers

// Step 1
const httpHeaders: HttpHeaders = new HttpHeaders({
Authorization: 'Bearer JWT-token'
});

// Step 2
this.http.post(url, body, { headers: httpHeaders });

5. Calling service method in component

component.ts

import { Component } from '@angular/core';
   import { MyService } from './my-service.service';

   @Component({
     selector: 'app-root',
     template: `
       <p>{{ data | json }}</p>
     `
   })
   export class AppComponent {
     data: any;

     constructor(private myService: MyService) {
       this.myService.getData().subscribe(data => {
         this.data = data;
       });
     }
   }
Enter fullscreen mode Exit fullscreen mode

Comp.spec.ts

Here's an example of how you can write a test case for the Angular component's method using Jasmine and the HttpClientTestingModule:



import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { MyComponent } from './my.component';
import { MyService } from './my.service';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let myService: MyService;
  let httpMock: HttpTestingController;

  beforeEach(async () => {. // Focus here
    await TestBed.configureTestingModule({ // Focus here
      imports: [HttpClientTestingModule],
      declarations: [MyComponent],
      providers: [MyService]
    })
      .compileComponents(); // Focus here
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    myService = TestBed.inject(MyService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  it('should call myService.getData() and set data', () => {
    const testData = { data: 'example data' };

    spyOn(myService, 'getData').and.returnValue(of(testData));

    component.ngOnInit();

    expect(component.data).toEqual(testData);
  });

  it('should handle error from myService.getData()', () => {
    const error = new ErrorEvent('Test Error');

    spyOn(myService, 'getData').and.returnValue(throwError(error));

    component.ngOnInit();

    expect(component.data).toBeUndefined();
  });
});



Enter fullscreen mode Exit fullscreen mode

Top comments (0)