0

I just discovered the mockjax library, and it seems almost perfect for my testing needs. I say "almost", because there's one thing I can't seem to simulate: $.ajaxPrefilter handlers.

Normally in jQuery you can specify:

$.ajaxPrefilter(function() {
    doSomethingOnEveryAjaxCall();
});

and then whenever anyone uses $.ajax (or $.get, $.post, etc.) that doSomethingOnEveryAjaxCall function will be called.

However, if I do:

$.mockjax({url: '/test', responseText: 'test'});
$.ajax({url: '/test'});

the prefilter I setup (doSomethingOnEveryAjaxCall) doesn't get called.

Is there any way to modify that code so that the prefilter gets called even on mockjax requests/responses?

machineghost
  • 33,529
  • 30
  • 159
  • 234
  • request should be global, in source, the global option request is set to false https://github.com/appendto/jquery-mockjax/blob/master/jquery.mockjax.js#l194 But i don't see any way to change it using plugin option and still not sure this will fire this event. – A. Wolff Dec 23 '13 at 22:21
  • Thanks, that could be it, but I don't think so; even if I override `s.global = true` inside jQuery's code (for `ajax`) it still doesn't trigger the prefilters. – machineghost Dec 23 '13 at 22:46
  • mockjax will only mock the `$.ajax` function. If you want it to mock `$.ajaxPrefilter` you can create a mock for `$.ajaxPrefilter` at upper level so that it calls `$.ajax` – Paul D. Dec 23 '13 at 22:50
  • mockjax (as I understand it) invokes the real `$.ajax` behind the scenes (see line 474 of mockjax). The real `$.ajax` does invoke the prefilters (via `inspectPrefiltersOrTransports`, called around line 8026 or so), so even a mockjax-mocked request should still trigger the prefilters. However, the issue is that for some reason the mock variables that mockjax creates aren't quite like the real ones (likely because of the args I pass to mockjax), so I'm just trying to figure out how to make those mock variables more "real" for prefilter-triggering purposes. – machineghost Dec 23 '13 at 22:58

1 Answers1

1

It turns out mockjax was capable of triggering ajax prefilters ... I just forgot to supply all of the necessary headers to make my prefilter actually trigger. Once I tried using the proper headers, the prefilter triggered as expected!

machineghost
  • 33,529
  • 30
  • 159
  • 234