javascript - 如何对与 DOM 元素交互的 Javascript 代码进行单元测试

标签 javascript jquery unit-testing qunit js-test-driver

背景:

我来自 Java 背景,所以不太熟悉 Javascript。

我们计划将 JavaScript 单元测试引入到我们现有的(遗留)代码和 future 的工作中。我们主要是一家 java 商店(Spring、Weblogic 等)。

我们正在寻找能够让我们与 IDE(IntelliJ idea)和声纳良好集成的选项,并能够将它们作为持续集成的一部分运行。

JsTestDriver 似乎符合所有条件。

问题:

我们现有的许多 javascript 代码是 a) 嵌入在 JSP 中和 b) 利用 jQuery 直接与页面元素交互。

我们应该如何着手测试一个严重依赖 DOM 的函数。以下是我正在谈论的函数的一些代码示例:

function enableOccupationDetailsText (){
    $( "#fldOccupation" ).val("Unknown");
    $( "#fldOccupation_Details" ).attr("disabled", "");
    $( "#fldOccupation_Details" ).val("");
    $( "#fldOccupation_Details" ).focus();
}

jQuery(document).ready(function(){

    var oTable = $('#policies').dataTable( {
            "sDom" : 'frplitip',
                "bProcessing": true,
                "bServerSide": true,
                "sAjaxSource": "xxxx.do",
                "sPaginationType": "full_numbers",
                "aaSorting": [[ 1, "asc" ]],
                "oLanguage": {
                    "sProcessing":   "Processing...",
                    "sLengthMenu":   "Show _MENU_ policies",
                    "sZeroRecords":  "No matching policies found",
                    "sInfo":         "Showing _START_ to _END_ of _TOTAL_ policies",
                    "sInfoEmpty":    "Showing 0 to 0 of 0 policies",
                    "sInfoFiltered": "(filtered from _MAX_ total policies)",
                    "sInfoPostFix":  "",
                    "sSearch":       "Search:",
                    "sUrl":          "",
                    "oPaginate": {
                        "sFirst":    "First",
                        "sPrevious": "Previous",
                        "sNext":     "Next",
                        "sLast":     "Last"
                }
            },
                "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                        $('td:eq(0)', nRow).html( "<a href='/ole/policy/general_details.do?policy_id="+aData[0]+"'>"+aData[0]+"</a>" );
                        return nRow;

                },

                "fnServerData" : function ( url, data, callback, settings ) {

                settings.jqXHR = $.ajax( {
                    "url": url,
                    "data": data,
                    "success": function (json) {
                        if (json.errorMessage != null) {
                            var an = settings.aanFeatures.r;
                            an[0].style.fontSize="18px";
                            an[0].style.backgroundColor="red";
                            an[0].style.height="70px";
                            an[0].innerHTML=json.errorMessage;
                            setTimeout('window.location="/xxxx"',1000);
                            //window.location="/xxxxx";
                        } else {
                            $(settings.oInstance).trigger('xhr', settings);
                            callback( json );
                        }
                    },
                    "dataType": "json",
                    "cache": false,
                    "error": function (xhr, error, thrown) {
                        if ( error == "parsererror" ) {
                            alert( "Unexpected error, please contact system administrator. Press OK to be redirected to home page." );
                            window.location="/xxxx";
                        }
                    }
                } );
                }

            } );
        $("#policies_filter :text").attr('id', 'fldKeywordSearch');
        $("#policies_length :input").attr('id', 'fldNumberOfRows');
        $("body").find("span > span").css("border","3px solid red");
        oTable.fnSetFilteringDelay(500);
        oTable.fnSearchHighlighting();
        $("#fldKeywordSearch").focus();

}
);

在后一种情况下,我的方法是所讨论的函数太大,应该分解成更小的(单元)以便对其进行测试。但是与 DOM、jQuery、数据表、ajax 等的所有交互点使得以我们在 Java 世界中所做的方式重构事物以使其更具可测试性变得非常复杂。

因此,我们将不胜感激对上述示例案例的任何建议!

最佳答案

测试以下代码:

function enableOccupationDetailsText (){
    $( "#fldOccupation" ).val("Unknown");
    $( "#fldOccupation_Details" ).attr("disabled", "");
    $( "#fldOccupation_Details" ).val("");
    $( "#fldOccupation_Details" ).focus();
}

您可以使用以下代码:

// First, create the elements
$( '<input>', { id: 'fldOccupation' } ).appendTo( document.body );
$( '<input>', { disabled: true, id: 'fldOccupation_Details' } )
    .appendTo( document.body );

// Then, run the function to test
enableOccupationDetailsText();

// And test
assert( $( '#fldOccupation' ).val(), 'Unknown' );
assert( $( '#fldOccupation_Details' ).prop( 'disabled' ), false );

如您所见,这只是经典的 setup > run > assert 模式。

关于javascript - 如何对与 DOM 元素交互的 Javascript 代码进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11081743/

相关文章:

php - JQuery AJAX 403 禁止访问

javascript - 如何使用 JQuery 提取嵌套 HTML 中的文本?

jquery - 无法让 Cycle2 轮播与文本叠加一起使用

python - 通过单元测试避免不必要的导入

c++ - 如何将 Boost.Test 输出记录到 HRF 中的标准输出和 XML 中的文件?

Javascript Select Box填充其他select box录制选项顺序

javascript - 从生成的 html 表中选择一行

unit-testing - XCTAssertEqual 与 Optional(不是 Equatable)

javascript - 不允许 HTTP PUT 请求

javascript - 具有不同模板的 Web 应用程序 (AngularJS)