2016-07-28 52 views
0
的NodeJS使用

Sinon工作Mocha我在我的代碼的NodeJS兩種方法一樣「this」引用不

function method1(id,callback){ 
    var data = method2(); 
    callback(null,data); 
} 

function method2(){ 
    return xxx; 
} 

module.exports.method1 = method1; 
module.exports.method2 = method2; 

測試函數方法1,我不得不stub方法方法2。 爲此需要使用此測試用例通過調用方法方法2是

function method1(id,callback){ 
     var data = this.method2(); 
     callback(null,data); 
} 

試驗規程這個

describe('test method method2', function (id) { 
    var id = 10; 
    it('Should xxxx xxxx ',sinon.test(function(done){ 
     var stubmethod2 = this.stub(filex,"method2").returns(data); 
     filex.method1(id,function(err,response){ 
     done(); 
     }) 
    }) 
}) 

,但停止代碼錯誤工作this.method2不是功能。

有什麼辦法可以擺脫thismodule.exports這似乎越野車。

請讓我知道如果我錯過了任何其他信息..

+0

你能提供完整的測試文件代碼嗎? – semanser

+0

你有這個工作嗎? – alexi2

+0

沒有像代碼工作或測試用例一樣權衡 – mukul

回答

0

您沒有使用正確module.exports。

你的代碼更改爲:

export function method1(id,callback){ 
    var data = method2(); 
    callback(null,data); 
} 

export function method2(){ 
    return xxx; 
} 

然後:

const MyFuncs = require('path_to_file_with_methods');

如果你需要的方法,這樣調用:

MyFuncs.method1(){} MyFuncs.method2(){}

文檔module.exports

您也可以按照以下方式使用module.exports。

module.exports = { 
    method1: method1, 
    method2: method2 
} 

並要求以同樣的方式。

編輯:

請注意,如果您的版本支持它,你也可以在你的出口一點語法糖:

module.exports = { 
    method1, 
    method2 
} 

這在一般的對象文字符號成立。

+0

任何版本的節點(官方)都不支持模塊API(IIRC)。我會建議使用第二個選項 – MayorMonty

+1

使用此引發以下錯誤 **語法錯誤:意外的保留字 at exports.runInThisContext(vm.js:53:16) at Module._compile(module.js:414:25) 在Object.Module._extensions..js(module.js:442:10)** – mukul

+0

嘗試'模塊。出口= { 方法1:方法1,方法2 :方法2 }' – alexi2