函数修改不反映在输出中

Function modification does not reflect in output

我有以下代码要测试。

module.exports = {
    // src/code.js
    cl: function(param){
      this.foo = function(){
        return "foo" + param;
      };
    },

    bar: function(param){
      var t = new cl(param);
      console.log(t.foo());
      return t.foo();
    }
};

测试如下:

// tst/test.js
var code = require("../src/code");

QUnit.module("Testing");

QUnit.test("test", function(assert){
    assert.equal("foo", code.bar(""));
});

QUnit.test("test mock", function(assert){
    code.cl = function(param){
      this.foo = function(){
        return "Mock:" + param;
      };
    };

    console.log(code.cl.toString());

    assert.equal("Mock:", code.bar(""));
});

我正在运行测试使用以下命令:

qunit -c ./src/code.js -t ./tst/test.js

函数体的日志打印如下:

function (param){
    this.foo = function(){
        return "Mock:" + param;
    };
    }

但是,第二个断言失败了。

Actual value:
Mock:
Expected value:
foo

行为似乎不一致。

我觉得不对劲的是 clbar 中的对象创建。当您引用对象的方法时,您必须为其添加 this

module.exports = {
    cl: function(param){
      this.foo = function(){
        return "foo" + param;
      };
    },
    bar: function(param){
      var t = new this.cl(param); //updated cl call with this
      console.log(t.foo());
      return t.foo();
    }
};

试试这个,如果你的测试通过了请告诉我。

编辑:
var t = new this.cl(param);
在这里,之前引用 cl 时没有 这个。我不确定为什么它没有抛出任何错误。我在浏览器控制台测试了类似的代码。

test = {
    cl: function(param){
      this.foo = function(){
        return "foo" + param;
      };
    },
    bar: function(param){
      var t = new cl(param);
      console.log(t.foo());
      return t.foo();
    }
};
test.bar("");


它抛出一个错误,指出 cl 未定义。

Uncaught ReferenceError: cl is not defined
    at Object.bar (<anonymous>:10:15)
    at <anonymous>:1:6

当您导出包含 cl 方法的对象时,您必须在 bar 中使用 this 引用它.