Skip to content

Instantly share code, notes, and snippets.

@sharmaadityaHQ
Created April 27, 2020 14:32
Show Gist options
  • Save sharmaadityaHQ/7dcb1c7bcf159c42bd1f05f7b15acc58 to your computer and use it in GitHub Desktop.
Save sharmaadityaHQ/7dcb1c7bcf159c42bd1f05f7b15acc58 to your computer and use it in GitHub Desktop.
Mock functions or spies in Jest
// 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