【问题标题】:Accessing out-of-scope methods for unit testing purposes访问超出范围的方法以进行单元测试
【发布时间】:2014-01-15 12:45:51
【问题描述】:

因为我使用的是 Zepto JavaScript 库,所以我的所有应用程序代码都必须封装在一个名为 Zepto 的函数中。直到最近,当我尝试编写单元测试时,这才成为问题。我意识到我无法访问我的 API,因为它在该函数的范围内。

这是我的主 JS 文件的样子:

Zepto(function(){
    var MyAPI = (function(){
        function myMethod() {
        ....
        }
        return {
            myMethod: myMethod
        }
    })(); 

    MyAPI.myMethod(); // works correctly
});

这是我的单元测试文件的样子(我正在使用 Qunit):

// include my main JS file 

test( 'MyAPI unit test', function() {
    // The test obviously fails because MyAPI is outside of scope
    ok( typeof MyAPI.myMethod === 'function', 'MyAPI is available' );
}); 

那么,我的问题是,如何为必须封装在 Zepto 函数中的 API 编写单元测试?换句话说,我怎样才能使这些方法在该函数上下文之外可用,以便对其进行测试?

【问题讨论】:

  • 你不会按照通常调用函数的方式来做吗?
  • MyAPI 无法在全局范围内访问,因为它是在 Zepto 函数中定义的。

标签: javascript unit-testing qunit zepto


【解决方案1】:

我能够通过将某些方法存储在全局变量中来解决这个问题。这提供了两全其美的效果,让我可以访问 Zepto 的功能,同时引用 Zepto 函数之外的方法。

更新主 JS 文件:

var app = {}; 

Zepto(function(){
    app.MyAPI = (function(){
        function myMethod() {
        ....
        }
        return {
            myMethod: myMethod
        }
    })(); 

    app.MyAPI.myMethod(); // works correctly
});

更新的测试套件文件:

setTimeout(function(){

    test( 'MyAPI unit test', function() {
        // The test now works because MyAPI is stored in the global 'app'
        ok( typeof app.MyAPI.myMethod === 'function', 'MyAPI is available' );
    }); 

}, 3000); // Give Zepto time to instantiate

【讨论】:

    猜你喜欢
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 2011-11-15
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多