2017-07-05 59 views
0

我正在研究一個現有的節點項目,其中大多數js文件的代碼結構如下所示。使用外部模塊進行JavaScript單元測試

var mod1 = require("mod1"); 
    var mod2 = require("mod2"); 
    var modn = require("moden"); 


    function func1(data, callback) { 
     // Do some validation with data etc.. 
     // Use one or more imported modules here 

    } 

    function func2(data, callback) { 
     // Do some validation with data etc.. 
     // Use one or more imported modules here 

    } 


    exports.func1 = func1 
    exports.func2 = func2 

單元測試func1時,如何不依賴導入的模塊?我如何模擬/存根他們? 我來自Java世界,所以我熟悉模擬概念,但在這裏我不確定如何使用require來模擬全局聲明的模塊導入。

目前我們正在使用nodeunit進行單元測試,但它測試了很小一部分代碼。

我在閱讀有關simon.js和testdouble,但不知道如何使用它們來模擬全局變量。

任何幫助/方向表示讚賞。

+0

我是supp因爲'func1'在內部使用了一些依賴關係,例如'mod1'。如果'func1'取決於所需的模塊。你爲什麼要嘲笑它而不是使用真正的依賴關係? –

+1

http://sinonjs.org/how-to/link-seams-commonjs/ –

+1

https://github.com/testdouble/testdouble.js/blob/master/docs/7-replacing-dependencies.md#replacing-真正的依賴與測試雙打 –

回答

0

對於測試期間壓倒一切的依賴性,我建議在您的情況使用https://github.com/thlorenz/proxyquire模塊

爲了快速exmple我粘貼項目的github

foo.js:

var path = require('path'); 

module.exports.extnameAllCaps = function (file) { 
return path.extname(file).toUpperCase(); 
}; 

module.exports.basenameAllCaps = function (file) { 
return path.basename(file).toUpperCase(); 
} 

foo.test.js:

var proxyquire = require('proxyquire') 
, assert  = require('assert') 
, pathStub = { }; 

// when no overrides are specified, path.extname behaves normally 
var foo = proxyquire('./foo', { 'path': pathStub }); 
assert.equal(foo.extnameAllCaps('file.txt'), '.TXT'); 
例子