3

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.

3 Answers3

2

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.

ziale
  • 111
  • 4
1
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);
})

})
ANKIT MISHRA
  • 558
  • 4
  • 13
0
If you have to use for Angular component function and that function not calling any api or subscribe, only return some value, In that case you have to firstly console that variable in your function and than use this type of test case.

//-------Component.ts

myFunc(){
return abc; // in that case, It does n't have subscribe or any api call and we need to print the value in console of abc.
}


// ----Spec.ts
import { HttpTestingController } from "@angular/common/http/testing"

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

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

it("Should return req payload", () =>{
 spyOn(console, "log").and.callThrough();
 expect(console.log).toHaveBeenCalledWith("myFunc")
})

})
ANKIT MISHRA
  • 558
  • 4
  • 13