**更新。根據下面的評論,用例可能並不清楚。 擴展,在我的應用程序模塊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(),所以它裏面的邏輯不會被調用。
您可能會得到更好的幫助,如果你解釋你要完成的任務。 「rewire()在匿名函數中的bar()方法」不是一個有意義的解釋(至少對我來說)。你究竟在努力完成什麼?期望的最終結果是什麼? – jfriend00
在我的應用程序中,bar()會執行更多邏輯並調用其他函數,但最終結果是它返回true或false。我試圖在我的測試套件中存儲bar()函數,以便在不同的測試場景中返回true/false。在Mocha中使用rewire()來測試foo()的功能而不調用bar()中的邏輯。合理? – tagyoureit