我正在尝试测试一个非常简单的 jQuery 插件,它只需调用 $.ajax 方法并将其内容放入元素中。对于测试,我使用 JsTestDriver 和 Sinon 进行模拟。
插件文件看起来:
(function($) {
$.fn.transfer = function() {
$.ajax({
url : 'friends',
type : 'GET',
contentType : 'application/json',
dataType : 'json',
success : function(html) {
console.log("-"+html+"-");
console.log($(this));
$(this).html(html);
console.log("+"+$(this).html()+"+")
}
});
};
})(jQuery);
理论上很简单的插件。
然后我写了一个单元测试模拟成功函数:
TestCase("Ajax ", {
'test response' : function () {
/*:DOC divElement = <div id="container" style="height: 100px;"></div>*/
sinon.stub(jQuery, "ajax").yieldsTo(
"success", 'alex');
$(this.divElement).transfer();
console.log("*"+$(this.divElement).text()+"*");
}
});
它似乎也正确。然后,如果您执行此测试,将通过控制台打印下一行:
[LOG] -alex-
[LOG] [object Object]
[LOG] +null+
[LOG] **
所以成功函数正确接收“alex”字符串。然后打印 $(this) 引用,使用 html() 函数设置消息,当我记录以前的设置值时,返回 null。最后一条日志消息在测试文件中,您可以在其中看到未设置 ajax 文本。
有人知道我做错了什么吗?因为我确信我错过了一些现在我看不到的东西。