Unwrap + Higher Order Components
Effortlessly Unwrap React HOCs for simple unit testing.
Unwrap React.memo
from react
.
@unhoc/react
is designed to work within the UnHOC ecosystem – see UnHOC for more information.
Npm
npm install @unhoc/core @unhoc/react --save-dev
Yarn
yarn add @unhoc/core @unhoc/react --dev
@unhoc/core
- Import
@unhoc/core
and@unhoc/react
.
import createUnHOC from '@unhoc/core';
import { unHOCMemo } from '@unhoc/react';
- Initialize UnHOC function.
const unhoc = createUnHOC({
plugins: [unHOCMemo()],
});
- Unwrap your React components for testing.
const unwrapped = unhoc(<Component />);
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 memoized by wrapping the component in the React.memo
method before exporting.
// Component.js
import * as React from 'react';
const Component = props => <div>Hello, {props.name}!</div>;
export default React.memo(Component);
If we were to shallow render this component in a unit test we would actually be rendering the memoized function and not the component itself.
Instead of trying to unwrap the component ourself, we can UnHOC the memoized function resulting in our unwrapped Component.
// Component.spec.js
import * as React from 'react';
import { shallow } from 'enzyme';
import createUnHOC from '@unhoc/core';
import { unHOCMemo } from '@unhoc/react';
import Component './component';
// Create UnHOC function
const unhoc = createUnHOC({
plugins: [
unHOCMemo()
],
});
// Now we can unwrap our component like unhoc(<Component />); e.g.
test('Hello, UnHOC', () => {
const wrapper = Enzyme.shallow(unhoc(<Component name="UnHOC" />));
expect(wrapper.text()).toBe('Hello, UnHOC!');
});
See examples for full test files.
Initializes an UnHOC plugin to unwrap the memo
HOC from react
.
This package is developed as part of the UnHOC project. See UnHOC Development for details.
We use SemVer for versioning. For the versions available, see the tags on this repository.
This package is part of the UnHOC project and is therefore licensed under the MIT License – see the project LICENSE file for details.