简体   繁体   中英

Unit testing javascript function with Qunit

It is possible to create a unit test that can test ui aspects? 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. 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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