Socket
Socket
Sign inDemoInstall

fetch-mock

Package Overview
Dependencies
Maintainers
3
Versions
226
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fetch-mock - npm Package Compare versions

Comparing version 8.2.1 to 8.3.0

56

cjs/lib/compile-route.js
const generateMatcher = require('./generate-matcher');
const matcherProperties = [
'query',
'method',
'headers',
'params',
'body',
'functionMatcher',
'url'
];
const isUrlMatcher = matcher =>
matcher instanceof RegExp ||
typeof matcher === 'string' ||
(typeof matcher === 'object' && 'href' in matcher);
const isFunctionMatcher = matcher => typeof matcher === 'function';
const argsToRoute = args => {
const [matcher, response, options = {}] = args;
const routeConfig = {};
if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) {
routeConfig.matcher = matcher;
} else {
Object.assign(routeConfig, matcher);
}
if (response) {
routeConfig.response = response;
}
Object.assign(routeConfig, options);
return routeConfig;
};
const sanitizeRoute = route => {

@@ -9,4 +44,8 @@ route = Object.assign({}, route);

}
route.identifier = route.name || route.matcher;
if (isUrlMatcher(route.matcher)) {
route.url = route.matcher;
delete route.matcher;
}
route.identifier = route.name || route.url;
route.functionMatcher = route.matcher || route.functionMatcher;
return route;

@@ -20,5 +59,5 @@ };

if (!route.matcher) {
if (!matcherProperties.some(matcherType => matcherType in route)) {
throw new Error(
'fetch-mock: Each route must specify a string, regex or function to match calls to fetch'
"fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'"
);

@@ -54,5 +93,5 @@ }

module.exports = route => {
const compileRoute = function(args) {
const route = sanitizeRoute(argsToRoute(args));
validateRoute(route);
route = sanitizeRoute(route);
route.matcher = generateMatcher(route);

@@ -64,2 +103,5 @@ limitMatcher(route);

module.exports.sanitizeRoute = sanitizeRoute;
module.exports = {
compileRoute,
sanitizeRoute
};

51

cjs/lib/generate-matcher.js

@@ -52,4 +52,4 @@ const glob = require('glob-to-regexp');

const getParamsMatcher = ({ params: expectedParams, matcher }) => {
if (!/express:/.test(matcher)) {
const getParamsMatcher = ({ params: expectedParams, url: matcheUrl }) => {
if (!/express:/.test(matcheUrl)) {
throw new Error(

@@ -61,3 +61,3 @@ 'fetch-mock: matching on params is only possible when using an express: matcher'

const keys = [];
const re = pathToRegexp(matcher.replace(/^express:/, ''), keys);
const re = pathToRegexp(matcheUrl.replace(/^express:/, ''), keys);
return url => {

@@ -75,5 +75,2 @@ const vals = re.exec(getPath(url)) || [];

const getFunctionMatcher = ({ matcher, functionMatcher = () => true }) =>
typeof matcher === 'function' ? matcher : functionMatcher;
const getBodyMatcher = ({ body: expectedBody }) => {

@@ -96,3 +93,3 @@ return (url, { body, method = 'get' }) => {

const getFullUrlMatcher = (route, matcher, query) => {
const getFullUrlMatcher = (route, matcherUrl, query) => {
// if none of the special syntaxes apply, it's just a simple string match

@@ -102,42 +99,40 @@ // but we have to be careful to normalize the url we check and the name

// from http://it.at.there/ once we start generating Request/Url objects
const expectedUrl = normalizeUrl(matcher);
if (route.identifier === matcher) {
const expectedUrl = normalizeUrl(matcherUrl);
if (route.identifier === matcherUrl) {
route.identifier = expectedUrl;
}
return url => {
return matcherUrl => {
if (query && expectedUrl.indexOf('?')) {
return url.indexOf(expectedUrl) === 0;
return matcherUrl.indexOf(expectedUrl) === 0;
}
return normalizeUrl(url) === expectedUrl;
return normalizeUrl(matcherUrl) === expectedUrl;
};
};
const getFunctionMatcher = ({ functionMatcher }) => functionMatcher;
const getUrlMatcher = route => {
const { matcher, query } = route;
const { url: matcherUrl, query } = route;
if (typeof matcher === 'function') {
if (matcherUrl === '*') {
return () => true;
}
if (matcher instanceof RegExp) {
return url => matcher.test(url);
if (matcherUrl instanceof RegExp) {
return url => matcherUrl.test(url);
}
if (matcher === '*') {
return () => true;
if (matcherUrl.href) {
return getFullUrlMatcher(route, matcherUrl.href, query);
}
if (matcher.href) {
return getFullUrlMatcher(route, matcher.href, query);
}
for (const shorthand in stringMatchers) {
if (matcher.indexOf(shorthand + ':') === 0) {
const url = matcher.replace(new RegExp(`^${shorthand}:`), '');
return stringMatchers[shorthand](url);
if (matcherUrl.indexOf(shorthand + ':') === 0) {
const urlFragment = matcherUrl.replace(new RegExp(`^${shorthand}:`), '');
return stringMatchers[shorthand](urlFragment);
}
}
return getFullUrlMatcher(route, matcher, query);
return getFullUrlMatcher(route, matcherUrl, query);
};

@@ -152,4 +147,4 @@

route.body && getBodyMatcher(route),
getFunctionMatcher(route),
getUrlMatcher(route)
route.functionMatcher && getFunctionMatcher(route),
route.url && getUrlMatcher(route)
].filter(matcher => !!matcher);

@@ -156,0 +151,0 @@

@@ -1,25 +0,7 @@

const compileRoute = require('./compile-route');
const { compileRoute } = require('./compile-route');
const FetchMock = {};
const argsToRoute = args => {
const [matcher, response, options = {}] = args;
// Handle the variety of parameters accepted by mock (see README)
if (matcher && response) {
return Object.assign(
{
matcher,
response
},
options
);
} else if (matcher && matcher.matcher) {
return matcher;
} else {
throw new Error('fetch-mock: Invalid parameters passed to fetch-mock');
}
};
FetchMock.mock = function(...args) {
if (args.length) {
this.addRoute(argsToRoute(args));
this.addRoute(args);
}

@@ -95,5 +77,7 @@

const defineShorthand = (methodName, underlyingMethod, shorthandOptions) => {
FetchMock[methodName] = function(...args) {
FetchMock[methodName] = function(matcher, response, options) {
return this[underlyingMethod](
Object.assign(argsToRoute(args), shorthandOptions)
matcher,
response,
Object.assign(options || {}, shorthandOptions)
);

@@ -100,0 +84,0 @@ };

@@ -11,2 +11,10 @@ 'use strict';

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -16,2 +24,34 @@

var matcherProperties = ['query', 'method', 'headers', 'params', 'body', 'functionMatcher', 'url'];
var isUrlMatcher = function isUrlMatcher(matcher) {
return matcher instanceof RegExp || typeof matcher === 'string' || (typeof matcher === 'undefined' ? 'undefined' : (0, _typeof3.default)(matcher)) === 'object' && 'href' in matcher;
};
var isFunctionMatcher = function isFunctionMatcher(matcher) {
return typeof matcher === 'function';
};
var argsToRoute = function argsToRoute(args) {
var _args = (0, _slicedToArray3.default)(args, 3),
matcher = _args[0],
response = _args[1],
_args$ = _args[2],
options = _args$ === undefined ? {} : _args$;
var routeConfig = {};
if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) {
routeConfig.matcher = matcher;
} else {
(0, _assign2.default)(routeConfig, matcher);
}
if (response) {
routeConfig.response = response;
}
(0, _assign2.default)(routeConfig, options);
return routeConfig;
};
var sanitizeRoute = function sanitizeRoute(route) {

@@ -23,4 +63,8 @@ route = (0, _assign2.default)({}, route);

}
route.identifier = route.name || route.matcher;
if (isUrlMatcher(route.matcher)) {
route.url = route.matcher;
delete route.matcher;
}
route.identifier = route.name || route.url;
route.functionMatcher = route.matcher || route.functionMatcher;
return route;

@@ -34,4 +78,6 @@ };

if (!route.matcher) {
throw new Error('fetch-mock: Each route must specify a string, regex or function to match calls to fetch');
if (!matcherProperties.some(function (matcherType) {
return matcherType in route;
})) {
throw new Error("fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'");
}

@@ -74,5 +120,5 @@ };

module.exports = function (route) {
var compileRoute = function compileRoute(args) {
var route = sanitizeRoute(argsToRoute(args));
validateRoute(route);
route = sanitizeRoute(route);
route.matcher = generateMatcher(route);

@@ -84,2 +130,5 @@ limitMatcher(route);

module.exports.sanitizeRoute = sanitizeRoute;
module.exports = {
compileRoute: compileRoute,
sanitizeRoute: sanitizeRoute
};

@@ -98,5 +98,5 @@ 'use strict';

var expectedParams = _ref6.params,
matcher = _ref6.matcher;
matcheUrl = _ref6.url;
if (!/express:/.test(matcher)) {
if (!/express:/.test(matcheUrl)) {
throw new Error('fetch-mock: matching on params is only possible when using an express: matcher');

@@ -106,3 +106,3 @@ }

var keys = [];
var re = pathToRegexp(matcher.replace(/^express:/, ''), keys);
var re = pathToRegexp(matcheUrl.replace(/^express:/, ''), keys);
return function (url) {

@@ -121,19 +121,10 @@ var vals = re.exec(getPath(url)) || [];

var getFunctionMatcher = function getFunctionMatcher(_ref8) {
var matcher = _ref8.matcher,
_ref8$functionMatcher = _ref8.functionMatcher,
functionMatcher = _ref8$functionMatcher === undefined ? function () {
return true;
} : _ref8$functionMatcher;
return typeof matcher === 'function' ? matcher : functionMatcher;
};
var getBodyMatcher = function getBodyMatcher(_ref8) {
var expectedBody = _ref8.body;
var getBodyMatcher = function getBodyMatcher(_ref9) {
var expectedBody = _ref9.body;
return function (url, _ref9) {
var body = _ref9.body,
_ref9$method = _ref9.method,
method = _ref9$method === undefined ? 'get' : _ref9$method;
return function (url, _ref10) {
var body = _ref10.body,
_ref10$method = _ref10.method,
method = _ref10$method === undefined ? 'get' : _ref10$method;
if (method.toLowerCase() === 'get') {

@@ -154,3 +145,3 @@ // GET requests don’t send a body so the body matcher should be ignored for them

var getFullUrlMatcher = function getFullUrlMatcher(route, matcher, query) {
var getFullUrlMatcher = function getFullUrlMatcher(route, matcherUrl, query) {
// if none of the special syntaxes apply, it's just a simple string match

@@ -160,21 +151,26 @@ // but we have to be careful to normalize the url we check and the name

// from http://it.at.there/ once we start generating Request/Url objects
var expectedUrl = normalizeUrl(matcher);
if (route.identifier === matcher) {
var expectedUrl = normalizeUrl(matcherUrl);
if (route.identifier === matcherUrl) {
route.identifier = expectedUrl;
}
return function (url) {
return function (matcherUrl) {
if (query && expectedUrl.indexOf('?')) {
return url.indexOf(expectedUrl) === 0;
return matcherUrl.indexOf(expectedUrl) === 0;
}
return normalizeUrl(url) === expectedUrl;
return normalizeUrl(matcherUrl) === expectedUrl;
};
};
var getFunctionMatcher = function getFunctionMatcher(_ref10) {
var functionMatcher = _ref10.functionMatcher;
return functionMatcher;
};
var getUrlMatcher = function getUrlMatcher(route) {
var matcher = route.matcher,
var matcherUrl = route.url,
query = route.query;
if (typeof matcher === 'function') {
if (matcherUrl === '*') {
return function () {

@@ -185,30 +181,24 @@ return true;

if (matcher instanceof RegExp) {
if (matcherUrl instanceof RegExp) {
return function (url) {
return matcher.test(url);
return matcherUrl.test(url);
};
}
if (matcher === '*') {
return function () {
return true;
};
if (matcherUrl.href) {
return getFullUrlMatcher(route, matcherUrl.href, query);
}
if (matcher.href) {
return getFullUrlMatcher(route, matcher.href, query);
}
for (var shorthand in stringMatchers) {
if (matcher.indexOf(shorthand + ':') === 0) {
var url = matcher.replace(new RegExp('^' + shorthand + ':'), '');
return stringMatchers[shorthand](url);
if (matcherUrl.indexOf(shorthand + ':') === 0) {
var urlFragment = matcherUrl.replace(new RegExp('^' + shorthand + ':'), '');
return stringMatchers[shorthand](urlFragment);
}
}
return getFullUrlMatcher(route, matcher, query);
return getFullUrlMatcher(route, matcherUrl, query);
};
module.exports = function (route) {
var matchers = [route.query && getQueryStringMatcher(route), route.method && getMethodMatcher(route), route.headers && getHeaderMatcher(route), route.params && getParamsMatcher(route), route.body && getBodyMatcher(route), getFunctionMatcher(route), getUrlMatcher(route)].filter(function (matcher) {
var matchers = [route.query && getQueryStringMatcher(route), route.method && getMethodMatcher(route), route.headers && getHeaderMatcher(route), route.params && getParamsMatcher(route), route.body && getBodyMatcher(route), route.functionMatcher && getFunctionMatcher(route), route.url && getUrlMatcher(route)].filter(function (matcher) {
return !!matcher;

@@ -215,0 +205,0 @@ });

@@ -7,32 +7,9 @@ 'use strict';

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _require = require('./compile-route'),
compileRoute = _require.compileRoute;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var compileRoute = require('./compile-route');
var FetchMock = {};
var argsToRoute = function argsToRoute(args) {
var _args = (0, _slicedToArray3.default)(args, 3),
matcher = _args[0],
response = _args[1],
_args$ = _args[2],
options = _args$ === undefined ? {} : _args$;
// Handle the variety of parameters accepted by mock (see README)
if (matcher && response) {
return (0, _assign2.default)({
matcher: matcher,
response: response
}, options);
} else if (matcher && matcher.matcher) {
return matcher;
} else {
throw new Error('fetch-mock: Invalid parameters passed to fetch-mock');
}
};
FetchMock.mock = function () {

@@ -44,3 +21,3 @@ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {

if (args.length) {
this.addRoute(argsToRoute(args));
this.addRoute(args);
}

@@ -111,8 +88,4 @@

var defineShorthand = function defineShorthand(methodName, underlyingMethod, shorthandOptions) {
FetchMock[methodName] = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return this[underlyingMethod]((0, _assign2.default)(argsToRoute(args), shorthandOptions));
FetchMock[methodName] = function (matcher, response, options) {
return this[underlyingMethod](matcher, response, (0, _assign2.default)(options || {}, shorthandOptions));
};

@@ -119,0 +92,0 @@ };

{
"name": "fetch-mock",
"type": "module",
"version": "8.2.1",
"version": "8.3.0",
"description": "Mock http requests made using fetch (or isomorphic-fetch)",

@@ -6,0 +6,0 @@ "main": "./cjs/server.js",

@@ -45,2 +45,4 @@ # fetch-mock

If you're using jest as your test runner, consider using [fetch-mock-jest](https://www.npmjs.com/package/fetch-mock-jest), a lightweight, jest-friendly wrapper around fetch-mock.
## License

@@ -47,0 +49,0 @@

@@ -56,2 +56,18 @@ import fetchMock = require('..');

fetchMock.mock({
url: "http://test.com",
response: 200,
headers: {},
query: {},
params: {},
body: {},
repeat: 1,
delay: 500,
functionMatcher: () => true
});
fetchMock.mock({
url: "http://test.com",
}, 200);
fetchMock.restore().reset().resetHistory().resetBehavior();

@@ -58,0 +74,0 @@

@@ -22,2 +22,6 @@ // Project: https://github.com/wheresrhys/fetch-mock, http://www.wheresrhys.co.uk/fetch-mock

type MockMatcherUrl = string | RegExp;
/**

@@ -36,3 +40,3 @@ * Mock matcher. Can be one of following:

*/
type MockMatcher = string | RegExp | MockMatcherFunction;
type MockMatcher = MockMatcherUrl | MockMatcherFunction;

@@ -174,2 +178,4 @@ /**

url?: MockMatcherUrl;
/**

@@ -258,3 +264,3 @@ * This option allows for existing routes in a mock to be overwritten.

*/
mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptions): this;
mock(matcher: MockMatcher | MockOptions, response: MockResponse | MockResponseFunction, options?: MockOptions): this;

@@ -261,0 +267,0 @@ /**

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc