繁体   English   中英

如何使用sinon.stub将单元测试编写为“请求”节点模块?

[英]how to write unit test to “request” node module with sinon.stub?

我的代码中有此功能:

let request = require("request");
let getDrillDownData = function (userId, query, callback) {

query.id = userId;
let urlQuery = buildUrlFromQuery(query);

request.get({
    url: urlQuery,
    json: true
}, function (error, response, data) {
    if (!error && response.statusCode === 200) {
        return callback(null, calculateExtraData(data));
    } else if (error) {
        return callback(error, null);
    }
});


};

我希望编写一些单元测试,以验证当使用正确的参数调用该函数时,该函数运行正常,并且如果出现错误,则确实返回了错误

我写了这个单元测试代码:

describe.only('Server Service Unit Test', function(){
var sinon = require('sinon'),
    rewire = require('rewire');

var reportService;
var reportData = require('./reportData.json');

beforeEach(function(){
    reportService = rewire('../../services/reports.server.service');
});

describe('report methods', function(){
    var reportData;
    var query = { id: "test"};
    var userId = 'testuser';
    var getDrillDownData;

    var request;

    beforeEach(function(){
        getDrillDownData = reportService.__get__('getDrillDownData');
    });

    it ('should get drill down data by userId and query', function(done){
        var getCallback = sinon.stub();

        request = {
            get: sinon.stub().withArgs({
                url: query,
                json: true
            }, getCallback.withArgs("error", {statusCode: 200}, reportData))
        };

        reportService.__set__('request', request);

        getDrillDownData(userId, query, function(err, returnData){
            (err === null).should.eql(true);
            //(getCallback.withArgs(undefined, {statusCode: 200}, reportData).calledOnce).equal(true);
            done();
        });
});
});

但我不断收到此错误:

错误:超时超过2000毫秒。 确保此测试中调用了done()回调。

有人可以帮忙吗? 谢谢

我直接存根request.get()

describe('report methods', function() {

  // Make `request.get()` a Sinon stub.
  beforeEach(function() {
    sinon.stub(request, 'get');
  });

  // Restore the original function.
  afterEach(function() {
    request.get.restore();
  });

  it ('should get drill down data by userId and query', function(done) {
    // See text.
    request.get.yields(null, { statusCode : 200 }, { foo : 'bar' });

    // Call your function.
    getDrillDownData('userId', {}, function(err, data) {
      ...your test cases here...
      done();
    });
  });
});

使用request.get.yields() (调用Sinon在参数列表中可以找到的第一个函数参数;在这种情况下,是(error, response, data)回调传递给函数中的request.get() ),您可以告诉Sinon使用哪些参数来调用回调。

这样,您可以检查request.get()的回调是否正确处理了所有参数。

您也可以使用.withArgs()request.get.withArgs(...).yields(...) ),尽管必须确保正确使用了它。 否则,如果确切的参数不匹配,则Sinon将调用原始的request.get()而不是使用存根版本。

相反,我更喜欢在调用之后使用stub.calledWith()来检查正确的参数。 这也可以与Mocha更好地集成,因为您可以使用显式断言。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM