javascript - "this" reference is not working in nodeJs -
i have 2 methods in nodejs code
function method1(id,callback){ var data = method2(); callback(null,data); } function method2(){ return xxx; } module.exports.method1 = method1; module.exports.method2 = method2;
for testing function method1 using sinon
, mocha
had stub
method method2. required call method method2
function method1(id,callback){ var data = this.method2(); callback(null,data); }
test code this
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(); }) }) })
using test cases passed, code stopped working error this.method2 not function.
is there way can rid of this
or module.exports
seems buggy.
please let me know if missed other info..
you not using module.exports correctly.
change code to:
export function method1(id,callback){ var data = method2(); callback(null,data); } export function method2(){ return xxx; }
and then:
const myfuncs = require('path_to_file_with_methods');
where need methods, called this:
myfuncs.method1(){}
myfuncs.method2(){}
the docs module.exports
you can use module.exports in following manner.
module.exports = { method1: method1, method2: method2 }
and require in same fashion.
edit:
note if version supports can bit of syntactic sugar in exports:
module.exports = { method1, method2 }
which holds object literal notation in general.
Comments
Post a Comment