2016-04-26 13 views
0

httpsを使用してレスポンスURLにデータを送信するテスト対象モジュールがあります。これを行う前に、AWS SDKを呼び出します。 AWS SDKがhttpsを使用して呼び出しをスタブしたくないのですが、テスト中のモジュールが使用するhttps.postへの呼び出しをスタブする必要があります(問題がある場合はAWS Lambdaユニットテストです)。Sinonテスト中のモジュールのみのNodeJSスタブ

は、私はこれを実現するにはどうすればよい

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

次のテストコードテスト(app.js)下

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

そして、私のモジュールを考えてみましょうか?

答えて

1

nockを使用して、関数呼び出しではなく特定のHTTP/S要求をモックできます。

nockを使用すると、URLとリクエストマッチャーを設定できます。リクエストマッチャーを使用すると、定義したリクエストと一致しないリクエストが許可されます。

例:

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

これは200で応答https://www.something.com/the-post-path-to-mockにのみインターセプトPOST呼び出し、希望、および他の要求を無視します。

Nockには、応答を嘲笑したり、元の要求データにアクセスするためのさまざまなオプションもあります。

関連する問題