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

5

背景:

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

我们计划将JavaScript单元测试引入到我们现有(遗留)代码和未来的工作中。我们主要使用Java(Spring,Weblogic等)。

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

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、datatables、ajax等进行交互的点使得重构变得非常复杂,无法像Java世界中那样使其更易于测试。

因此,对于上述示例情况的任何建议都将不胜感激!


2
请参阅在Jasmine测试中测试DOM操作 - Richard JP Le Guen
请注意PhantomJS无头浏览器WebKit。 - obimod
2个回答

6

为了测试以下代码:

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 );

正如你所看到的,这只是经典的设置-运行-断言模式。

拆除那些DOM对象,这样你就不会有一个测试干扰另一个测试了,这个做法怎么样?如果可以的话,如何实现? - Greg Woods
2
@GregWoods 好的,你可以使用类似于 $('#fldOccupation').remove(); $('#fldOccupation_Details').remove(); 或者简单的 $( document.body.children ).remove(); 来删除它们。 - Florian Margaine

4

也许Selenium/SeleniumGrid对您有用:http://seleniumhq.org/

它并非按照定义是"UnitTest",但您可以使用Java或Python(和其他更多语言)编写Selenium测试作为单元测试。Selenium测试在真实浏览器中启动Web测试,并且非常适合测试前端(以及DOM操作)。

编辑:今天我偶然发现了这个网站,其中描述了特别适用于jQuery背景下的不同单元测试方法:http://addyosmani.com/blog/jquery-testing-tools/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接