Skip to content

Instantly share code, notes, and snippets.

@TravisBernard
Created January 2, 2019 18:13
Show Gist options
  • Save TravisBernard/92e81e079474006c3fff1348b5ae16c1 to your computer and use it in GitHub Desktop.
Save TravisBernard/92e81e079474006c3fff1348b5ae16c1 to your computer and use it in GitHub Desktop.
Using Jest, create a mock that maintains real functionality but also allows method spying.
// FILE: __mocks__/reducers.js
/*
* Wrap every function exported in a module with a Jest mock fn, keeping the original implementation.
* Allows for using the fn().mock.xxx properties to test fn usage and i/o while still maintaining the original
* functionality
*
* Originally wrote this to wrap around Redux reducers and action creators in a React project to spy on reducer
* activity while still testing the store's side effects
*/
const mockifiedReducer = jest.requireActual('./reducers')
Object.entries(mockifiedReducer).reduce((mockObj, [key, val]) => {
if (typeof val === 'function') {
mockObj[key] = jest.fn((...args) => val(...args))
}
return mockObj
}, mockifiedReducer)
module.exports = mockifiedReducer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment