Skip to content

Instantly share code, notes, and snippets.

@Pajn
Last active December 5, 2015 15:49
Show Gist options
  • Save Pajn/c73849a58c97435c7498 to your computer and use it in GitHub Desktop.
Save Pajn/c73849a58c97435c7498 to your computer and use it in GitHub Desktop.
'use strict';
/**
* Wraps the passed function to track its calls.
*
* All calls are stored in an array on a calls property.
* Every call is an object with a context and args property.
*/
function trackCalls(fn) {
const calls = [];
const wrap = function() {
calls.push({
args: arguments,
context: this,
});
return fn.apply(this, arguments);
};
wrap.calls = calls;
return wrap;
}
function createMockFunction() {
let defaultReturnValue;
const returnValues = [];
const mock = trackCalls(() =>
(
returnValues.find(returnValue =>
arguments.length === returnValue.args.length &&
returnValue.args.every((arg, index) => arg === arguments[index])
) || defaultReturnValue
).returnValue;
);
mock.returns = function (args, returnValue) {
if (arguments.length === 1) {
defaultReturnValue = {returnValue: returnValue};
} else {
returnValues.push({
args: args,
returnValue: returnValue,
});
}
return mock;
};
return mock;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment