Created
January 2, 2019 18:13
-
-
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.
This file contains hidden or 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
// 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