jakerella / jquery-mockjax Goto Github PK
View Code? Open in Web Editor NEWThe jQuery Mockjax Plugin provides a simple and extremely flexible interface for mocking or simulating ajax requests and responses
License: Other
The jQuery Mockjax Plugin provides a simple and extremely flexible interface for mocking or simulating ajax requests and responses
License: Other
Pretty please???
Can Mockjax be modified to intercept ALL XMLHttpRequests, not just ones that attempt to use jQuery to do so?
Thanks!
I found that it can not mock a request with 'PUT' method.
Could this type be supported?
Once I call abort() in an asynchroneous way, the fail() callback is called.
But the setTimeout in MockJax will call the done. It should not
Today, mockjax is more of a stub than a mock. It would be a great improvement (at least in testing) if you could also set expectations on the mock within a test and then verify that the expectations were fulfilled. This allows testing of the behavior (calling the proper service, passing the proper values) rather than just testing the resulting state assuming that the stub is set up to return the proper data needed for the particular test.
I was trying to mock a url similar to
"/my_api/action_summary?token=&aggregated=daily&action=1" but only the first * gets replaced to ".+".
The fix is easy, just need to change the replace("_",".+") to replace(/_/g,".+") [line 107]
// Look for a simple wildcard '*' or a direct URL match
var star = handler.url.indexOf('*');
if (handler.url !== requestSettings.url && star === -1 ||
!new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace(/\*/g, '.+')).test(requestSettings.url))
{
return null;
}
Hi Folks,
I have been trying to use the mock ajax with jquery 1.9.1 version, the response is always returning as 'undefined' on the success callback but if I change the jquery earlier versions, say version less than 1.9 it works just fine. Is there any compatibility issues or I'm missing something. Please shed some light and check my sample code on the following link...
Hi there,
I am having a problem where when I have mockjax script loaded, I am unable to make ajax calls to "real" URL.
Please see this jsfiddle for an example: http://jsfiddle.net/dubgR/2/
What am I missing here?
Thanks for the help.
The ajax proxy call is currently using the HTTP verb defined in the mock m.type, it should always use a get.
Patch in jquery.mockjax.js:
type: m.type,
type: 'GET', // Always use get to load mock object files
Just create a new branch called gh-pages
based on master and push that. Can then use those pages to look at examples etc.
Make JD the author (no need for double listing), add contributors.
I had an error using isTimeout in mockjax with jQuery's Deferred callbacks (http://api.jquery.com/category/deferred-object/).
I'm using jQuery version 1.7.2, but there were errors with earlier versions as well. I created a test demonstrating the problem in this repo: https://github.com/michaelbrooks/jquery-mockjax
The error was on line 181 of jquery.mockjax.js, where it attempts to call requestSettings.error(), but no such function exists.
I have no idea how to fix this, but hopefully this is helpful. I see there have been earlier changes to make mockjax work with deferred callbacks (#37) but this problem seems to be particular to the case of using isTimeout.
Installing mackjax via bower fails;
$ bower install jquery-mockjax
bower cloning git://github.com/appendto/jquery-mockjax
bower cached git://github.com/appendto/jquery-mockjax
bower fetching jquery-mockjax
bower checking out jquery-mockjax#v1.5.1
bower copying /Users/aqb99/.bower/jquery-mockjax
/usr/local/lib/node_modules/bower/node_modules/semver/semver.js:117
return stars.trim().replace(starExpression, starReplace)
^
TypeError: Object 1.3.2,1.4.4,1.5.2,1.6.4,1.7 has no method 'trim'
at replaceStars (/usr/local/lib/node_modules/bower/node_modules/semver/semver.js:117:16)
at Object.validRange (/usr/local/lib/node_modules/bower/node_modules/semver/semver.js:187:11)
at new Package (/usr/local/lib/node_modules/bower/lib/core/package.js:68:23)
at Package.addDependencies (/usr/local/lib/node_modules/bower/lib/core/package.js:273:33)
at async.parallel.results (/usr/local/lib/node_modules/bower/node_modules/async/lib/async.js:454:21)
at _asyncMap (/usr/local/lib/node_modules/bower/node_modules/async/lib/async.js:185:13)
at async.forEach (/usr/local/lib/node_modules/bower/node_modules/async/lib/async.js:86:13)
at Array.forEach (native)
at _forEach (/usr/local/lib/node_modules/bower/node_modules/async/lib/async.js:26:24)
at async.forEach (/usr/local/lib/node_modules/bower/node_modules/async/lib/async.js:85:9)
Probably this is nothing to do with mockjax and is a bower bug, but other packages install fine.
isTimeout incorrectly calls the success handler for jquery 1.5 and up. I have tried to write a patch for this but could not figure out a way to fix it. I was able to add failing tests though: kumar303/jquery-mockjax@master...timeout These tests pass with jquery 1.4
When I include mockjax whenever request is made it submit the request to the current file not the actual path specified. Is it bug or there is some option that I can specified?
Hi,
I really enjoyed using mockjax in my latest project, but I found the console.log information for the requests a bit incomplete. MOCK POST: /mockUrl
doesn't tell me anything about the data posted, the delivered response, the server response code,...
When working with real AJAX requests, I always have the network panel open to spot the data that is sent "over the wire". This allows me to spot errors much faster than by manually setting breakpoints. It would be nice if mockjax offered a similar experience.
Hi,
I have a weird issue: I declared two routes, one on GET and another on POST, and the GET route works well until I call the POST route at least once. Then it always return null
data.
Here is the test case: http://jsfiddle.net/2V3DD/3/
Here is the thing:
[server] GET: Response: { "property":"not posted..!" }
[client] GET: Success! { "property":"not posted..." }
[server] POST: Response: { "property":"Posted!" }
[client] POST: Success! { "property":"Posted!" }
[server] GET: Response: { "property":"Posted!" }
[client] GET: Success! null
Error: Uncaught [client] GET: Data is null
[server] POST: Response: { "property":"Posted!" }
[client] POST: Success! { "property":"Posted!" }
I tried this use case and it is indeed broken with jQuery 1.8.2 and 1.7.2 at least, on Chromium and Firefox.
Alexis
I'm getting an error "m is null" on line 84. Looks like it happens when we don't get a match on the mockHandlers.
83 // Inspect the request type
84 if ( m.type && m.type != s.type ) {
They blog post isn't editable, the comments aren't reflected in it. There are tools for converting html to markdown, so the first step should be easy enough. Afterwards, people can contribute to docs directly via pull requests, making the repo the project home, instead of the blog post.
If you put some code like this:
$.mockjax({
type: "GET",
url: "*",
responseTime: 50,
response: function (settings) {
// Return the data to verify against.
var responseData = JSON.parse(JSON.stringify(someObject));
this.responseText = responseData; // i am sure this is not null
}
});
var def = someGetCall();
def.done(function (msg)) {
// msg is null
});
Only seems to happen with jQuery 2.0, GET and JSON scenario.
Hi, the response callback currently has no access to the data that is passed to the original ajax call.
Would it be an idea to replace the:
m.Response()
with:
m.Response(s)
in the send function? This would allow my response callback to create responses based on the data passed in.
Is there a way to trigger $.mockjax
when we have a specific url but only with specific data (params)
like so...
url: 'api/login',
data:{ // here i want to mach the data (as params or as the object)
type:"login"
},
responseText: {}
});
Hi,
I have a strange bug with Mockjax.
When I load it, it will capture the first mocked request made and respond accordingly. But on the second call, the request isn't captured and it goes on the server (returning 404).
I'm not sure where this come from, but I'm using it in an AMD environnement (with require.js), could this be an issue?
In our tests, some ajax urls have parameter in some cases and not in the other. So we want to give an expression that would with our gateway with or without parameters (Something like gatewayURL*).
But in the code, *
is getting replaced with .+
, and so it doesnt work when there are no parameters.
So, is it possible to change the .+
in the line below (line no:107) to a .*
!new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace('*', '.+')).test(requestSettings.url)) {
Regards
sharbel
Seems like binding error callbacks via the Promise interface doesn't seem to be compatible with mockjax, see also http://api.jquery.com/category/deferred-object/
See the following JSBin:
http://jsbin.com/cojacalome/1/edit?html,js,output
Notice that the first request succeeds, but the second one fails. The problem is that mockjax is expecting responseText to be a JSON object when dataType is set to 'jsonp'. However, it is possible to pass data of any type (i.e., string) into a JSONP callback.
jQuery 1.5.2 (and possibly earlier versions) allows you to call $.ajax in two ways:
Seems like it should be easy to fix; if I have time next week I can put together a pull request with tests.
Thanks for the library!
I get this error when I use :
$(function() {
$.mockjax({
url: '/app/',
proxy:'apps.json'
});
});
With : http://code.jquery.com/jquery-1.7.1rc1.min.js
and Chrome : 15.0.874.121 m
I grab the jquery-mockjax from the Github repo.
I tried to run chrome like that : chrome.exe --allow-file-access-from-files but always get the same error.
Inside the apps.json :
[
{title : "fwefwewef", description : "fweweffwefwe"},
{title : "fwefwejoijwef", description : "fwejijweffwefwe"}
]
Any idea ?
The current codebase has some serious problems: Lots of single-character variable names, heavy nesting, a single function that does most of the work instead of delegating to small methods.
Cleaning that up would probably break most or all open pull requests, so those should be merged first...
I have a few projects that don't work well with async mocking and I'd like to extend the conditional below to include a global setting that would allow me to avoid the setTimeout issue (and invoke process directly instead).
if ( requestSettings.async === false || mockHandler.async === false ) {
process();
} else {
this.responseTimer = setTimeout(process, mockHandler.responseTime || 50);
}
I could work up a PR but I wanted to see if this was something that would be pulled into core first
Imagine you have a mock to the request A and another to the request B. Both use wildcard.
In this case, the mockHandlers iteraction will fail in first run of request B because the variable m will get null value. The reason is the true value returned to the conditional m.url.substr(0, star) != s.url.substr(0, star) in the wildcard verification.
So, once the m is null, m.data and m.type will throws an exception.
Simple wrap lines in:
if (m) {
// lines 52-86
}
Currently the unit tests are broken because the JSONP callbacks are running twice. This is because the ajax call to the proxy url is run as dataType script. It is then executed once from the proxy call and again from the JSONP call.
It seems like xml files do not work for the proxy approach. Tested with both json and xml proxy files and the latter would'nt work. Could you please fix that? Used
<script src="../lib/jquery-1.10.2.min.js"></script>
<script src="../lib/jquery-migrate-1.2.1.min.js"></script>
<script src="../lib/jquery.mockjax.js"></script>
as libraries. responseXML worked like a charm. However, for more complex xml files, the proxy approach would be of great help.
The matcher for mocked urls is case sensitive. So if I mock "http://google.com*" it works as expected but if I mock "http://GoOgLe.com*" it does not.
Right now isMockDataEqual({},{}) === false; shouldn't it be true?
url: "offset=" should match only urls containing that 'offset=' substring, currently they match all URLs.
The problem basically is: Everything before an asterisk is ignored. Instead the asterisk should behave as an actual wildcard.
Currently examples/demo.html has some code that indicates some interactive examples, but there is nothing interactive there. Let's integrate that into the existing documentation, and drop the examples.
Using mockjax within an application to test certain error handlers. In case of a scrolling pager, I want the request for the second page to fail, then pass when clicking the retry button. For that it would be nice if I could either define a mock to run only once (remove itself), or get a callback to remove it with some other method. Currently not really feasible at all as only $.mockjaxClear exists to delete things.
I've been trying to mock out jsonp requests. It seems that the jsre, rquery, and jsc variables are missing/out-of-scope.
the modified test code fails with jQuery 1.5 once 'calling' the remote server:
https://gist.github.com/1024911
asyncTest('Response returns jsonp', function() {
$.mockjax({
url: 'http://example.com/jsonp*',
contentType: 'text/json',
proxy: 'test_jsonp.js'
});
window.abcdef123456 = function(json) {
ok( true, 'JSONP Callback executed');
deepEqual(json, { "data" : "JSONP is cool" });
};
$.ajax({
url: 'http://example.com/jsonp?callback=?',
jsonpCallback: 'abcdef123456',
dataType: 'jsonp',
error: noErrorCallbackExpected,
complete: function(xhr) {
equals(xhr.getResponseHeader('Content-Type'), 'text/json', 'Content type of text/json');
start();
}
});
$.mockjaxClear();
});
The check for the console needs to be modified to:
if ( window.console && window.console.log ) {
window.console.log('MOCK GET: ' + s.url);
}
Just what the title says.
Right now it's impossible to "resolve" the request at a later stage (don't read timeout).
Shouldn't you return a $.Deferred object instead?
Eg. I want to hook up into an ajax call and perform 3 other ajax calls "invisibly", concatenate the payloads and return one single payload
So peeking into the source shows me that there is a log option on line 527 that is completely ignored.
And there is a logMock(...) function that actually performs the console.log calls, but it is hard coded to always run on line 449.
But it has a comment on line 127 that says "// If logging is enabled, log the mock to the console".
Adding as an issue because of that comment, and the apparently vestigial log option. Would fix myself and make a pull request but I think the decision of moving logMock or setting log in default options to it, as well as the most ideal conditional check, would best be left to the repo maintainers.
Thanks for the awesome plugin! <3 Works great on our actual pages and in our Jasmine unit tests.
It seems the data object gets replaced in the mock object after calling matching an ajax call.
This seems the right thing to do when you are trying to match an exact object, but it doesn't work if you want to match subsequent ajax calls with a "wildcard".
This is the problem:
$.mockjax({
url: "/path/to/validate",
data: { remote: { test: function(data) {
return data !== "hello";
}
}
},
responseTime: 1000,
responseText: "false"
});
$.mockjax({
url: "/path/to/validate",
data: { remote: "hello" },
responseTime: 1000,
responseText: "true"
});
In this case, after calling ajax once, the first mockjax gets replaced and will not behave like it should afterwards...
Is there a way to achieve this problem?
Basically, any ajax calls that are not equal to "hello" should fail.
jQuery version: 1.5 (test/jquery-1.5.html).
Output follows (bold text means failed 'red' tests).
Mockjax
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.220 Safari/535.1
Core: Return XMLHttpRequest object from $.ajax (0, 1, 1)
Core: Intercept and proxy (sub-ajax request) (1, 0, 1)
Proxy request succeeded
Core: Dynamic response callback (0, 1, 1)
Core: Remove mockjax definition by id (0, 3, 3)
Core: Intercept log messages (0, 1, 1)
Core: Disable console logging (0, 1, 1)
URL Matching: Exact string (0, 1, 1)
URL Matching: Wildcard match (0, 1, 1)
URL Matching: RegEx match (0, 1, 1)
Data Types: Response returns text (0, 1, 1)
Data Types: Response returns html (0, 2, 2)
Data Types: Response returns json (0, 2, 2)
Data Types: Response returns jsonp (1, 1, 2)
Error callback executed
Content type of text/json
Expected:
"text/json"
Data Types: Response executes script (1, 1, 2)
Script executed
Expected:
1
Result:
0
Diff:
1 0
Source:
at Object.complete (file:///C:/appendto-jquery-mockjax-v1.4.0-5-g96a2a52/appendto-jquery-mockjax-96a2a52/test/test.js:304:4)
Content type of text/plain
Expected:
"text/plain"
Data Types: Response returns parsed XML (0, 3, 3)
Connection Simulation: Async test (0, 2, 2)
Connection Simulation: Sync test (0, 2, 2)
Connection Simulation: Response time simulation and latency (0, 3, 3)
Tests completed in 1109 milliseconds.
27 tests of 30 passed, 3 failed.
Hi
Mockjax is cloning the whole settings.context when it is using $.extend. There are two issues here -
It clones the whole object structure (Maybe a whole DOM tree).
We need to have some references to update after getting the response (like updating knoclout observables or UI based on the response). In this case we are not able to identify the object back as we are getting a new object structure.
JQuery also had similar issues that was fixed. See here http://bugs.jquery.com/ticket/9887.
We will need to stop making deep copies if it specified in jQuery.ajaxSettings.flatOptions. Below is the fn added by jquery to fix this.
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend(target, src) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for (key in src) {
if (src[key] !== undefined) {
(flatOptions[key] ? target : (deep || (deep = {})))[key] = src[key];
}
}
if (deep) {
jQuery.extend(true, target, deep);
}
return target;
}
We need to the same logic and call it at the two places where we do $.extend. Can also send in the changes. Or should I fork and commit?
I have a hosted QUnit test suite here that includes the use of jquery-mockjax to stub out an AJAX call. The test fails in Camino 2 on OS X. That may not come as a huge surprise, but the rest of the jQuery and jQuery UI stuff works very well in that browser, so it's disappointing to see that failure.
The test code is here:
https://github.com/jdee/dubsar/blob/master/public/javascripts/application-ui_test.js
Deprecate $.mockjaxClear for now.
jsonp mocking fails because of rquery being undefind, on line 141.
My workaround was to copy rquery from https://github.com/jquery/jquery/blob/1d202c6afc03c98dc656bf6bbde317fb0d050574/src/ajax.js#L13
I can create a pull request with the simple solution.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.