title: How do I use Sinon to stub interaction with a database using mssql library?
body: <p>Using the <a href="https://github.com/patriksimek/node-mssql" rel="nofollow">node-mssql</a> library to pull data from SQL. I've been using Sinon for a while now (written about 200 tests with it); having a ton of trouble getting my head around how to stub this library out. The code looks like: </p>
  
  <pre><code>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 &gt;= '" + start + "' and DWCreatedDate &lt;= '" + 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   
      }
    });
  });
  </code></pre>
  
  <p>Code works fine. Now I'm trying to write a test for it. I knew this library would be difficult to test so I procrastinated. My closest code: </p>
  
  <pre><code>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
  });
  </code></pre>
  
  <p>Your natural inclination might be to say "well, use <code>createStubInstance</code>" but when I use that I get back connection objects (<code>new sql.Connection(config)</code>) that have TediousRequest (what the library defaults to when it builds out the driver object inside of the connection) in them instead of my stub request. I can't find TediousRequest anywhere in the <code>sql</code> object to stub it out. </p>
  
  <p>I'm stuck here; hoping someone has some code around that does this or can explain what I'm doing wrong. </p>