2012-04-19 6 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に死亡:関数として未定義のプロパティ]ダイアログボックスをラップしようとしました - {「メッセージ」:「関数として未定義のプロパティ]ダイアログボックスをラップしようとしました」、「名前」 :「例外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のダイアログを模擬し、このシナリオでユニットテストを書く方法を知っていますか?

+0

これはどのようなテストフレームワークですか? – streetlight

答えて

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"); 
}); 
関連する問題