Created
April 27, 2020 14:32
-
-
Save sharmaadityaHQ/7dcb1c7bcf159c42bd1f05f7b15acc58 to your computer and use it in GitHub Desktop.
Mock functions or spies in Jest
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
// The mock function factory | |
function fn(impl = () => {}) { | |
const mockFn = function(...args) { | |
mockFn.mock.calls.push(args) | |
mockFn.mock.instances.push(this) | |
try { | |
const value = impl.apply(this, args) | |
mockFn.mock.results.push({ type: "return", value }) | |
return value | |
} | |
catch (value) { | |
mockFn.mock.results.push({ type: "error", value }) | |
throw value | |
} | |
} | |
mockFn.mock = { | |
calls: [], | |
instances: [], | |
results: [] | |
} | |
return mockFn | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment