Rob*_*bin 5 javascript jasmine jasmine-ajax
我有一个网络应用程序需要检查用户是否连接到互联网.在实现中,如果对已知端点的ajax ping成功,则check()函数将为true,如果ajax调用以任何方式失败,则为false.
在Jasmine中,我可以request.respondWith({status:400, etc})用来模拟失败,但我无法弄清楚如何模拟根本没有发出的更基本的错误.
实际上,当甚至无法进行调用时,浏览器似乎"返回"状态代码0和readyState 4.
我应该如何在Jasmine测试中解决这个问题?
这是个有趣的问题。虽然我可能无法为您提供直接的答案,但我想尝试一下。
下面的代码说明了三个这样的示例(而不是测试)。查看实际效果
var errorFunction = function(jqXHR, status, error) {
console.log('This is errorFunction')
}
var makeAPICall = function(url) {
return $.ajax({
url: url,
fail: errorFunction,
error: errorFunction
});
}
var testFunction = function() {
makeAPICall().done(function(data, status, xh) {
if (xh.status === 0 && xh.readyState == 4) {
errorFunction();
return;
}
console.log("this is successFunction");
}).fail(errorFunction);
}
var getData = function() {
var str = 'ABCDEFGHIJ'
var returnStr = '';
for (var i = 0; i < 3000; i++) {
returnStr += str;
}
return returnStr;
}
describe('test ajax errors', function() {
it('tests a failed call due to huge payload ', function() {
var xhrObj = $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts?userId=' + getData(),
async: false
});
console.log('Below is the xhr object that is breing returned via spy');
console.log(xhrObj);
spyOn(window, 'makeAPICall').and.returnValue(xhrObj);
spyOn(window, 'errorFunction').and.callThrough();
testFunction();
expect(window.errorFunction).toHaveBeenCalled();
});
it('tests a failed call due to some n/w error scenario (readyState->4, status->0)', function() {
var xhrObj = $.ajax({
url: '',
async: false
});
xhrObj.status = 0;
xhrObj.statusText = 'error';
console.log('Below is the xhr object that is breing returned via spy');
console.log(xhrObj);
spyOn(window, 'makeAPICall').and.returnValue(xhrObj);
spyOn(window, 'errorFunction').and.callThrough();
testFunction();
expect(window.errorFunction).toHaveBeenCalled();
});
it('tests a failed call (bad url pattern)', function() {
var xhrObj = $.ajax({
url: 'https://jsonplaceholder.typicode.com/postssss/1',
async: false
});
console.log('Below is the xhr object that is breing returned via spy');
console.log(xhrObj);
spyOn(window, 'makeAPICall').and.returnValue(xhrObj);
spyOn(window, 'errorFunction').and.callThrough();
testFunction();
expect(window.errorFunction).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
笔记:
errorFunction是从 did ifreadySatate === 4 && status === 0以及所有其他
error/fail回调中调用的 errorFunctionmakeAPICall返回jqXHR使用done&fail回调的。getData是一个生成巨大有效负载的实用函数:在 test1 中使用url调用以模拟readyState->4 & status->0$.ajax({some params & async false}) async: false帮助我生成一个虚拟对象并通过spy| 归档时间: |
|
| 查看次数: |
431 次 |
| 最近记录: |