I have a function which calls out for JSON and then in the success function makes some changes to the DOM. I'm trying to use the mock-ajax library in my Jasmine tests to avoid having to expose the various private functions for mocking.
Even though when stepping through the test the request.response
is set the onSuccess method is never called.
My tests:
describe('the table loader', function () {
var request;
beforeEach(function() {
//html with a loader div, an output div and a transit and dwell template
setFixtures('<div class="loader"></div><div class="row"><div id="output" class="col-xs-12"></div></div><script id="thingTemplate" type="text/x-handlebars">{{snip}}</script>');
expect($('.loader')).toBeVisible();
//start ajax call
window.dashboards.thing.display({
loaderId: '.loader',
templateId: '#thingTemplate',
templateOutletId: '#output',
dataUrl: '/my/fake/url'
});
//catch the ajax request
request = mostRecentAjaxRequest();
});
describe('on success', function () {
beforeEach(function() {
//populate the response
request.response({
status: 200,
responseText: "{rowItem: [{},{},{}]}"
});
});
it('should hide the loader', function () {
//thing should now receive that JSON and act accordingly
expect($('.loader')).not.toBeVisible();
});
});
});
and my code:
(function (dashboards, $) {
dashboards.thing = dashboards.thing || {};
var compileTable = function(templateId, jsonContext) {
var source = $(templateId).html();
var template = Handlebars.compile(source);
var context = jsonContext;
return template(context);
};
var getDashboardData = function(options) {
$.getJSON(
options.dataUrl,
function (data) {
processDashboardData(options, data);
}
).fail(function (jqxhr, textStatus, error) {
console.log('error downloading dashboard data');
console.log(textStatus + ': ' + error);
}).always(function() {
console.log('complete');
});
};
var processDashboardData = function (options, data) {
$(options.loaderId).hide();
$(options.templateOutletId).html(compileTable(options.templateId, data));
};
dashboards.thing.display = function (options) {
getDashboardData(options);
};
}(
window.dashboards = window.dashboards || {},
jQuery
));
None of the deferred functions (success, error, and always) are being called.
Edit
based on @gregg's answer below (and he's right I didn't include the UseMock call in the example code) this feels like a versions issue. As even with that call included this still isn't working for me.
I've added a runnable example on github