使用 Nock 模拟 NodeJS 请求和响应

Mocking NodeJS request and response with Nock

我正在尝试掌握工具 Nock 以模拟来自我的代码执行调用的请求和响应。我使用 npm 请求作为一个简单的 HTTP 客户端来请求后端 REST API,Chai 用于期望库,Mocha 用于 运行 我的测试。这是我用于测试的代码:

 var nock = require('nock');
 var storyController = require('../modules/storyController');

 var getIssueResponse = {
   //JSON object that we expect from the API response.
 }

 it('It should get the issue JSON response', function(done) {
   nock('https://username.atlassian.net')
   .get('/rest/api/latest/issue/AL-6')
   .reply(200, getIssueResponse);

   storyController.getStoryStatus("AL-6", function(error, issueResponse) {
   var jsonResponse = JSON.parse(issueResponse);

   expect(jsonResponse).to.be.a('object');
   done();
 })
});

这里是执行 GET 请求的代码:

 function getStoryStatus(storyTicketNumber, callback) {
   https.get('https://username.atlassian.net/rest/api/latest/issue/' + storyTicketNumber, function (res) {

   res.on('data', function(data) {
    callback(null, data.toString());
   });

   res.on('error', function(error) {
    callback(error);
   });
  })
 }

这个单项测试通过了,我不明白为什么。看起来它实际上是在进行真正的调用,而不是使用我的假箭尾 request/response。如果我评论箭尾部分或更改:

 .reply(200, getIssueResponse) to .reply(404)

它没有破坏测试,也没有任何变化,我没有对我的诺克变量做任何事情。有人可以用一个清晰​​的例子向我解释如何使用 Nock 在我的 NodeJS http 客户端中模拟请求和响应吗?

TLDR:我认为您的代码所做的比它告诉您的要多。

重要说明:当在 "stream mode" 中放置一个 http 请求时,data 事件可能(并且可能确实)被多次触发,每个 "chunk" 数据,超过互联网块可以在 1400 到 64000 字节之间变化,所以预计 多个 回调调用(这是一种非常特殊的坏处)

作为一个简单的建议,您可以尝试使用 request 或只是连接接收到的数据,然后在 end 事件上调用回调。

我已经使用后一种技术尝试了一个非常小的片段

var assert = require('assert');
var https = require('https');
var nock = require('nock');

function externalService(callback) {
  // directly from node documentation:
  // https://nodejs.org/api/https.html#https_https_get_options_callback
  https.get('https://encrypted.google.com/', (res) => {

    var data = '';
    res.on('data', (d) => {
      data += d;
    });

    res.on('end', () => callback(null, JSON.parse(data), res));
  // on request departure error (network is down?)
  // just invoke callback with first argument the error
  }).on('error', callback);
}


describe('Learning nock', () => {
  it('should intercept an https call', (done) => {
    var bogusMessage = 'this is not google, RLY!';

    var intercept = nock('https://encrypted.google.com').get('/')
      .reply(200, { message: bogusMessage });

    externalService((err, googleMessage, entireRes) => {
      if (err) return done(err);

      assert.ok(intercept.isDone());
      assert.ok(googleMessage);
      assert.strictEqual(googleMessage.message, bogusMessage);
      assert.strictEqual(entireRes.statusCode, 200);

      done();
    });

  })
})

它工作得很好,即使使用 on('data')

编辑:

Reference on how to handle correctly a stream

我已将示例扩展为成熟的 mocha 示例