2017-06-13 63 views
0

當使用testdouble.js進行測試時,td.replace是否可以在node.js模塊中使用內部函數?用testdouble.js代替內部函數?

內部函數由一個數據庫調用組成,所以我不想測試它。然而我想測試這個函數是否收到了預期的參數。

例如,給定一個Node.js的模塊:

module.exports = { record: recordEvent } 

recordEvent = (event) => 
    var dbModel = map(event); 
    persist(dbModel); 

var map = (event) => 
    // some code that transforms event to the db specific representation (testable) 

var persist = (model) => 
    // some SQL insert/update code here (not testable) 

而下面的測試,如果堅持得到正確的PARAMS,檢查:

recorder = require('event_recorder') 
describe 'Event recorder module', -> 
    it 'converts the event to a db model', -> 

     var event = {...// mock event }; 
     var model = {...// mock model of the event }; 

     var persist = td.replace(recorder, 'persist') 
     td.when(persist(model)).thenReturn(true) 

     result = recorder.record(event) 
     expected = true; 

     result.should.be.equal(expected) 

但是測試拋出一個錯誤:

td.replace - No "persist" property was found

我明白爲什麼它有這個錯誤,因爲堅持的方法是不公開的。我怎麼能在testdouble中做到這一點?

回答

1

您暗示的一種選擇是公開persist方法。另一種選擇是對persist接受或使用其他功能的執行SQL查詢和存根函數:

var executeQuery = td.function() 

recorder.recordEvent(event, executeQuery) 

td.verify(executeQuery('UPDATE ...'))