jakerella / jquery-mockjax

The jQuery Mockjax Plugin provides a simple and extremely flexible interface for mocking or simulating ajax requests and responses
Other
2.11k stars 375 forks source link

beforeSend not called when mockjax setup with a function #351

Closed rally25rs closed 4 years ago

rally25rs commented 4 years ago

It seems that if you setup a project like:

function beforeSend(jqXHR) {
  console.log("BEFORE SEND", jqXHR);
}

console.log("SETUP");
$.ajaxSetup({
  beforeSend: beforeSend
});

$.mockjax({
  url: "/test",
  response: function(request) {
    console.log("MOCKJAX");
  }
});

$.ajax({
  url: "/test",
  type: "GET"
});

then the beforeSend hook is called correctly. Console output will be

SETUP
BEFORE SEND
MOCKJAX

However you can't get the request headers this way. According to this section of the docs: https://github.com/jakerella/jquery-mockjax#accessing-request-headers to get to the headers you have to pass a function to mockjax, and the docs even state that you could check headers that would be added by beforeSend, however beforeSend is not called when configured this way.

function beforeSend(jqXHR) {
  console.log("BEFORE SEND", jqXHR);
}

console.log("SETUP");
$.ajaxSetup({
  beforeSend: beforeSend
});

$.mockjax(function(request) {
  console.log("MOCKJAX", request);
});

$.ajax({
  url: "/test",
  type: "GET"
});

console output is just

SETUP
MOCKJAX

CORRECTION:

It looks like beforeSend is called, but out of order. If the mockjax function returns successfully, then beforeSend appears to be called after the mockjax handler...

SETUP
MOCKJAX
BEFORE SEND

Example code: https://codesandbox.io/s/blissful-glade-l13m8

This seems to contradict the documentation.

rally25rs commented 4 years ago

Oh, I guess I misread the doc example... its supposed to return a function that becomes the handler to be called later... not enough coffee 😑

jakerella commented 4 years ago

No worries! Hope you got it sorted.