Test Cases For HTTP POST Method Services In Angular

In the previous blog, we test the HTTP GET method. We also understood that what is Testing, Jasmine, Karma, HttpTestingController, HttpClientTestingModule etc. You can check HTTP GET method Testing here.

Today, we test the HTTP POST test case for services.

Testing POST Method.

employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';
import { Employee } from './employee';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': 'my-auth-token'
  })
};

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  empUrl = "/api/employees";
  constructor(private http: HttpClient) { }

  addEmployee(emp: Employee): Observable<Employee> {
    return this.http.post<Employee>(this.empUrl, emp, httpOptions)
      .pipe(
        tap(employee => console.log("employee: " + JSON.stringify(employee))),
        catchError(this.handleError(emp))
      );
  }
  private handleError<T>(result = {} as T) {
    return (error: HttpErrorResponse): Observable<T> => {
      console.error(error);
      return of(result);
    };
  }
}

employee.ts

export interface Employee {
    name: string;
    age: number;
}

employee.service.spec.ts

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Employee } from './employee';
import { EmployeeService } from './employee.service';

//Testing of EmployeeService
describe('#EmployeeService.addEmploye()', () => {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;
  let empService: EmployeeService;

  beforeEach(() => {
    //Configures testing app module
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        EmployeeService
      ]
    });

    //Initialize HttpClient, HttpTestingController and EmployeeService
    httpClient = TestBed.inject(HttpClient);
    httpTestingController = TestBed.inject(HttpTestingController);
    empService = TestBed.inject(EmployeeService);
  });

  afterEach(() => {
    httpTestingController.verify(); //Verifies that no requests are outstanding.
  });
  
  //Test case
  it('should add an employee and return it', () => {
    const newEmp: Employee = { name: 'John', age: 31 };

    empService.addEmployee(newEmp).subscribe(
      data => expect(data).toEqual(newEmp, 'should return the employee'),
      fail
    );

    // addEmploye should have made one request to POST employee
    const req = httpTestingController.expectOne(empService.empUrl);
    expect(req.request.method).toEqual('POST');
    expect(req.request.body).toEqual(newEmp);

    // Expect server to return the employee after POST
    const expectedResponse = new HttpResponse({ status: 201, statusText: 'Created', body: newEmp });
    req.event(expectedResponse);
  });
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories