如何在jquery插件中单元测试内部函数?

Joh*_*ith 6 javascript jquery unit-testing jquery-plugins

在一个jQuery插件中,我创建了辅助函数,就像这样

(function($) {

  var someHelperFunction = function(s, d) {
    return s*d;
  }
  var someOtherHelperFunction = function(s) {
    return s*2;
  }

// here goes the normal plugin code

})(jQuery);
Run Code Online (Sandbox Code Playgroud)

现在我想从外面调用someHelperFunction,以便能够对它进行单元测试,这有可能吗?

gio*_*_13 0

帮助程序的范围位于插件内部,这是一个匿名函数,您无法访问其中声明的变量。
如果你想测试它,请将var关键字放在函数前面。这会将函数声明为全局函数(将它们附加到窗口对象),使它们能够在窗口范围内可见(通过调用someHelperFunctionwindow.someHelperFunction)。
所以,为了测试:

(function($) {
    someHelperFunction = function(s, d) {
        return s*d;
    }
    someOtherHelperFunction = function(s) {
        return s*2;
    }
     // here goes the normal plugin code
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

测试结束后,var再次添加关键字。

更新
我认为更好的方法是将可测试函数分组到一个对象中 - 并构造一个 api。然后,根据同样的原则,您可以使该 api 在全局范围内可见或不可见:

(function($, global) {
    someHelperFunction = function(s, d) {
        return s*d;
    }
    someOtherHelperFunction = function(s) {
        return s*2;
    }

    var api = {
        someHelperFunction: someHelperFunction,
        someOtherHelperFunction: someOtherHelperFunction
    };

    // decide whether you want to expose your api or not 
    if(makeGlobal) {
        global.api = api;
    }
})(jQuery, this);
Run Code Online (Sandbox Code Playgroud)

  • 不要仅仅为了测试私有函数而使用全局变量。这不是一个好的答案,因为它认可了不良做法。 (3认同)