Mocking the callback response function of Node Http Request using jest

Viewed 1932

Hi I want to mock the response in Http Request function. I could not find anything on net, that states how we can mock a callback and pass it on to the function.

File 1: HTTPfile.ts

import https from 'https';
const putSampleDataAsync = (): Promise<string> => {
  var options = {
    host: 'sample.com',
    path: '/upload',
    method: 'PUT',
  };
  const body = [];

  return new Promise(function (resolve, reject) {
    var req = https.request(options, function (res) {
      res.on('data', function (chunk) {
        body.push(chunk);
      });
      res.on('end', function (chunk) {
        body.push(chunk);
        resolve(res.statusCode.toString());
      });
    });

    req.on('error', function (error) {
      reject(error);
    });
    req.write('some sample data in stringify Json format');
    req.end();
  });
};

File 2: HTTPfile.test.ts

import putSampleDataAsync from 'HTTPfile';
import https from 'https';

jest.mock('https');

describe('Mocking HTTP Calls Test', () => {
  test('Success - ', () => {
    (https.request as jest.Mock).mockImplementation((options, response) => {
      console.log('How to mock ..!' + response);
      return {
        on: jest.fn(),
        write: jest.fn(),
        end: jest.fn(),
      };
    });
  });
});

I kept the http.ts (with a simple mock of http.request as jest.fn) in mock folder in root of my application.

Here I want to mock response callback function which is getting passed as a parameter.

1 Answers

Although I didn't get the answer for above question, on how to mock the mock callback in Http Request function. However I found a way around to test these type of request using Nock. I am just posting the answer in case it helps anyone:

HttpFile.test.ts

import putSampleDataAsync from 'HTTPfile';
import nock from 'nock';

describe('Mocking HTTP Calls Test ', () => {

    it(' - Success ', () => {
        nock('https://' + 'sample.com')
        .put('/upload')
        .reply(200, { results: {} });

    return putSampleDataAsync()
        .then(res => {expect(res).toEqual("200")});
    });

    it(' - Failed Response ', () => {
        nock('https://' + 'sample.com')
        .put('/upload')
        .reply(400, { results: {} });

    return putSampleDataAsync()
        .then(res => {expect(res).toEqual("400")});
    });

})

The above mentioned test file will be able to mock the request using Nock and will provide required status codes.

Related