功能修改不会反映出输出



我有以下我要测试的代码。

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

行为似乎不一致。

我看起来不错的是 cl 的对象创建 bar> bar 。当您引用对象的方法时,您必须与IT一起添加 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 在没有> this 的情况下引用了。我不确定为什么它不会丢任何错误。我在浏览器控制台中测试了类似的代码。

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 。。