@unhoc/material-ui v1.0.2
Unwrap + Higher Order Components
Effortlessly Unwrap React HOCs for simple unit testing.
Unwrap withStyles from @material-ui/styles.
@unhoc/material-ui is designed to work within the UnHOC ecosystem – see UnHOC for more information.
Installation
Npm
npm install @unhoc/core @unhoc/material-ui --save-devYarn
yarn add @unhoc/core @unhoc/material-ui --devPeer Dependencies
@unhoc/corejssvia@material-ui/styles
Usage
- Import
@unhoc/coreand@unhoc/material-ui.
import createUnHOC from '@unhoc/core';
import { unHOCWithStyles } from '@unhoc/material-ui';- Initialize UnHOC function.
const unhoc = createUnHOC({
plugins: [unHOCWithStyles(mockStyles, options)],
});- Unwrap your React components for testing.
const unwrapped = unhoc(<Component />);Example
We'll use the following React component as the component we wish to test. It's a very simple component that renders "Hello, name" where name is a prop passed in.
The component is then wrapped in Material UI's withStyle method before exporting.
// Component.ts
const styles = createStyles({
root: {
background: '#fff',
},
});
const Component = (props: any) => (
<div className={props.classes.root}>Hello, {props.name}!</div>
);
export default withStyles(styles)(Component);If we were to shallow render this component in a unit test we would actually be rendering the withStyles function and not the component itself.
Instead of trying to unwrap the component ourself, we can UnHOC the withStyles function resulting in our unwrapped Component.
// Component.spec.js
import * as React from 'react';
import { shallow } from 'enzyme';
import createUnHOC from '@unhoc/core';
import { unHOCWithStyles } from '@unhoc/material-ui';
import Component './component';
// Create UnHOC function
const unhoc = createUnHOC({
plugins: [unHOCWithStyles(styles)],
});
// Now we can unwrap our component like unhoc(<Component />); e.g.
test('Hello, UnHOC', () => {
const wrapper = Enzyme.shallow(unhoc(<Component name="UnHOC" />));
expect(wrapper.props()).toHaveProperty('className', 'root-1-0-1');
expect(wrapper.text()).toBe('Hello, UnHOC!');
});See examples for full test files.
API
unHOCWithStyles(styles = {}, options?)
Initializes an UnHOC plugin to unwrap the withStyles HOC from @material-ui/styles
| Param | Type |
|---|---|
| styles | { [key: string]: any } |
| options | jss.StyleSheetFactoryOptions (below) |
// from jss
type StyleSheetFactoryOptions = {
media?: string;
meta?: string;
index?: number;
link?: boolean;
element?: HTMLStyleElement;
generateId?: GenerateId;
classNamePrefix?: string;
};Development
This package is developed as part of the UnHOC project. See UnHOC Development for details.
Versioning
We use SemVer for versioning. For the versions available, see the tags on this repository.
License
This package is part of the UnHOC project and is therefore licensed under the MIT License – see the project LICENSE file for details.