【问题标题】:How do I use Sinon to stub interaction with a database using mssql library?如何使用 Sinon 存根与使用 mssql 库的数据库的交互?
【发布时间】:2016-12-03 06:08:29
【问题描述】:

使用node-mssql 库从 SQL 中提取数据。我已经使用 Sinon 有一段时间了(用它写了大约 200 个测试);在如何将这个库排除在外时遇到了很多麻烦。代码如下:

var sql = require('mssql');
var conn = new sql.Connection(sqlConfig); // sqlConfig is connection info, defined elsewhere 

conn.connect(function(err) {
  var req, selectFromTable;
  if (err != null) {
    // handle error
  }
  req = new sql.Request(conn);
  selectFromTable = "select * from DW." + table + " where DWCreatedDate >= '" + start + "' and DWCreatedDate <= '" + end + "' ";
  logger.debug("Selecting with: ", selectFromTable);
  req.input('statement', sql.NVarChar, selectFromTable);
  return req.execute('sp_executesql', function(err, results, returnValue, affected) {
    if (err != null) {
      // etc.
    } else {
      // data processing   
    }
  });
});

代码运行良好。现在我正在尝试为它编写一个测试。我知道这个库很难测试,所以我拖延了。我最接近的代码:

var conn, reqExecute, sqlReqStub; 
sqlReqStub = sinon.stub(); 
sqlReqStub.execute = sinon.stub(); 
sinon.stub(sql, 'Request').returns(sqlReqStub); 
conn = sinon.stub(); 
sinon.stub(sql, 'Connection').returns(conn);

conn.connect = sinon.stub().callsArgWith(0, null);

reqExecute = sqlReqStub.execute.withArgs('sp_executesql').onFirstCall().callsArgWith(1, null, {
  a: 1
});

您的自然倾向可能是说“好吧,使用 createStubInstance”,但是当我使用它时,我会返回具有 TediousRequest 的连接对象 (new sql.Connection(config))(当它在内部构建驱动程序对象时库默认为连接)在它们中,而不是我的存根请求。我在 sql 对象的任何地方都找不到 TediousRequest 来存根。

我被困在这里;希望有人有一些代码可以做到这一点,或者可以解释我做错了什么。

【问题讨论】:

    标签: sql-server node.js sinon node-mssql


    【解决方案1】:

    好吧,我确实设法解决了这个问题,但由于某种原因感觉有点 hacky。可能是因为我从来不知道如何存根 new sql.Request(conn) 调用。

    理想情况下我希望无需在我的module.exports 中包含 sql 库就可以正常工作。我可以使用request 库来做到这一点,但是在敲掉这个库几个小时后,我无法让它以同样的方式工作。

    首先:导出sql库:

    sql = require('mssql')
    // much code
    module.exports.sqlLib = sql
    

    第二个:存根的东西:

      var connection, sqlReqStub, sqlStubLib;
      var server = require('./index.js')    
      sqlStubLib = {};    
      connection = new EventEmitter();    
      connection.connected = true;    
      connection.close = function() {};    
      connection.connect = sinon.stub().callsArgWith(0, null);    
      sqlStubLib.Connect = sinon.stub();    
      sqlStubLib.Connection = function() {
        return connection;
      };    
      sqlReqStub = sinon.stub();    
      sqlReqStub.input = function() {};    
      sqlReqStub.execute = sinon.stub();    
      sqlReqStub.execute.withArgs('sp_executesql').onFirstCall().callsArgWith(1, null, [
        [
        // js object 
        ]
      ], null, null);
    
      sqlStubLib.Request = function() {
        return sqlReqStub;
      };
    
      server.sqlLib = sqlStubLib;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-16
      • 2015-03-29
      • 2015-04-10
      • 2013-03-15
      • 1970-01-01
      • 2020-06-25
      • 2012-02-07
      • 2021-04-28
      相关资源
      最近更新 更多