【问题标题】:How can I unit test jquery dialog get displayed?如何显示单元测试 jquery 对话框?
【发布时间】:2012-05-01 13:38:18
【问题描述】:

我写了下面的代码,尝试测试一个 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 对话框并编写单元测试吗?

【问题讨论】:

  • 这是用于什么测试框架的?

标签: jquery unit-testing jquery-ui-dialog qunit sinon


【解决方案1】:

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

var jQueryMock = sinon.mock(jQuery.fn);

【讨论】:

    【解决方案2】:

    我创建了一个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");
    });
    

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 2016-02-12
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多