From fb5a98e63e5e19f347ecad55f54e33853cdea8bc Mon Sep 17 00:00:00 2001 From: Jen Hamon Date: Mon, 30 Mar 2015 21:15:34 -0700 Subject: [PATCH] Throw error on duplicate calls to MockAjax#install. Fixes #96 --- lib/mock-ajax.js | 4 ++++ spec/integration/mock-ajax-spec.js | 27 +++++++++++++++++++++++++++ src/mockAjax.js | 4 ++++ 3 files changed, 35 insertions(+) diff --git a/lib/mock-ajax.js b/lib/mock-ajax.js index 5015278..ccd7395 100644 --- a/lib/mock-ajax.js +++ b/lib/mock-ajax.js @@ -396,6 +396,10 @@ getJasmineRequireObj().MockAjax = function($ajax) { mockAjaxFunction = $ajax.fakeRequest(global, requestTracker, stubTracker, paramParser); this.install = function() { + if (global.XMLHttpRequest === mockAjaxFunction) { + throw "MockAjax is already installed."; + } + global.XMLHttpRequest = mockAjaxFunction; }; diff --git a/spec/integration/mock-ajax-spec.js b/spec/integration/mock-ajax-spec.js index 1f4ecb6..ad743da 100644 --- a/spec/integration/mock-ajax-spec.js +++ b/spec/integration/mock-ajax-spec.js @@ -1,4 +1,31 @@ describe("mockAjax", function() { + it("throws an error if installed multiple times", function() { + var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), + fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, + mockAjax = new window.MockAjax(fakeGlobal); + + function doubleInstall() { + mockAjax.install(); + mockAjax.install(); + } + + expect(doubleInstall).toThrow(); + }); + + it("does not throw an error if uninstalled between installs", function() { + var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), + fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, + mockAjax = new window.MockAjax(fakeGlobal); + + function sequentialInstalls() { + mockAjax.install(); + mockAjax.uninstall(); + mockAjax.install(); + } + + expect(sequentialInstalls).not.toThrow(); + }); + it("does not replace XMLHttpRequest until it is installed", function() { var fakeXmlHttpRequest = jasmine.createSpy('fakeXmlHttpRequest'), fakeGlobal = { XMLHttpRequest: fakeXmlHttpRequest }, diff --git a/src/mockAjax.js b/src/mockAjax.js index 77a7937..abb1879 100644 --- a/src/mockAjax.js +++ b/src/mockAjax.js @@ -7,6 +7,10 @@ getJasmineRequireObj().MockAjax = function($ajax) { mockAjaxFunction = $ajax.fakeRequest(global, requestTracker, stubTracker, paramParser); this.install = function() { + if (global.XMLHttpRequest === mockAjaxFunction) { + throw "MockAjax is already installed."; + } + global.XMLHttpRequest = mockAjaxFunction; };