**更新。根据下面的评论,用例可能并不清楚。 扩展,在我的应用程序模块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