diff --git a/lib/mock-ajax.js b/lib/mock-ajax.js index 2a635f2..05b0408 100644 --- a/lib/mock-ajax.js +++ b/lib/mock-ajax.js @@ -55,8 +55,8 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. this.requests.reset(); }; - this.stubRequest = function(url) { - var stub = new RequestStub(url); + this.stubRequest = function(url, data) { + var stub = new RequestStub(url, data); stubTracker.addStub(stub); return stub; }; @@ -85,10 +85,10 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. stubs = []; }; - this.findStub = function(url) { + this.findStub = function(url, data) { for (var i = stubs.length - 1; i >= 0; i--) { var stub = stubs[i]; - if (stub.url === url) { + if (stub.url === url && (!stub.data || stub.data === data)) { return stub; } } @@ -138,7 +138,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. this.readyState = 2; this.onreadystatechange(); - var stub = stubTracker.findStub(this.url); + var stub = stubTracker.findStub(this.url, data); if (stub) { this.response(stub); } @@ -246,8 +246,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. }; } - function RequestStub(url) { + function RequestStub(url, data) { this.url = url; + this.data = data; this.andReturn = function(options) { this.status = options.status || 200; diff --git a/spec/javascripts/webmock-style-spec.js b/spec/javascripts/webmock-style-spec.js index fb8dadf..a7b3d74 100644 --- a/spec/javascripts/webmock-style-spec.js +++ b/spec/javascripts/webmock-style-spec.js @@ -63,4 +63,44 @@ describe("Webmock style mocking", function() { expect(response.responseText).toEqual('no'); }); }); + + describe("stubbing with form data", function() { + beforeEach(function() { + mockAjax.stubRequest("http://example.com/someApi", 'foo=bar').andReturn({responseText: "form", status: 201}); + }); + + var postRequest = function(data) { + var xhr = new fakeGlobal.XMLHttpRequest(); + xhr.onreadystatechange = function(arguments) { + if (this.readyState == this.DONE) { + response = this; + successSpy(); + } + }; + + xhr.open("POST", "http://example.com/someApi"); + xhr.send(data); + }; + + it("uses the form data stub when the data matches", function() { + postRequest('foo=bar'); + + expect(response.status).toEqual(201); + expect(response.responseText).toEqual('form'); + }); + + it("falls back to the stub without data specified if the data doesn't match", function() { + postRequest('foo=baz'); + + expect(response.status).toEqual(200); + expect(response.responseText).toEqual('hi!'); + }); + + it("uses the stub without data specified if no data is passed", function() { + postRequest(); + + expect(response.status).toEqual(200); + expect(response.responseText).toEqual('hi!'); + }); + }); });