How can I display the unit test jquery dialog box?

I wrote the code below, try to check if the jquery dialog will apologize and display.

var jqueryMock = sinon.mock(jQuery);
var dialogExpectation = jqueryMock.expects("dialog");
dialogExpectation.once();

//call my function, in which create a jquery dialog.

equals(dialogExpectation.verify(), true, "Dialog is displayed");
jqueryMock.restore();   

However, this shows me an error: Died in test # 1: Trying to wrap the undefined properties dialog as a function - {"message": "Attempting to wrap the undefined properties dialog as a function", "name": "TypeError"}

The jquery code is very simple:

displayMessage: function (message, title, hashId) { 

//some logic to build the message, title and hashId.  

 $(messageDiv).dialog({
            height: 240,
            width: 375,
            modal: true,
            title: title,
            resizable: false,
            buttons: [{
                text: localizedErrorMessages['OkText'],
                click: function () {
                    $(this).dialog("close");
                }
            }]             
        }); // end of dialog            
    } // end of displayMessage

Does anyone know how to trick the jquery dialog and write unit test in this script?

+5
source share
2 answers

You need to make fun of jQuery.fn as follows:

var jQueryMock = sinon.mock(jQuery.fn);
+3
source

I created jsFiddle to demonstrate a working answer.

function displayMessage(message, title, hashId) { 

     $("#message").dialog(); 
} 

test("dialog was called", function() {

    var jQueryMock = sinon.mock($.fn); // jQuery.fn and $.fn are interchangeable
    var dialogExpectation = jQueryMock.expects("dialog");
    dialogExpectation.once();

    //call my function, in which create a jquery dialog.
    displayMessage("new message", "title", 1);

    equal(dialogExpectation.verify(), true, "Dialog was not displayed");
    jQueryMock.restore();   
});

// This demonstrates a failing test - since the method actuall calls "dialog".
// It also demonstrates a more compact approach to creating the mock
test("toggle was called", function() {

    var mock = sinon.mock(jQuery.fn).expects("toggle").once();
    displayMessage("new message", "title", 1);

    equal(mock.verify(), true, "Toggle was never called");
});
0
source

All Articles