0

I have two methods in my nodeJs code like

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 and Mocha i had to stub method method2. For which it required to call method method2 as

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

Test Code for 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 this test cases passed, But the code stopped working with error this.method2 is not a function.

Is there any way i can get rid of this or module.exports which seems buggy.

Please let me know if i missed any other info..

mukul
  • 433
  • 7
  • 18

2 Answers2

0

You are not using module.exports correctly.

Change your 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 you need the methods, called like this:

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

The docs for module.exports

You can also use module.exports in the following manner.

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

And require in the same fashion.

Edit:

Note that if your version supports it you can also a bit of syntactic sugar in your exports:

module.exports = {
    method1,
    method2
}

Which holds for object literal notation in general.

alex
  • 5,467
  • 4
  • 33
  • 43
  • The modules API isn't currently supported (IIRC) in any version of node (officially). I would recommend to use the second option – bren Jul 28 '16 at 23:48
  • 1
    Using this throws following error **SyntaxError: Unexpected reserved word at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:414:25) at Object.Module._extensions..js (module.js:442:10)** – mukul Jul 29 '16 at 09:08
  • Try the `module.exports = { method1: method1, method2: method2 }` – alex Jul 29 '16 at 09:15
  • No its throwing a Syntax Error at the declaration Line **export function method1(id,callback)** – mukul Jul 29 '16 at 10:28
  • Can you put more of the relevant code up? How you are exporting, and where you are importing. Plus the tests? – alex Jul 29 '16 at 11:52
0

use arrow function to correct this method

in your case

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

can be changed to

  let method1 = (id,callback)=>{
    var data = this.method2();
    callback(null,data);
  }
Rahul Somaraj
  • 251
  • 2
  • 9