2016-07-28 40 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

相关问题