0

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.

Community
  • 1
  • 1
John Nikolakis
  • 229
  • 4
  • 7

3 Answers3

2

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.

Max
  • 1,175
  • 3
  • 12
  • 22
0

You can use this:

if ( $.isFunction($.fn.beforeSend) ) {
//function exists
}
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

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.