It looks like you need to call $.mockjaxClear(); before you create another mock handler.
Mockjax works by modifying the $ .ajax method.
At the bottom of its source code, we see that the $ .mockjax method you use, which is one of its public methods, simply adds more handlers to the mockHandlers array.
$.mockjax = function(settings) { var i = mockHandlers.length; mockHandlers[i] = settings; return i; };
In the source code to replace $ .ajax you can see:
// Iterate over our mock handlers (in registration order) until we find // one that is willing to intercept the request for(var k = 0; k < mockHandlers.length; k++) {
Your problem is that the $ .ajax method satisfies the first handler (and not the last) of the mock array in the array for the URL /echo/json/ .
Here is my fork of your violin by simply adding the line $.mockjaxClear() .
Edit:
More flexible solution:
- Outside of any test function, decare is a variable that will have a request handler identifier for subsequent changes.
- Before the module, where you need to override a specific handler, declare a variable (there is no need for an initial value) to store a backup copy of the handler that you want to change.
- Then, in the module settings function, use $ .extend to copy the settings from $ .mockjax.handler (
<your handlerID variable> ) to this backup. In the teardown module, use $ .mockjaxClear ( <your handlerID variable> ) to remove the module, and then set <your handlerID variable> to something else. - Now you can redefine your handlers in the
setup module and in separate test functions.
But do not take my word for it. Check the script .
It is much more flexible like this. You can modify this handler and leave all other handlers that might be intact.
It seems to be potentially error prone, so I would advise being careful.
source share