Skip to content

Latest commit

 

History

History

react

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

UnHOC React


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.

Installation

Npm

npm install @unhoc/core @unhoc/react --save-dev

Yarn

yarn add @unhoc/core @unhoc/react --dev

Peer Dependencies

  • @unhoc/core

Usage

  1. Import @unhoc/core and @unhoc/react.
import createUnHOC from '@unhoc/core';
import { unHOCMemo } from '@unhoc/react';
  1. Initialize UnHOC function.
const unhoc = createUnHOC({
  plugins: [unHOCMemo()],
});
  1. 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 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.

API

unHOCMemo()

Initializes an UnHOC plugin to unwrap the memo HOC from react.

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.