Skip to content

Commit

Permalink
Merge pull request #17 from NOX73/feature/match-method
Browse files Browse the repository at this point in the history
Added method matching support.
  • Loading branch information
wheresrhys committed Oct 5, 2015
2 parents e120ab4 + ec019e7 commit df64a1d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/fetch-mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
Expand Down
26 changes: 26 additions & 0 deletions test/spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: [{
Expand Down

0 comments on commit df64a1d

Please sign in to comment.