Reputation: 1834
I want to use Jasmine for two things, test a function that does a real ajax call, and acquire the callback data from the ajax call for use in additional jasmine tests.
This is what I have so far:
Javascript function:
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;
}
});
}
The test:
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];
});
If I console log the foo variable after 5 seconds I can see that the ajax request was made and the data is available in the foo variable
Upvotes: 0
Views: 397
Reputation: 1834
After a few days looking into this, my big take away is that Jasmine is a great tool, but the documentation is terrible. I found it very difficult to simply understand what a spy is and when a it should be used.
My solution was to not use a spy at all.
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();
}
And in the getAttributeInfo function I added return
just before $.ajax
UPDATE
...
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();
}
});
Upvotes: 1