Skip to content

Instantly share code, notes, and snippets.

@anthify
Created July 17, 2019 08:45
Show Gist options
  • Save anthify/a905ed34265298f9b1b827e23560270c to your computer and use it in GitHub Desktop.
Save anthify/a905ed34265298f9b1b827e23560270c to your computer and use it in GitHub Desktop.
Wrapper for Enzyme and Styled Components
import React from 'react';
import { ThemeConsumer } from 'styled-components';
import { mount } from 'enzyme';
import theme from '../../app/theme';
/**
* find is object to provide quick short end element selectors
*/
export const find = subject => ({
attr: (attr, value, el = '') => subject.find(`${el}[${attr}="${value}"]`),
name: (name, el = '') => subject.find(`${el}[name="${name}"]`),
type: (type, el = '') => subject.find(`${el}[type="${type}"]`),
className: className => subject.find(`.${className}`)
});
/**
* render uses mount with theme to inject context for theme support
* whilst returning the Component as the root (as opposed to the ThemeProvider)
*/
const mountWithTheme = tree => {
ThemeConsumer._currentValue = theme;
return mount(tree);
};
export const render = Component => props =>
mountWithTheme(<Component {...props} />);
/**
* createProps is designed to make more integrated tests with react components and redux easier
* and slight less bloated than what it is already.
*
* Instatiate the mapStateToProps function from the component, and mergeProps (if there is one).
*
* If mergeProps contains a resource/service then include that in the init call i.e. createProps(..., mergeProps(myService()))
*
* Example:
*
* const { props, newProps } = createProps(mapStateToProps, mergeProps)(stateProps, dispatchProps, ownProps);
*
* props <- Object representing the props that would be inejcted into your Component
*
* newProps <- a method that can be used to create new props.
*
* Example:
*
* const stateForTest = newProps({ reducer: myReducer(undefined, dispatchAnError()) })
*/
export const createProps = (mapStateToProps, mergeProps = props => props) => (
stateProps = {},
dispatchProps = {},
ownProps = {}
) => ({
props: mergeProps(mapStateToProps(stateProps), dispatchProps, ownProps),
newProps: (p = stateProps, d = dispatchProps, o = ownProps) =>
mergeProps(mapStateToProps(p), d, o)
});
/**
*
* @param {array} actions
* Array containing executed action functions.
* Example:
* sequence([ actionOne(), actionTwo(arg) ], reducer);
* @param {function} reducer
* reducer function - not extecuted. Initial reducer call is hanlded by this method before
* actions are triggered.
*
* Example:
* sequence(actionsArray, myReducer)
*/
export const sequence = (actions = [], reducer) =>
actions.reduce((prev, curr) => reducer(prev, curr), reducer());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment