Sinon NodeJS存根仅用于测试模块

问题描述:

我有一个测试模块,它使用https将数据放入响应URL。在这之前,它会调用AWS SDK。我不想存储AWS SDK使用https进行的调用,但我确实希望将调用存储到我测试的模块使用的https.post(如果这很重要,那么这是一个AWS Lambda单元测试)。Sinon NodeJS存根仅用于测试模块

考虑下面的测试代码

describe('app', function() { 
     beforeEach(function() { 
      this.handler = require('../app').handler; 
      this.request = sinon.stub(https, 'request'); 
     }); 

     afterEach(function() { 
      https.request.restore(); 
     }); 

     describe('#handler()', function() { 
      it('should do something', function (done) { 

       var request = new PassThrough(); 
       var write = sinon.spy(request, 'write'); 

       this.request.returns(request); 

       var event = {...}; 

       var context = { 
        done: function() { 
         assert(write.withArgs({...}).calledOnce); 
         done(); 
        } 
       } 

       this.handler(event, context); 
      }); 
     }); 
    }); 

而且我被测模块(app.js)

var aws = require("aws-sdk"); 
var promise = require("promise"); 
exports.handler = function (event, context) { 

    var iam = new aws.IAM(); 
    promise.denodeify(iam.getUser.bind(iam))().then(function (result) { 
     .... 
     sendResponse(...); 
    }, function (err) { 
     ... 
    }); 

}; 

// I only want to stub the use of https in THIS function, not the use of https by the AWS SDK itself 
function sendResponse(event, context, responseStatus, responseData) { 

    var https = require("https"); 
    var url = require("url"); 

    var parsedUrl = url.parse(event.ResponseURL); 
    var options = { 
     ... 
    }; 

    var request = https.request(options, function (response) { 
     ... 
     context.done(); 
    }); 

    request.on("error", function (error) { 
     ... 
     context.done(); 
    }); 

    // write data to request body 
    request.write(...); 
    request.end(); 
} 

我怎样才能做到这一点?

您可以使用nock来模拟特定的HTTP/S请求,而不是函数调用。

使用nock,您可以设置URL和请求匹配器,以允许通过的请求与您定义的请求不匹配。

如:

nock('https://www.something.com') 
    .post('/the-post-path-to-mock') 
    .reply(200, 'Mocked response!'); 

这只会拦截POST调用https://www.something.com/the-post-path-to-mock,具有200响应,而忽略其他请求。

诺克还提供了许多选项来嘲笑响应或访问原始请求数据。