Last active
December 5, 2015 15:49
-
-
Save Pajn/c73849a58c97435c7498 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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