2012-04-19 81 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"); 
}); 
相關問題