From ec019e7bc42d780ca300bfbe0e1c34aa6bf9525b Mon Sep 17 00:00:00 2001 From: Rozhnov Alexandr Date: Mon, 5 Oct 2015 14:43:31 +0300 Subject: [PATCH] Added method matching support. --- src/fetch-mock.js | 24 ++++++++++++++++++------ test/spec.js | 26 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/fetch-mock.js b/src/fetch-mock.js index e8faf1cb..ed8b6e9a 100644 --- a/src/fetch-mock.js +++ b/src/fetch-mock.js @@ -58,6 +58,18 @@ function mockResponse (url, config) { function compileRoute (route) { + var method = route.method; + var matchMethod; + if(method) { + method = method.toLowerCase(); + matchMethod = function(options) { + var m = options && options.method ? options.method.toLowerCase() : 'get'; + return m === method; + }; + } else { + matchMethod = function(){ return true; }; + } + debug('compiling route: ' + route.name); if (!route.name) { @@ -77,20 +89,20 @@ function compileRoute (route) { if (route.matcher.indexOf('^') === 0) { debug('constructing starts with string matcher for route: ' + route.name); expectedUrl = expectedUrl.substr(1); - route.matcher = function (url) { - return url.indexOf(expectedUrl) === 0; + route.matcher = function (url, options) { + return matchMethod(options) && url.indexOf(expectedUrl) === 0; }; } else { debug('constructing string matcher for route: ' + route.name); - route.matcher = function (url) { - return url === expectedUrl; + route.matcher = function (url, options) { + return matchMethod(options) && url === expectedUrl; }; } } else if (route.matcher instanceof RegExp) { debug('constructing regex matcher for route: ' + route.name); const urlRX = route.matcher; - route.matcher = function (url) { - return urlRX.test(url); + route.matcher = function (url, options) { + return matchMethod(options) && urlRX.test(url); }; } return route; diff --git a/test/spec.js b/test/spec.js index 92f97601..9c6d2240 100644 --- a/test/spec.js +++ b/test/spec.js @@ -252,6 +252,32 @@ module.exports = function (fetchMock, theGlobal) { }); }); + it('match method', function(done) { + fetchMock.mock({ + routes: [{ + name: 'route1', + method: 'get', + matcher: 'http://it.at.here', + response: 'ok' + }, { + name: 'route2', + method: 'put', + matcher: 'http://it.at.here', + response: 'ok' + }] + }); + Promise.all([fetch('http://it.at.here', {method: 'put'}), fetch('http://it.at.here'), fetch('http://it.at.here', {method: 'GET'}), fetch('http://it.at.here', {method: 'delete'})]) + .then(function (res) { + expect(fetchMock.called()).to.be.true; + expect(fetchMock.called('route1')).to.be.true; + expect(fetchMock.called('route2')).to.be.true; + expect(fetchMock.calls('route1').length).to.equal(2); + expect(fetchMock.calls('route2').length).to.equal(1); + expect(fetchMock.calls('__unmatched').length).to.equal(1); + done(); + }).catch(done); + }); + it('match multiple routes', function (done) { fetchMock.mock({ routes: [{