Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Qunit对javascript函数进行单元测试_Javascript_Jquery_Qunit - Fatal编程技术网

使用Qunit对javascript函数进行单元测试

使用Qunit对javascript函数进行单元测试,javascript,jquery,qunit,Javascript,Jquery,Qunit,是否可以创建一个可以测试ui方面的单元测试?以下是一个例子: addMessage = function (type, message) { //success, error, info, block(alert) $("body").append('<div id="messageCenter" class="alert alert-' + type + '" style="position: fixed; top: 0; width

是否可以创建一个可以测试ui方面的单元测试?以下是一个例子:

addMessage = function (type, message) {
        //success, error, info, block(alert)           
        $("body").append('<div id="messageCenter" class="alert alert-' + type + '" style="position: fixed; top: 0; width: 100%; text-align:center;">' + message + '</div>');
        setTimeout(function () {
            $("#messageCenter").fadeOut(500, function () {
                $("#messageCenter").remove();
            });
        }, 10000);

    }
addMessage=函数(类型,消息){
//成功、错误、信息、阻止(警报)
$(“正文”)。附加(“”+消息+“”);
setTimeout(函数(){
$(“#消息中心”).fadeOut(500,函数(){
$(“#消息中心”).remove();
});
}, 10000);
}

这将在页面顶部创建一个消息栏,向用户显示一些信息。有人能帮我举一个这个函数的单元测试的例子吗?提前谢谢

单元测试无法100%可靠地测试可视元素,您应该始终手动确认它们是否正常工作,但总有一些事情可以做。如果没有其他原因,那么为了完整性或代码覆盖率

首先描述函数应该做什么,以及您希望测试涵盖哪些内容。例如:

  • 将向页面添加一条消息
  • 消息内容正确
  • 容器具有与消息类型对应的类
  • 10.5秒后,该消息在页面上不再可见(超时+淡出)
  • 现在很容易为特定需求编写单元测试

    asyncTest( "Message bar functionality", function() {
        expect( 4 );
    
        addMessage( 'info', 'test' );
        equal( $( '#messageCenter' ).length, 1, "Div created" );
        equal( $( '#messageCenter.alert-info' ).length, 1, "Message has correct class" );
        equal( $( '#messageCenter' ).text(), 'test', "Message has correct content" );
    
        setTimeout( function() {
            equal( $( '#messageCenter' ).length, 0, "Message no longer visible after 11 seconds" );
            start();
        }, 11000 ); // 10500 might be too tight, 10600 would probably be fine too
    });