2016-07-28 3 views
1

node-mssql 라이브러리를 사용하여 SQL에서 데이터를 가져옵니다. 나는 잠시 동안 Sinon을 사용 해왔다. (약 200 개의 테스트를 써서); 이 라이브러리를 뽑아내는 방법에 대해 머리를 써야하는 데 많은 어려움을 겪고 있습니다. 코드는 다음과 같습니다.Sinon을 사용하여 mssql 라이브러리를 사용하여 데이터베이스와의 상호 작용을 스텁하는 방법은 무엇입니까?

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 라이브러리를 수출