2017-01-22 43 views
0

**更新。根據下面的評論,用例可能並不清楚。 擴展,在我的應用程序模塊foo()調用bar(),它做了一些複雜的邏輯並返回一個布爾值。我正在創建單元測試(Mocha)並嘗試使用rewire重新連接foo()方法,所以我可以在真正調用bar時將true/false返回到bar()中。使用rewire在NodeJS的匿名導出中存根功能

嘗試在匿名函數中存根(aka rewire)bar()方法。可能嗎?在嘗試了很多不同的方法之後,我看不出如何覆蓋bar()。

//foobar.js 
module.exports = function(config) { 

    function bar() { 
     console.log('why am i in _%s_ bar?', config) 
     //some logic 
     return true 
    } 

    function foo() { 
     if (bar()) { 
      console.log('should not get here, but someVar is passing: ', someVar) 
      return true 
     } else { 
      console.log('should get here, though, and we still see someVar: ', someVar) 
      return false 
     } 
    } 

    return { 
     foo: foo, 
     bar: bar 
    } 
} 

//rewire_foobar.js 
var rewire = require('rewire') 
var myModule = rewire(__dirname + '/foobar.js') 

myModule.__with__({ 
    'bar': function(){ 
     console.log('changing return to false from rewire') 
     return false 
    }, 
    'someVar': "abcde" 

})(function() { 

    var result = myModule('a').foo() 
    console.log('result is: ', result) 

}) 

給出了結果

why am i in _a_ bar? 
should not get here, but someVar is passing: abcde 
result is: true 

someVar被通過。但是我需要重新連接bar(),所以它裏面的邏輯不會被調用。

+0

您可能會得到更好的幫助,如果你解釋你要完成的任務。 「rewire()在匿名函數中的bar()方法」不是一個有意義的解釋(至少對我來說)。你究竟在努力完成什麼?期望的最終結果是什麼? – jfriend00

+0

在我的應用程序中,bar()會執行更多邏輯並調用其他函數,但最終結果是它返回true或false。我試圖在我的測試套件中存儲bar()函數,以便在不同的測試場景中返回true/false。在Mocha中使用rewire()來測試foo()的功能而不調用bar()中的邏輯。合理? – tagyoureit

回答

0

我找到了解決方法。我最初的目標是測試foo()和stub bar(),所以我可以控制結果/測試參數。如果有人能想出更好的解決方案,那將是非常棒的。

在這種方法中,每一個變量和函數調用都需要被存根/重新連線。對於我的測試來說沒問題,但對於所有解決方案可能都不可行。

我的解決方法是:

  1. 寫,把foo()函數到一個臨時文件。 (在測試中,這個 應該/可以在before()塊中完成)。

  2. 將函數作爲獨立函數進行測試。

  3. 刪除測試臨時文件。

下面是foobar.spec.js代碼:

var rewire = require('rewire') 
var foobar = require('./foobar.js') 
var fs = require('fs') 

//extracts the function to test and exports it as temp() 
//could be done in a before() block for testing 
var completeHack = 'exports.temp = ' + foobar().foo.toString() 
//write the function to a temporary file 
fs.writeFileSync(__dirname + '/temp.js', completeHack , 'utf8') 

//rewire the extracted function 
var myModule = rewire(__dirname + '/temp.js') 

myModule.__with__({ 
    //and stub/rewire and variables 
    'bar': function(){ 
     console.log('changing return to false from rewire') 
     return false 
    }, 
    'someVar': "abcde", 
    'config': 'not really important' 

})(function() { 
    //and test for our result 
    var result = myModule.temp() 
    console.log('result is: ', result) 

}) 

//and finally delete the temp file. Should be put in afterEach() testing function 
fs.unlinkSync(__dirname + '/temp.js')