【问题标题】:Sinon NodeJS stub only for module under testSinon NodeJS 存根仅适用于被测模块
【发布时间】:2016-04-26 14:58:50
【问题描述】:

我有一个正在测试的模块,它使用https 将数据放入响应 URL。在此之前,它会调用 AWS 开发工具包。我不想存根 AWS SDK 使用 https 进行的调用,但我确实想存根对我正在测试的模块使用的 https.post 的调用(如果重要的话,它是一个 AWS Lambda 单元测试)。

考虑下面的测试代码

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

我怎样才能做到这一点?

【问题讨论】:

    标签: node.js mocha.js sinon


    【解决方案1】:

    您可以使用 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响应,并忽略其他请求。

    Nock 还提供了许多用于模拟响应或访问原始请求数据的选项。

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 2018-06-15
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2020-11-23
      • 2022-01-26
      • 2020-07-07
      相关资源
      最近更新 更多