簡體   English   中英

如何在jquery插件中單元測試內部函數?

[英]how to unit test internal functions in jquery plugin?

在一個jQuery插件中,我創建了輔助函數,就像這樣

(function($) {

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

// here goes the normal plugin code

})(jQuery);

現在我想從外面調用someHelperFunction,以便能夠對它進行單元測試,這有可能嗎?

根據這個相關問題 ,我只想測試外部接口。

但是,如果必須單獨測試這些方法,則必須在其部署的上下文之外測試它們的“副本”作為內部方法。 換句話說,創建一個客戶端代碼無法訪問它們的對象,然后在預處理過程中將這些版本與外部腳本拼湊在一起。 聽起來很多工作,但是,嘿,這是隱藏方法的重點,對吧? (使它們無法到達。)

您可能還想考慮JavaScript doctests。 我知道有兩個實現:Ian Bicking的doctest.js和我自己的doctest

如果內部函數需要測試,這是一個很好的指示,它們應該位於某個單獨的模塊中,並作為依賴項注入並在對象公共接口實現中使用。 這是更“可測試”的方式。

var myActualImplementationTestTheHellOutOfMe = function(s, d) {

    return s*d;

}

(function($, helper) {

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

// here goes the normal plugin code

})(jQuery, myActualImplementationTestTheHellOutOfMe);

幫助程序作用於插件內部,這是一個匿名函數,您無法訪問其中聲明的變量。
如果要測試它,請將var關鍵字放在函數前面。 這會將函數聲明為全局函數(將它們附加到窗口對象),使它們能夠從窗口范圍中看到(通過調用someHelperFunctionwindow.someHelperFunction )。
所以,測試:

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

測試結束后,再次添加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);

看看qunit ,一個JavaScript單元測試庫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM