2012-04-19 55 views
5

我写下面的代码,尝试测试一个jQuery对话是否可以原谅和显示。我怎样才能单元测试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:尝试换未定义的属性对话框的功能 - {“消息”:“试图包未定义的属性对话框中的功能”,“名” :“类型错误”}

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的对话框,在这种情况下写单元测试?

+0

这是什么测试框架? – streetlight 2013-02-21 13:27:19

回答

3

您需要模拟jQuery.fn这样的:

var jQueryMock = sinon.mock(jQuery.fn); 
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"); 
}); 
相关问题