javascript - 如何使用 jasmine-ajax 来验证 send 方法是否被调用?
问题描述
如果我从不调用该方法,应该使用 4jasmine-ajax
调用吗 onreadystatechange
?readyState
send
如果以上不是预期的行为,我如何使用jasmine-ajax
来验证该send
方法是否被调用?
这是正在测试的代码:
Loader = (function() {
var loadNames = function(url, success_callback, error_callback) {
var ajax = new XMLHttpRequest();
ajax.open("GET", url);
ajax.onreadystatechange = function () {
console.log("Ready state is " + ajax.readyState);
if (ajax.readyState === 4 && ajax.status === 200) {
success_callback(JSON.parse(ajax.responseText));
} else if (ajax.readyState === 4 && ajax.status !== 200) {
error_callback("There was a problem. Status returned was " + ajax.status);
}
};
ajax.onerror = function () {
error_callback("Unknown error");
};
// Shouldn't removing the call to send prevent
// onredystatechange from being called with readyState 4?
// ajax.send();
};
return {
loadNames: loadNames
};
})();
这是测试:
describe("Loader", function () {
var successFunction, failFunction;
beforeEach(function () {
jasmine.Ajax.install();
successFunction = jasmine.createSpy("successFunction");
failFunction = jasmine.createSpy("failFunction");
});
afterEach(function () {
jasmine.Ajax.uninstall();
});
describe("#loadNames", function () {
it("Makes a success callback with the data when successful", function () {
Loader.loadNames("someURL", successFunction, failFunction);
jasmine.Ajax.requests.mostRecent().respondWith({
"status": 200,
"contentType": 'application/json',
"responseText": '[1, 2, 4, 3, 5]'
});
// Shouldn't this fail since I never called send?
expect(successFunction).toHaveBeenCalledWith([1, 2, 4, 3, 5]);
});
});
});
我很惊讶地看到它successFunction
被调用了,因为被测代码从不调用ajax.send()
. 如果这是库的预期行为,那么我如何spyOn
使用底层ajax
对象以便验证被测代码是否调用send
?
解决方案
是的,您没有调用,但是由于这段代码ajax.send()
,您正在触发事件:ajax.onreadystatechange
jasmine.Ajax.requests.mostRecent().respondWith({
"status": 200,
"contentType": 'application/json',
"responseText": '[1, 2, 4, 3, 5]'
});
这会更改就绪状态并将就绪状态设置为完成。这实际上与文档中的说明完全相同:https ://jasmine.github.io/2.6/ajax.html
至于如何检查 xhr.send 是否真的被调用,这个SO 答案解释了你可以在你的 beforeEach 中监视它:
spyOn(XMLHttpRequest.prototype, 'send');
在加载程序中取消注释 xhr.send() 部分后,您可以检查方法调用,如下所示:
describe("#loadNames", function () {
it("Makes a success callback with the data when successful", function () {
Loader.loadNames("someURL", successFunction, failFunction);
jasmine.Ajax.requests.mostRecent().respondWith({
"status": 200,
"contentType": 'application/json',
"responseText": '[1, 2, 4, 3, 5]'
});
expect(XMLHttpRequest.prototype.open).toHaveBeenCalled();
});
});
推荐阅读
- flutter - 如何在 Flutter 中为 Divider 添加渐变颜色
- angular - 如何使用角度激活的路由器从 url 访问查询参数?
- javascript - while 循环的问题 - 生成随机卡片
- docker - 高山 docker 容器无法识别 tesseract-ocr
- arrays - 是否有一种算法可以比对元素进行排序更快地将具有相同键的元素分组?
- linux - 在 .patch 文件中手动创建一个新文件,但“索引”行是干什么用的?
- java - 跟踪文件更改的最有效方法是什么?
- python - TypeError:列表索引必须是整数或切片,而不是 str?刽子手
- node.js - 如何从 node.js 脚本登录 azure 广告(无浏览器流程)
- python - 如何为这个数组序列创建一个“for”循环?