Skip to content

Instantly share code, notes, and snippets.

@chrisui
Created March 31, 2017 18:45
Show Gist options
  • Save chrisui/214c62996daba6e5b8f34422086f410d to your computer and use it in GitHub Desktop.
Save chrisui/214c62996daba6e5b8f34422086f410d to your computer and use it in GitHub Desktop.
Component test utility
export const testComponent = (
Component: RC,
defaultProps?
: () => Object
= () => ({}),
) => {
return (otherProps: Object, hoc?: (RC) => RC) => {
// our final props for the component merged from default
// and per-test
const props = {
...defaultProps(),
...otherProps,
};
// our final enhanced component
const FinalComponent = hoc
? hoc(Component)
: Component;
// our element to render given props and component
const element = React.createElement(FinalComponent, props);
// shallow render our component, diving until we reach the
// original component. useful for testing hocs!
const render = (doRender) => {
return doRender(element);
};
return {
props, // final props obj used for testing
element, // react Element ready for rendering
render, // render and provide wrapper around target component
};
};
};
describe('testComponent', () => {
it('should provide an element with merged props', () => {
const Test = () => null;
const Component = props => <Test {...props} />;
const create = testComponent(Component, () => ({
defaultProp: 'DEFAULT_PROP_VALUE',
}));
const {element, props} = create({
fixtureProp: 'FIXTURE_PROP_VALUE',
});
const result = shallow(element);
expect(props).toMatch({
defaultProp: 'DEFAULT_PROP_VALUE',
fixtureProp: 'FIXTURE_PROP_VALUE',
});
expect(result.props()).toMatch({
defaultProp: 'DEFAULT_PROP_VALUE',
fixtureProp: 'FIXTURE_PROP_VALUE',
});
});
it('should allow passing of higher order components and provide render func', () => {
const hoc = Component => props => (
<div>
Enhanced {props.title}!
<Component {...props} />
</div>
);
const Test = () => null;
const Component = props => <Test {...props} />;
const create = testComponent(Component, () => ({
defaultProp: 'DEFAULT_PROP_VALUE',
}));
const {render} = create({title: 'component'}, hoc);
const result = render(shallow);
expect(result.html()).toMatch(/Enhanced component\!/);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment