【问题标题】:"this" reference is not working in nodeJs“this”引用在 nodeJs 中不起作用
【发布时间】:2016-12-02 18:52:44
【问题描述】:

我的 nodeJs 代码中有两种方法,例如

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

function method2(){
  return xxx;
}

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

为了使用SinonMocha 测试函数method1,我必须使用stub 方法method2。 为此需要将方法method2调用为

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 is not a function。

有什么办法可以摆脱 thismodule.exports 这似乎是错误的。

如果我错过任何其他信息,请告诉我..

【问题讨论】:

  • 能否提供完整的测试文件代码?
  • 你搞定了吗?
  • 这不像是代码工作或测试用例工作的权衡

标签: javascript node.js unit-testing mocha.js sinon-chai


【解决方案1】:

使用箭头函数修正此方法

在你的情况下

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

可以改成

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

【讨论】:

    【解决方案2】:

    您没有正确使用 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
    }
    

    这适用于一般的对象文字符号。

    【讨论】:

    • 任何版本的节点(官方)目前都不支持模块 API(IIRC)。我建议使用第二个选项
    • 使用这个会引发以下错误 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)
    • 试试module.exports = { method1: method1, method2: method2 }
    • 不会在声明行抛出语法错误export function method1(id,callback)
    • 你能把更多的相关代码放上来吗?您如何出口,以及您在哪里进口。加上测试?
    猜你喜欢
    • 1970-01-01
    • 2016-06-09
    • 2021-11-01
    • 2016-08-09
    • 2011-12-13
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    相关资源
    最近更新 更多