5

我写了下面的代码,尝试测试一个 jquery 对话框是否得到原谅和显示。

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

但是,它向我显示了错误:在测试 #1 中死亡:尝试将未定义的属性对话框包装为函数 - {“消息”:“尝试将未定义的属性对话框包装为函数”,“名称”:“TypeError”}

jquery 代码很简单:

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

任何人都知道如何在这种情况下模拟 jquery 对话框并编写单元测试?

4

2 回答 2

3

你需要像这样模拟 jQuery.fn:

var jQueryMock = sinon.mock(jQuery.fn);
于 2012-04-20T10:42:05.513 回答
0

我创建了一个jsFiddle来演示有效的答案。

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");
});
于 2014-04-18T03:07:15.033 回答