2016-07-28 10 views
1

node-mssqlライブラリを使用してSQLからデータをプルします。私はしばらくの間Sinonを使ってきました。このライブラリをどのようにスタブするのか、頭がおかしくなります。コードは次のようになります。mssqlライブラリを使用してSinonを使用してデータベースとのやり取りをスタブするにはどうすればよいですか?

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を見つけることができません。

私はここにいません。誰かがこれを行うコードをいくつか持っているとか、私が間違っていることを説明できると思っています。

答えて

0

私はそれを解決することができましたが、何らかの理由でちょっとハッキリしています。おそらく、私がnew sql.Request(conn)コールをスタブする方法を決して分かったのではないでしょうか。

理想的には私はmodule.exportsにSQLライブラリを含めることなくこの作業をしたいと考えています。私はrequestライブラリでそれを行うことができますが、数時間後にこのライブラリをノックアウトしても、同じ方法で動作させることはできません。

まず:

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; 
SQLライブラリをエクスポートします
関連する問題