Skip to content

Commit

Permalink
Fix for #136 (cross domain requests)
Browse files Browse the repository at this point in the history
As far as I can tell the hack originally suggested by @dcneiner is the best way to do this. The problem is that we still pass our mock XHR object to jQuery and it still sees the mismatched domains and forces an actual HTTP request using a script tag. Instead, we have to explicitly tell jQuery not to do so. We can safely set this all the time, because if we're mocking, we never want to send a cross-domain request.

Thanks to @LeopoldoFu and @r4j4h for keeping on this one.
  • Loading branch information
jakerella committed Jan 23, 2016
1 parent 9376b68 commit 7c4dee0
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/jquery.mockjax.js
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,11 @@
}
}


// We are mocking, so there will be no cross domain request, however, jQuery
// aggressively pursues this if the domains don't match, so we need to
// explicitly disallow it. (See #136)
origSettings.crossDomain = false;

// Removed to fix #54 - keep the mocking data object intact
//mockHandler.data = requestSettings.data;

Expand Down
46 changes: 44 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@

qunit.begin(function() {

qunit.noErrorCallbackExpected = function noErrorCallbackExpected() {
qunit.assert.ok(false, 'Error callback executed');
qunit.noErrorCallbackExpected = function noErrorCallbackExpected(xhr) {
qunit.assert.ok(false, 'Error callback executed: ' + xhr.status, xhr.responseText);
};

// Speed up our tests
Expand Down Expand Up @@ -2443,6 +2443,48 @@
});
});

t('Bug #136: cross domain script requests - GET', function(assert) {
var done = assert.async();

$.mockjax({
type: 'GET',
url: 'http://jquery-mockjax-foobar.com/somefile.js',
responseText: '(window.mockjaxCrossDomain=true)'
});

$.ajax({
type: 'GET',
dataType: 'script',
url: 'http://jquery-mockjax-foobar.com/somefile.js',
error: qunit.noErrorCallbackExpected,
success: function(data) {
assert.strictEqual(window.mockjaxCrossDomain, true, 'mockjax call for script was mocked');
},
complete: done
});
});

t('Bug #136: cross domain script requests - POST', function(assert) {
var done = assert.async();

$.mockjax({
type: 'POST',
url: 'http://jquery-mockjax-foobar.com/somefile.js',
responseText: '(window.mockjaxCrossDomain=true)'
});

$.ajax({
type: 'POST',
dataType: 'script',
url: 'http://jquery-mockjax-foobar.com/somefile.js',
error: qunit.noErrorCallbackExpected,
success: function(data) {
assert.strictEqual(window.mockjaxCrossDomain, true, 'mockjax call for script was mocked');
},
complete: done
});
});


/* -------------------- */
qunit.module('namespace');
Expand Down

0 comments on commit 7c4dee0

Please sign in to comment.