我想使用 Jasmine 做两件事,测试执行真正 ajax 调用的函数,并从 ajax 调用获取回调数据以用于其他 jasmine 测试。
这是我到目前为止所拥有的:
Javascript函数:
function getAttributeInfo(selectedLayer){
// Get layer attributes
$.ajax({
type: 'get',
url: '/geoserver/oqplatform/ows?service=WFS&version=1.0.0&request=GetFeature&typeName='+ selectedLayer +'&outputFormat=json',
success: function(data) {
// pass the data into a global variable
foo = data;
// EDIT
return data;
}
});
}
测试:
it("an ajax test", function() {
var ajaxFunction = getAttributeInfo(SVIRLayerNames[0]);
// creating spied callback
var callback = jasmine.createSpy('callback');
spyOn($, 'ajax').and.callFake(function (req) {
var d = $.Deferred();
return d.promise();
});
// EDIT
//ajaxFunction.fetch(callback);
ajaxFunction(callback);
// everything after this does not seem to execute
var fakeData = callback.calls.mostRecent().args[0];
});
如果我在 5 秒后通过控制台记录 foo 变量,我可以看到发出了 ajax 请求并且数据在 foo 变量中可用
最佳答案
经过几天的研究,我最大的收获是 Jasmine 是一个很棒的工具,但文档很糟糕。我发现很难简单地理解 spy 是什么以及何时应该使用它。
我的解决方案是根本不使用 spy 。
beforeAll(function(done) {
var mySyncFunction = function () {
var layerName = 'foobar';
var layerRequest = getAttributeInfo(layerName);
layerRequest.success(function(layerResponse) {
// Pass data from the response into a global variable to be tests
// I can also check for things like the API version number.
});
layerRequest.done(function() {
// Alert Jasmine that the AJAX call is done
done();
});
};
mySyncFunction();
}
在 getAttributeInfo 函数中,我在 $.ajax
之前添加了 return
更新
...
beforeAll(function(done) {
$.ajax({
url: '/my/data',
data: {},
success: function (response) {
foo = response
done();
},
dataType: 'html'
});
});
////////////////
// Some tests //
////////////////
it("meets some requirement", function() {
for (var i = 0; i < foo.length; i++) {
var name = foo[i].fields.name;
expect(name).toBeDefined();
}
});
关于javascript - 使用 jasmine 进行真正的 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32229267/