使用qunit测试我的代码时出错

时间:2013-10-21 13:45:58

标签: javascript jquery qunit

这是应用程序的代码。 所有其余功能都是从init()调用的。

如何开始使用qunit测试代码,因为如果我直接调用tests.js文件中的函数,它会显示“ReferenceError: init is not defined”。

var SOUND;
(function ($, undefined) {
// some code here 
// and has variables and functions defined which get called inside this and are all interdependent.


init = function () {
   } 

})(jQuery);

1 个答案:

答案 0 :(得分:0)

您的问题是您在IFFE内声明了init函数,并且该函数范围之外的任何内容都无法访问它。您可以使用一个非常简单的模块来解决这个问题。从IFFE返回init方法并将其赋值给变量的模式。

<强> JS

// "namespace" for your application.
// Whatever your IFFE returns is assigned to the App variable
// this allows other scripts to use your application code
var App = (function ($, undefined) {

    // some code here 
    // and has variables and functions defined which get called inside this and are all interdependent.

    // example of a function inside your "application" js
    var printTitle = function () {
        var title = document.title;
        console.log(title);
    }

    var init = function () {
        printTitle();
    }

    // expose internal methods by returning them.
    // you should probably be exposing more than your init method
    // so you can unit test your code
    return {
        init: init
    }
})(jQuery);


// since we've returned the init function from within our iffe
// and that function is assigned to the App variable
// we are able to call App.init here
App.init(); // logs title

JSFiddle

我发现以下文章有助于接近js测试: