Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
wheresrhys committed Jan 25, 2020
1 parent a575bb8 commit e6dff32
Show file tree
Hide file tree
Showing 9 changed files with 129 additions and 98 deletions.
20 changes: 12 additions & 8 deletions src/lib/compile-route.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {debug, getDebug, setDebugNamespace} = require('./debug');
const { getDebug } = require('./debug');
const generateMatcher = require('./generate-matcher');

const matcherProperties = [
Expand Down Expand Up @@ -47,7 +47,7 @@ const sanitizeRoute = route => {
route.method = route.method.toLowerCase();
}
if (isUrlMatcher(route.matcher)) {
debug('Mock uses a url matcher', route.matcher)
debug('Mock uses a url matcher', route.matcher);
route.url = route.matcher;
delete route.matcher;
}
Expand Down Expand Up @@ -79,7 +79,9 @@ const limit = route => {
const debug = getDebug('limit()');
debug('Limiting number of requests to handle by route');
if (!route.repeat) {
debug(' No `repeat` value set on route. Will match any number of requests');
debug(
' No `repeat` value set on route. Will match any number of requests'
);
return;
}

Expand All @@ -98,17 +100,19 @@ const limit = route => {

const delayResponse = route => {
const debug = getDebug('delayResponse()');
debug(`Applying response delay settings`)
debug(`Applying response delay settings`);
const { delay } = route;
if (delay) {
debug(` Wrapping response in delay of ${delay} miliseconds`)
debug(` Wrapping response in delay of ${delay} miliseconds`);
const response = route.response;
route.response = () => {
debug(`Delaying response by ${delay} miliseconds`)
debug(`Delaying response by ${delay} miliseconds`);
return new Promise(res => setTimeout(() => res(response), delay));
}
};
} else {
debug(` No delay set on route. Will respond 'immediately' (but asynchronously)`)
debug(
` No delay set on route. Will respond 'immediately' (but asynchronously)`
);
}
};

Expand Down
20 changes: 11 additions & 9 deletions src/lib/debug.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
const debug = require('debug');

let debugFunc
let debugFunc;
let phase = 'default';
let namespace = '';
const newDebug = () => {
debugFunc = namespace ? debug(`fetch-mock:${phase}:${namespace}`) : debug(`fetch-mock:${phase}`)
}
debugFunc = namespace
? debug(`fetch-mock:${phase}:${namespace}`)
: debug(`fetch-mock:${phase}`);
};

const newDebugSandbox = (ns) => debug(`fetch-mock:${phase}:${ns}`);
const newDebugSandbox = ns => debug(`fetch-mock:${phase}:${ns}`);

newDebug()
newDebug();

module.exports = {
debug: (...args) => {
debugFunc(...args)
debugFunc(...args);
},
setDebugNamespace: str => {
namespace = str
namespace = str;
newDebug();
},
setDebugPhase: str => {
phase = str || 'default';
newDebug();
},
getDebug: (namespace) => newDebugSandbox(namespace)
}
getDebug: namespace => newDebugSandbox(namespace)
};
30 changes: 18 additions & 12 deletions src/lib/fetch-handler.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {debug, setDebugPhase, getDebug} = require('./debug');
const { debug, setDebugPhase, getDebug } = require('./debug');
const responseBuilder = require('./response-builder');
const requestUtils = require('./request-utils');
const FetchMock = {};
Expand Down Expand Up @@ -64,7 +64,7 @@ const resolve = async (
FetchMock.fetchHandler = function(url, options, request) {
setDebugPhase('handle');
const debug = getDebug('fetchHandler()');
debug('fetch called with:', url, options)
debug('fetch called with:', url, options);
const normalizedRequest = requestUtils.normalizeRequest(
url,
options,
Expand All @@ -75,11 +75,11 @@ FetchMock.fetchHandler = function(url, options, request) {

const { signal } = normalizedRequest;

debug('Request normalised')
debug(' url', url)
debug(' options', options)
debug(' request', request)
debug(' signal', signal)
debug('Request normalised');
debug(' url', url);
debug(' options', options);
debug(' request', request);
debug(' signal', signal);

const route = this.executeRouter(url, options, request);

Expand Down Expand Up @@ -114,7 +114,7 @@ FetchMock.fetchHandler = function(url, options, request) {
.then(done, done)
.then(() => {
setDebugPhase();
})
});
});
};

Expand Down Expand Up @@ -188,9 +188,9 @@ FetchMock.generateResponse = async function(route, url, options, request) {

FetchMock.router = function(url, options, request) {
const route = this.routes.find((route, i) => {
debug(`Trying to match route ${i}`)
return route.matcher(url, options, request)
});
debug(`Trying to match route ${i}`);
return route.matcher(url, options, request);
});

if (route) {
this.push({
Expand All @@ -214,7 +214,13 @@ FetchMock.getNativeFetch = function() {
};

FetchMock.push = function({ url, options, request, isUnmatched, identifier }) {
debug('Recording fetch call', { url, options, request, isUnmatched, identifier })
debug('Recording fetch call', {
url,
options,
request,
isUnmatched,
identifier
});
const args = [url, options];
args.request = request;
args.identifier = identifier;
Expand Down
6 changes: 3 additions & 3 deletions src/lib/generate-matcher.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {debug, getDebug, setDebugNamespace} = require('./debug');
const { debug, setDebugNamespace } = require('./debug');
const glob = require('glob-to-regexp');
const pathToRegexp = require('path-to-regexp');
const querystring = require('querystring');
Expand Down Expand Up @@ -203,7 +203,7 @@ const getUrlMatcher = route => {
};

module.exports = route => {
setDebugNamespace('generateMatcher()')
setDebugNamespace('generateMatcher()');
debug('Compiling matcher for route');
const matchers = [
route.query && getQueryStringMatcher(route),
Expand All @@ -216,7 +216,7 @@ module.exports = route => {
].filter(matcher => !!matcher);

debug('Compiled matcher for route');
setDebugNamespace()
setDebugNamespace();
return (url, options = {}, request) =>
matchers.every(matcher => matcher(url, options, request));
};
6 changes: 3 additions & 3 deletions src/lib/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {debug} = require('./debug');
const { debug } = require('./debug');
const setUpAndTearDown = require('./set-up-and-tear-down');
const fetchHandler = require('./fetch-handler');
const inspecting = require('./inspecting');
Expand All @@ -14,7 +14,7 @@ FetchMock.config = {
};

FetchMock.createInstance = function() {
debug('Creating fetch-mock instance')
debug('Creating fetch-mock instance');
const instance = Object.create(FetchMock);
instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice();
instance.routes = instance._uncompiledRoutes.map(config =>
Expand All @@ -36,7 +36,7 @@ FetchMock.bindMethods = function() {
};

FetchMock.sandbox = function() {
debug('Creating sandboxed fetch-mock instance')
debug('Creating sandboxed fetch-mock instance');
// this construct allows us to create a fetch-mock instance which is also
// a callable function, while circumventing circularity when defining the
// object that this function should be bound to
Expand Down
106 changes: 62 additions & 44 deletions src/lib/inspecting.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {setDebugPhase, setDebugNamespace, debug} = require('./debug');
const { setDebugPhase, setDebugNamespace, debug } = require('./debug');
const { normalizeUrl } = require('./request-utils');
const FetchMock = {};
const { sanitizeRoute } = require('./compile-route');
Expand All @@ -11,50 +11,57 @@ const filterCallsWithMatcher = (matcher, options = {}, calls) => {
return calls.filter(([url, options]) => matcher(normalizeUrl(url), options));
};

const formatDebug = (func) => {
return function (...args) {
setDebugPhase('inspect')
const formatDebug = func => {
return function(...args) {
setDebugPhase('inspect');
const result = func.call(this, ...args);
setDebugPhase()
setDebugPhase();
return result;
}
}
};
};

FetchMock.filterCalls = function(nameOrMatcher, options) {
debug('Filtering fetch calls')
debug('Filtering fetch calls');
let calls = this._calls;
let matcher = '*';

if ([true, 'matched'].includes(nameOrMatcher)) {
debug(`Filter provided is ${nameOrMatcher}. Returning matched calls only`)
debug(`Filter provided is ${nameOrMatcher}. Returning matched calls only`);
calls = calls.filter(({ isUnmatched }) => !isUnmatched);

} else if ([false, 'unmatched'].includes(nameOrMatcher)) {
debug(`Filter provided is ${nameOrMatcher}. Returning unmatched calls only`)
debug(
`Filter provided is ${nameOrMatcher}. Returning unmatched calls only`
);
calls = calls.filter(({ isUnmatched }) => isUnmatched);
} else if (typeof nameOrMatcher === 'undefined') {
debug(`Filter provided is undefined. Returning all calls`)
debug(`Filter provided is undefined. Returning all calls`);
calls = calls;
} else if (isName(nameOrMatcher)) {
debug(`Filter provided, looks like the name of a named route. Returning only calls handled by that route`)
debug(
`Filter provided, looks like the name of a named route. Returning only calls handled by that route`
);
calls = calls.filter(({ identifier }) => identifier === nameOrMatcher);
} else {
matcher = normalizeUrl(nameOrMatcher);
if (this.routes.some(({ identifier }) => identifier === matcher)) {
debug(`Filter provided, ${nameOrMatcher}, identifies a route. Returning only calls handled by that route`)
debug(
`Filter provided, ${nameOrMatcher}, identifies a route. Returning only calls handled by that route`
);
calls = calls.filter(call => call.identifier === matcher);
}
}


if ((options || matcher !== '*') && calls.length) {
if (typeof options === 'string') {
options = { method: options };
}
debug('Compiling filter and options to route in order to filter all calls', nameOrMatcher)
debug(
'Compiling filter and options to route in order to filter all calls',
nameOrMatcher
);
calls = filterCallsWithMatcher(matcher, options, calls);
}
debug(`Retrieved ${calls.length} calls`)
debug(`Retrieved ${calls.length} calls`);
return calls;
};

Expand Down Expand Up @@ -84,45 +91,50 @@ FetchMock.called = formatDebug(function(nameOrMatcher, options) {
});

FetchMock.flush = formatDebug(async function(waitForResponseMethods) {
setDebugNamespace('flush')
debug(`flushing all fetch calls. ${waitForResponseMethods ? '' : 'Not '}waiting for response bodies to complete download`);
setDebugNamespace('flush');
debug(
`flushing all fetch calls. ${
waitForResponseMethods ? '' : 'Not '
}waiting for response bodies to complete download`
);

const queuedPromises = this._holdingPromises;
this._holdingPromises = [];
debug(`${queuedPromises.length} fetch calls to be awaited`)
debug(`${queuedPromises.length} fetch calls to be awaited`);

await Promise.all(queuedPromises)
debug(`All fetch calls have completed`)
await Promise.all(queuedPromises);
debug(`All fetch calls have completed`);
if (waitForResponseMethods && this._holdingPromises.length) {
debug(`Awaiting all fetch bodies to download`)
debug(`Awaiting all fetch bodies to download`);
await this.flush(waitForResponseMethods);
debug(`All fetch bodies have completed downloading`)
debug(`All fetch bodies have completed downloading`);
}
setDebugNamespace()
setDebugNamespace();
});

FetchMock.done = formatDebug(function(nameOrMatcher) {
setDebugPhase('inspect')
setDebugNamespace('done')
debug('Checking to see if expected calls have been made')
setDebugPhase('inspect');
setDebugNamespace('done');
debug('Checking to see if expected calls have been made');
let routesToCheck;


if(nameOrMatcher && typeof nameOrMatcher !== 'boolean') {
debug('Checking to see if expected calls have been made for single route:', nameOrMatcher)
routesToCheck = [{ identifier: nameOrMatcher }]
} else {
debug('Checking to see if expected calls have been made for all routes')
routesToCheck = this.routes;
}

if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') {
debug(
'Checking to see if expected calls have been made for single route:',
nameOrMatcher
);
routesToCheck = [{ identifier: nameOrMatcher }];
} else {
debug('Checking to see if expected calls have been made for all routes');
routesToCheck = this.routes;
}

// Can't use array.every because would exit after first failure, which would
// break the logging
const result = routesToCheck
.map(({ identifier }) => {
if (!this.called(identifier)) {
debug('No calls made for route:', identifier)
debug('No calls made for route:', identifier);
console.warn(`Warning: ${identifier} not called`); // eslint-disable-line
return false;
}
Expand All @@ -132,14 +144,20 @@ FetchMock.done = formatDebug(function(nameOrMatcher) {
).repeat;

if (!expectedTimes) {
debug('Route has been called at least once, and no expectation of more set:', identifier)
debug(
'Route has been called at least once, and no expectation of more set:',
identifier
);
return true;
}
const actualTimes = this.filterCalls(identifier).length;

debug(`Route called ${actualTimes} times:`, identifier)
debug(`Route called ${actualTimes} times:`, identifier);
if (expectedTimes > actualTimes) {
debug(`Route called ${actualTimes} times, but expected ${expectedTimes}:`, identifier)
debug(
`Route called ${actualTimes} times, but expected ${expectedTimes}:`,
identifier
);
console.warn(
`Warning: ${identifier} only called ${actualTimes} times, but ${expectedTimes} expected`
); // eslint-disable-line
Expand All @@ -150,9 +168,9 @@ FetchMock.done = formatDebug(function(nameOrMatcher) {
})
.every(isDone => isDone);

setDebugNamespace()
setDebugPhase()
return result
setDebugNamespace();
setDebugPhase();
return result;
});

module.exports = FetchMock;

0 comments on commit e6dff32

Please sign in to comment.