2017-01-22 42 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')