From 7c4dee011e85b59d2e5208d072020d63b27941bb Mon Sep 17 00:00:00 2001 From: jakerella Date: Sat, 23 Jan 2016 16:13:54 -0500 Subject: [PATCH] Fix for #136 (cross domain requests) 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. --- src/jquery.mockjax.js | 6 +++++- test/test.js | 46 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/jquery.mockjax.js b/src/jquery.mockjax.js index 98fe6bbd..5e2fd5a1 100644 --- a/src/jquery.mockjax.js +++ b/src/jquery.mockjax.js @@ -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; diff --git a/test/test.js b/test/test.js index 488fc758..8dadd683 100644 --- a/test/test.js +++ b/test/test.js @@ -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 @@ -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');