UnHOC React Redux
Unwrap + Higher Order Components
Effortlessly Unwrap React HOCs for simple unit testing.
Unwrap connect
from react-redux
.
@unhoc/react-redux
is designed to work within the UnHOC ecosystem – see UnHOC for more information.
Installation
Npm
npm install @unhoc/core @unhoc/react-redux --save-dev
Yarn
yarn add @unhoc/core @unhoc/react-redux --dev
Peer Dependencies
@unhoc/core
Usage
- Import
@unhoc/core
and@unhoc/react-redux
.
import createUnHOC from '@unhoc/core';
import { unHOCConnect } from '@unhoc/react-redux';
- Initialize UnHOC function.
const unhoc = createUnHOC({
plugins: [unHOCConnect(mockState, mockDispatch)],
});
- 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 part of the Redux state.
The component is then wrapped with connect
from react-redux
before exporting.
// Component.ts
const mapStateToProps = state => ({ name: state.name });
const Component = connect(mapStateToProps)((props: any) => (
<div>Hello, {props.name}!</div>
));
export default connect(mapStateToProps)(Component);
If we were to shallow render this component in a unit test we would actually be rendering the connect function and not the component itself.
Instead of trying to unwrap the component ourself, we can UnHOC the connect function resulting in our unwrapped Component.
// Component.spec.js
import * as React from 'react';
import { shallow } from 'enzyme';
import createUnHOC from '@unhoc/core';
import { unHOCConnect } from '@unhoc/react-redux';
import Component './component';
// Create UnHOC function
const unhoc = createUnHOC({
plugins: [unHOCConnect({ name: 'UnHOC' })],
});
// Now we can unwrap our component like unhoc(<Component />); e.g.
test('Hello, UnHOC', () => {
const wrapper = Enzyme.shallow(unhoc(<Component />));
expect(wrapper.text()).toBe('Hello, UnHOC!');
});
See examples for full test files.
API
unHOCConnect(mockState?, mockDispatch?)
Initializes an UnHOC plugin to unwrap the connect
HOC from react-redux
.
Param | Type |
---|---|
mockState | { [key: string]: any } |
mockDispatch | { [key: string]: any } |
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.