npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

dynamic-hoc

v1.1.2

Published

A utility that wraps a React HOC and produces a HOC with additional methods to swap out the given HOC at runtime.

Downloads

9

Readme

dynamic-hoc

A utility that wraps a React HOC and produces a HOC with additional methods to swap out the given HOC at runtime.

This module provides the ability to wrap any React HOC (such as react-redux.connect or react-router.withRouter) to produce a new HOC. The resultant HOC function has properties that allow you to change the HOC at runtime and re-render the wrapped component.

Why?

The primary purpose of this function is to provide the ability to write unit tests for React components in isolation from data injected by a HOC, which often requires extensive mocking. While the developer can export both the original component and the wrapped component, this technique does not apply if the component’s descendants are wrapped by the HOC. With dynamicHoc, each wrapped component can have its HOC replaced with mock data or functions in the test suite.

This enables developers to test React components as units. This is normally possible by exporting the unwrapped component and testing it in isolation, but the component cannot be fully rendered in a test if it contains child components that are wrapped in HOCs. If the HOC has logic of its own, such as functions mapStateToProps, they can be tested independently with dedicated unit tests, or composed with a utility like reselect, where the selectors have their own dedicated unit tests. See the Example section for an illustration of a typical scenario where a “pure” component’s children are components wrapped in a HOC.

Installation

# npm
npm install dynamic-hoc

# yarn
yarn add dynamic-hoc

Example

Components

import { connect } from 'react-redux'
import React from 'react'
import { dynamicHoc } from 'dynamic-hoc'

const TodoList = ({ todos }) => (
  <ul>
    {todos.map(todo => (
      <li key={todo.id}>
        <TodoContainer todo={todo} />
      </li>
    ))}
  </ul>
)

export const TodoListContainer = dynamicHoc(
  connect(
    state => ({ todos: state.todos }),
    () => ({}),
  ),
)(TodoList)

const Todo = ({ creator, onComplete, todo }) => (
  <div>
    <span>{todo.text}</span>
    <span>Created by {creator.name}</span>
    <button onClick={onComplete}>Complete</button>
  </div>
)

export const TodoContainer = dynamicHoc(
  connect(
    (state, props) => ({
      creator: state.users.find(user => user.id === props.todo.creatorId),
    }),
    (dispatch, props) => ({
      onComplete: () =>
        dispatch({
          type: 'COMPLETE_TODO',
          todo: props.todo,
        }),
    }),
  ),
)(Todo)

Tests

import React from 'react'
import { render } from '@testing-library/react'
import test from 'ava'
import { injectProps } from 'inject-props'

test.afterEach(() => {
  TodoListContainer.resetHoc()
  TodoContainer.resetHoc()
})

test('TodoListContainer', () => {
  const testTodos = [
    { creator: '1', id: '42', text: 'foo' },
    { creator: '2', id: '43', text: 'bar' },
  ]

  const testCreators = {
    '1': { id: '1', name: 'Mary' },
    '2': { id: '2', name: 'Steve' },
  }

  TodoListContainer.replaceHoc(injectProps({ todos: testTodos }))

  TodoContainer.replaceHoc(
    injectProps(props => ({
      creator: testCreators[props.todo.creator],
      onComplete: () => {},
    })),
  )

  const { getByText } = render(<TodoListContainer />)

  getByText('foo')
  getByText('Created by Mary')
  getByText('bar')
  getByText('Created by Steve')
})

API

dynamicHoc(initialHoc): Component => WrapperComponent

|Argument|Type|Description| |:---|:---|:---| |initialHoc|Component => WrapperComponent|Any higher order component factory.| |Component|ReactComponent|The component to wrap.|

The returned wrapper component has additional methods:

WrappedComponent.replaceHoc(hoc): void

Replaces the current HOC, triggering any component instances to re-render.

|Argument|Type|Description| |:---|:---|:---| |hoc|Component => WrapperComponent|Any higher order component factory.|

const MyConnectedComponent = dynamicHoc(withRouter)(MyComponent)

MyConnectedComponent.replaceHoc(
  injectProps({ location: { pathname: '/foo' } }),
)

<MyConnectedComponent x={1} y={2} />
// → <MyComponent x={1} y={2} location={{ pathname: '/foo' }} />

WrappedComponent.resetHoc(): void

Replaces the current HOC with initialHoc, triggering any component instances to re-render.

MyConnectedComponent.resetHoc()

FAQ

What if I don't want to add a test dependency to my production app?

You could export a version of the HOC that only loads dynamic-hoc when in your test environment.

import { connect as reduxConnect } from 'react-redux'

export let connect = reduxConnect

if (process.env.NODE_ENV === 'test') {
  const { dynamicHoc } = require('dynamic-hoc')
  
  connect = (mapStateToProps, mapDispatchToProps, mergeProps, options) =>
    dynamicHoc(reduxConnect(mapStateToProps, mapDispatchToProps, mergeProps, options))
}

Or you could use a test library to mock the dependency.

jest.mock('react-redux', () => {
  const { dynamicHoc } = require('dynamic-hoc')
  const reactRedux = jest.requireActual('react-redux')
  
  const mock = {
    ...reactRedux,
    connect: (mapStateToProps, mapDispatchToProps, mergeProps, options) =>
      dynamicHoc(reactRedux.connect(mapStateToProps, mapDispatchToProps, mergeProps, options)),
  }
  
  return {
    __esModule: true,
    default: reactRedux,
    ...reactRedux,
  }
})

License

MIT