Reputation: 229
I've found out how to test promises in jasmine, but I couldn't find a way to test the beforeSend method.
var xhr = $.ajax({
url: 'http://example.com',
type: 'POST',
data: '...',
beforeSend: function() {
methodToBeTested();
}
});
I do need the code to run before the request is sent so using the always promise is not an option.
Upvotes: 0
Views: 604
Reputation: 1
Or you can access the arguments passed on to the spied ajax call later:
$.ajax.calls.argsFor(0)[0].beforeSend();
//instead of argsFor(), you can use first(), mostRecent(), all() ...
This is in case you do not want to have beforeSend() called each time.
Upvotes: 0
Reputation: 1195
Here's my slightly hackie feeling solution but it worked for me.
it('test beforeSend', function() {
spyOn(window, 'methodToBeTested')
spyOn($, "ajax").andCallFake(function(options) {
options.beforeSend();
expect(methodToBeTested).toHaveBeenCalled();
//this is needed if you have promise based callbacks e.g. .done(){} or .fail(){}
return new $.Deferred();
});
//call our mocked AJAX
request()
});
You could also try the Jasmine AJAX plugin https://github.com/pivotal/jasmine-ajax.
Upvotes: 2
Reputation: 82231
You can use this:
if ( $.isFunction($.fn.beforeSend) ) {
//function exists
}
Upvotes: 0