Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test http.post request with parameters in angular 9?

I am new at angular I have a service that calls HTTP post requests with some parameters. Now I want to test that service function in angular.

My service part is

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class GetProviderService{
      providersData: any;
      constructor(private http: HttpClient) {
       }

getProviders(param: any): any{
   var json = JSON.stringify(param);
const myHeader = new HttpHeaders().set('content-type','application/json');
this.http.post<any>(url, json, {headers: myHeader}).subsribe(data=> {
   this.providerData = data;
   return this.providerData;
   }),
   (erorr) => {
     window.alert("error");
     return null;
   }
}

now I want to cover getProviders functions with error subscribe and error. How can I do this?

Thank you in advance.

like image 857
DHRUVIN MASHRUWALA Avatar asked May 25 '26 01:05

DHRUVIN MASHRUWALA


2 Answers

Assuming you get the url from somewhere (e.g: getProviders(param: any, url: string) is an example of a test suite:

import { TestBed  } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController  } from '@angular/common/http/testing';
import { GetProviderService } from './get-provider.service';

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

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

  fit('should log success on success', () => {
    const mockUrl = 'http://mockurl.com/test';
    const mockResponse = {hello: 'test'}
    service.getProviders({}, mockUrl);
    httpMock.expectOne(mockUrl).flush(mockResponse);
    // your expects here
  });

  fit('should log error on error', () => {
    const mockUrl = 'http://mockurl.com/test';
    const mockErrorMsg = 'My mock error message'
    const mockError = new ErrorEvent('Network error', {
      message: mockErrorMsg,
    });
    service.getProviders({}, mockUrl);
    httpMock.expectOne(mockUrl).error(mockError);
    // your expects here
  });
});

And here is the relevant angular documentation: https://angular.io/guide/http#testing-http-requests

It is the part of the http guide and not the testing guide, probaly that is why you did not find it.

like image 102
ziale Avatar answered May 28 '26 12:05

ziale


import { HttpTestingController } from "@angular/common/http/testing"

describe("service", ()=>{
let httpTestingController: HttpTestingController

beforeEach(()=>{
httpTestingController = TestBed.inject(HttpTestingController)
})

it("Should return req payload", () =>{
service.reserveDevice().subscribe()

const req = httpTestingController.expectOne({method: "POST"})
req.flush();
console.log(req.request.body); //Will return your post payload
console.log(req.request.body);
})

})
like image 38
ANKIT MISHRA Avatar answered May 28 '26 12:05

ANKIT MISHRA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!