Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test HttpService.Post calls using jest

I am calling a API in nestjs service like below,

import { HttpService, Post } from '@nestjs/common';

export class MyService {

constructor(private httpClient: HttpService) {}

public myMethod(input: any) {
    return this.httpClient
      .post<any>(
        this.someUrl,
        this.createObject(input.code),
        { headers: this.createHeader() },
      )
      .pipe(map(response => response.data));
  }
}

How can I mock/spyOn the call to this.httpClient.post() in jest to return response without hitting the actual API?

describe('myMethod', () => {
    it('should return the value', async () => {
      const input = {
        code: 'value',
      };
      const result = ['test'];

      // spyOn?

      expect(await myService.myMethod(input)).toBe(result);
  });
});
like image 956
Devrath N D Avatar asked Jan 22 '20 13:01

Devrath N D


2 Answers

Got it working by using spyOn.

describe('myMethod', () => {
    it('should return the value', async () => {
      const input = {
        code: 'mock value',
      };

      const data = ['test'];

      const response: AxiosResponse<any> = {
        data,
        headers: {},
        config: { url: 'http://localhost:3000/mockUrl' },
        status: 200,
        statusText: 'OK',
      };

      jest
        .spyOn(httpService, 'post')
        .mockImplementationOnce(() => of(response));

      myService.myMethod(input).subscribe(res => {
        expect(res).toEqual(data);
      });
  });
});
like image 71
Devrath N D Avatar answered Oct 17 '22 06:10

Devrath N D


A good alternative to mocking the http service would also be to declare it in the providers array as follow.

let httpClient: HttpService;
beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        {
          provide: HttpService,
          useValue: {
            post: jest.fn(() => of({
              // your response body goes here 
            })),
          },
        },
      ],
    }).compile();

    httpClient = module.get<HttpService>(HttpService);
  });

By providing your HttpService in the testing module rather than use spy on, you ensure that the HttpModule won't be imported or used and reduce your test code dependency to other services.

like image 30
Diaboloxx Avatar answered Oct 17 '22 04:10

Diaboloxx