Last active
March 22, 2018 02:42
-
-
Save cooperka/fbe5e46b936d70f411448d2f334a0868 to your computer and use it in GitHub Desktop.
Jest helper for Redux component testing
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
const mockDispatch = () => {}; | |
function mapEverything(mapStateToProps, mapDispatchToProps, mergeProps, state, ownProps) { | |
const stateProps = mapStateToProps | |
? mapStateToProps(state, ownProps) | |
: {}; | |
const dispatchProps = mapDispatchToProps | |
? mapDispatchToProps(mockDispatch, ownProps) | |
: { | |
dispatch: mockDispatch, | |
}; | |
const mergedProps = mergeProps | |
? mergeProps(stateProps, dispatchProps, ownProps) | |
: { | |
...stateProps, | |
...dispatchProps, | |
...ownProps, | |
}; | |
return mergedProps; | |
} | |
module.exports = { | |
Provider: ({ children }) => children, | |
/** | |
* Returns a modified redux connector which adds a | |
* new method `getMappedProps` to the component for testing purposes. | |
*/ | |
connect: (mapStateToProps, mapDispatchToProps, mergeProps) => (component) => { | |
// Provide access to the mapped props from the component. | |
// eslint-disable-next-line no-param-reassign | |
component.getMappedProps = (state = {}, ownProps = {}) => | |
mapEverything(mapStateToProps, mapDispatchToProps, mergeProps, state, ownProps); | |
return component; | |
}, | |
}; |
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
import * as R from 'ramda'; | |
// This is the same object you pass to `combineReducers`. | |
import { reducersMap } from '../reducers.index'; | |
// Execute each reducer, passing an undefined state to get back their initial state. | |
const defaultState = R.map((reducer) => reducer(undefined, {}), reducersMap); | |
export { defaultState }; |
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
import React from 'react'; | |
import renderer from 'react-test-renderer'; | |
import { defaultState } from '../mockData'; | |
import MyComponent from './component'; | |
// Pass in the default Redux state, along with any specific props you want to mock. | |
const mockProps = DevPanel.getMappedProps(defaultState, { | |
someProp: 'foo', | |
}); | |
it('renders as expected', () => { | |
const component = renderer.create(<MyComponent {...mockProps} />); | |
expect(component.toJSON()).toMatchSnapshot(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment