我写了下面的代码,尝试测试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:尝试将未定义的属性对话框包装为函数 - {“message”:“尝试将未定义的属性对话框包装为函数”,“name”:“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 :(得分:3)
你需要像这样模仿jQuery.fn:
var jQueryMock = sinon.mock(jQuery.fn);
答案 1 :(得分: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");
});