Created
January 23, 2014 19:34
-
-
Save davidjbeveridge/8585283 to your computer and use it in GitHub Desktop.
utility for spying on jQuery.ajax request by url, type, data.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ajaxSpy = (function($){ | |
var oldAjax = $.ajax; | |
var requests = []; | |
var watchers = []; | |
function newAjax(opts){ | |
// execute real $.ajax and save the promise | |
var promise = oldAjax.apply(this, arguments); | |
requests.push({ | |
opts: opts, | |
promise: promise | |
}); | |
promise | |
.then(responseSuccess(promise)) | |
.fail(responseFailure(promise)); | |
return promise; | |
} | |
function addWatcher(match, success, failure) { | |
watchers.push([match, success, failure]); | |
} | |
function responseSuccess(promise) { | |
var request = _.find(requests, function(r) { | |
return r.promise === promise; | |
}); | |
return function(data, status, xhr){ | |
fireSuccessWatcher(request, data, status, xhr); | |
}; | |
} | |
function fireSuccessWatcher(request, data, status, xhr) { | |
var applicableWatchers = _.filter(watchers, watcherMatches(request)); | |
_.each(applicableWatchers, function(watcher) { | |
var success = watcher[1]; | |
if(typeof success === 'function') { | |
success(data, status, xhr); | |
} | |
}); | |
} | |
function responseFailure(promise) { | |
var request = _.find(requests, function(r) { | |
return r.promise === promise; | |
}); | |
return function(xhr, status, err){ | |
fireFailureWatcher(request, xhr, status, err); | |
}; | |
} | |
function fireFailureWatcher(request, xhr, status, err) { | |
var applicableWatchers = _.filter(watchers, watcherMatches(request)); | |
_.each(applicableWatchers, function(watcher) { | |
var fail = watcher[2]; | |
if(typeof fail === 'function') { | |
fail(xhr, status, err); | |
} | |
}); | |
} | |
function watcherMatches(request) { | |
return function(watcher){ | |
return _.isEqual(watcher, request.opts); | |
}; | |
} | |
// public interface | |
return { | |
start: function() { | |
$.ajax = newAjax; | |
}, | |
end: function() { | |
$.ajax = oldAjax; | |
}, | |
watch: addWatcher | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The matching wasn't quite right. Here's a slightly tweaked version:
Below are the ruby helpers I added for simple capybara testing- it doesn't actually care about success or failure, it just uses a flag to get notified when it's safe to refresh the page.