Giter VIP home page Giter VIP logo

jquery-mockjax's People

Contributors

addepar-andy avatar bdusell avatar danpaz avatar dcneiner avatar elijahmanor avatar gregid avatar ifandelse avatar jakerella avatar jcreamer898 avatar jdsharp avatar johnkpaul avatar jonspalmer avatar jzaefferer avatar kkirsche avatar koorgoo avatar kumar303 avatar manuelzs avatar mattmcla avatar michaelbrooks avatar mlynch avatar nicholascloud avatar prantlf avatar reinrl avatar rniemeyer avatar shellscape avatar stas-vilchik avatar suchipi avatar udnisap avatar weswedding avatar wfortin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-mockjax's Issues

Intercept ALL XMLHttpRequests

Can Mockjax be modified to intercept ALL XMLHttpRequests, not just ones that attempt to use jQuery to do so?

Thanks!

Can the type be 'PUT'?

I found that it can not mock a request with 'PUT' method.
Could this type be supported?

abort() is not 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

Support expectations and verification

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.

Handle multiple * in url

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;
}

Bug in IE9

It seems that some of test is failed or you don't test mockjax under IE9. I've just run mockjax under IE9 with Jasmine and I've got the error "SCRIPT438: Object doesn't support property or method 'apply'"

mockjax-error

isTimeout with jQuery Deferred callbacks doesn't work

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.

bower install jquery-mockjax throws error

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.

it doesn't skip the path doesn't exist

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?

More verbose console information for mockjax requests

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.

Data empty on a GET route after calling a POST route

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:

  • If I click the "Get" button, it works:
    [server] GET: Response: { "property":"not posted..!" }
    [client] GET: Success! { "property":"not posted..." }
  • Now, if I click the "Post" button, it also works:
    [server] POST: Response: { "property":"Posted!" }
    [client] POST: Success! { "property":"Posted!" }
  • But now, when I click the "Get" button, it crashes:
    [server] GET: Response: { "property":"Posted!" }
    [client] GET: Success! null
    Error: Uncaught [client] GET: Data is null
  • Even weirder: If I click again "Post", it still works:
    [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

m is null Line 84

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 ) {

Move documentation to GitHub

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.

mockjax GET with jQuery 2.0 JSON result doesn't work

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.

Pass settings parameters to response callback

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.

Mockjax only capture the first request (AMD)

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 the url regular expression is getting replaced with .+ instead of .*

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

Mockjax doesn't work with $.ajax(url, settings)

jQuery 1.5.2 (and possibly earlier versions) allows you to call $.ajax in two ways: $.ajax(url, settings) or $.ajax(settingsIncludingURL). When mockjax overrides the ajax method here, it assumes it's just getting a single settings hash, which breaks requests made in the other format.

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!

Origin null is not allowed by Access-Control-Allow-Origin.

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 ?

Overhaul codebase

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...

Support global async setting for tests that don't work well with setTimeout

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

When we have two or more mocks on same run

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
}

proxy approach does not seem to work for xml files

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.

Better fuzzy matching

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.

More control over handlers

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.

jsre, rquery, jsc not defined

I've been trying to mock out jsonp requests. It seems that the jsre, rquery, and jsc variables are missing/out-of-scope.

Mocking remote JSONP fails

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();
});

Console check needs to be modified

The check for the console needs to be modified to:

if ( window.console && window.console.log ) {
    window.console.log('MOCK GET: ' + s.url);
}

Support for async/deferred responses

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

Logging is hardcoded to be on, and log option is ignored

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.

Keep the mocking data object intact

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.

Failed unit test in Chrome

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.

Mockjax is cloning the whole settings.context

Hi

Mockjax is cloning the whole settings.context when it is using $.extend. There are two issues here -

  1. It clones the whole object structure (Maybe a whole DOM tree).

  2. 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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.