gpt4 book ai didi

javascript - 如何使用 jasmine-ajax 验证是否调用了发送方法?

转载 作者:行者123 更新时间:2023-11-30 19:38:56 26 4
gpt4 key购买 nike

如果我从不调用 send 方法,jasmine-ajax 是否应该使用 4 的 readyState 调用 onreadystatechange

如果以上不是预期的行为,我该如何使用 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 answer说明您可以在 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();
});
});

关于javascript - 如何使用 jasmine-ajax 验证是否调用了发送方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55620423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com