使用Jest模拟节点Http请求的回调响应功能

时间:2020-07-30 20:23:42

标签: node.js typescript mocking jestjs

嗨,我想模拟Http Request函数中的响应。我在网上找不到任何东西,说明我们如何模拟回调并将其传递给函数。

文件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();
  });
};

文件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(),
      };
    });
  });
});

我将http.ts(以http.request的简单模拟为jest.fn)保存在应用程序根目录的 mock 文件夹中。

这里我要模拟响应回调函数,该函数将作为参数传递。

1 个答案:

答案 0 :(得分:0)

尽管我没有得到上述问题的答案,但有关如何在Http Request函数中模拟模拟回调的信息。但是,我找到了一种使用Nock测试这些类型的请求的方法。我只是发布答案以防万一:

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")});
    });

})

上述测试文件将能够使用Nock模拟请求并提供所需的状态代码。

相关问题