简体   繁体   English

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

[英]Unit testing javascript function with Qunit

It is possible to create a unit test that can test ui aspects? 有可能创建一个可以测试ui方面的单元测试吗? here is an example: 这是一个例子:

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

    }

This creates a message bar at the top of the page to show the user some information. 这会在页面顶部创建一个消息栏,向用户显示一些信息。 Can someone help me with an example of the unit test for this function? 有人可以帮我提供这个功能的单元测试示例吗? Thanks in advance. 提前致谢。

Unit tests can't test visual elements 100% reliably and you should always confirm manually that they work, but there's always something you can do. 单元测试无法100%可靠地测试视觉元素,您应该始终手动确认它们是否有效,但总有一些事情可以做。 If for nothing else then for the sake of completeness or code coverage. 如果没有别的,那么为了完整性或代码覆盖。

First describe what the function is supposed to do and what you want the tests to cover. 首先描述函数应该做什么以及您希望测试覆盖什么。 For example: 例如:

  1. A message is added to the page 消息将添加到页面中
  2. The message has correct content 邮件内容正确
  3. The container has a class corresponding to the message type 容器具有与消息类型对应的类
  4. After 10.5 seconds the message is no longer visible on the page (timeout + fadeout). 10.5秒后,页面上不再显示该消息(超时+淡出)。

It's now easy to write the unit tests for the specific requirements. 现在可以轻松编写针对特定要求的单元测试。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM