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

react-props-history

v3.0.7

Published

Allows props history of a React component to be inspected in tests

Downloads

26

Readme

react-props-history

Build Status npm version David David

Allows props history of a React component to be inspected in tests

Install

npm i react-props-history -D

Example

Consider this PizzaBuilder:

import React, {useState} from 'react';
import Dropdown from "…";

const PizzaBuilder = props => {
  const [status, setStatus] = useState('Hungry');
  const setCrustType = crust => setStatus(`Selected 🍕 crust: ${crust}`);

  return <>
    <div>{status}</div>
    <Dropdown
      onItemSelected={setCrustType}
    />
  </>;
};

To test that the correct crust is shown after an item from Dropdown has been selected, you might be tempted to mock away Dropdown, or use some selectors to drill down the DOM tree, find the dropdown, simulate a click event, find the row with the target crust, simulate a click event, etc. 😨 It may look something like this:

import {render} from 'react-testing-library';
import {Simulate} from 'react-dom/test-utils';

describe('SearchBar', () => {
  it('updates text on Dropdown item selected', () => {
    const {queryByText, container} = render(<PizzaBuilder/>);
    
    const dropdown = container.querySelector('[aria-label="Crust picker"]');
    Simulate.mouseDown(dropdown);
    
    // You probably have something more complicated than :first-of-type
    const thinCrustItem = dropdown.querySelector('li:first-of-type');
    Simulate.mouseDown(thinCrustItem);

    expect(queryByText('Selected 🍕 crust: thin')).toBeTruthy();
  });
});

The noise-to-signal ratio is too damn high. All you want is to assert Selected 🍕 crust: thin exists. But you have to spend 80% of your test doing irrelevant gymnastics to trigger your item-selected handler.
If you decided to swap out Dropdown with RadioGroup, your tests will break immediately.

If you find a component hard to unit test, it’s a strong sign that it’s too tightly-coupled.

A well-composed component should be loosely-coupled, without the need to mock or drill down its children. Let's make PizzaBuilder take CrustSelector as a prop:

import Dropdown from "…";

const PizzaBuilder = ({CrustSelector = Dropdown}) => {
  …
  return <>
    <div>{status}</div>
    <CrustSelector
      onItemSelected={setCrustType}
    />
  </>;
};

It works exactly the same as before, except we now allow CrustSelector to be optionally passed in, while maintaining the simple syntax <PizzaBuilder/> with Dropdown as default.

If you decided to swap out Dropdown with RadioGroup, you can do that easily. Anyone could be a CrustSelector ~if you believe in yourself~, it just needs to implement onItemSelected.

The only link between PizzaBuilder and CrustSelector is onItemSelected.

Loosely-coupled components have minimal knowledge and dependencies on each other.

With react-props-history, we can now pass in a special CrustSelector that lets us trigger onItemSelected in our tests:

import withPropsHistory from 'react-props-history';
import {render} from 'react-testing-library';
import {act} from 'react-dom/test-utils';

describe('SearchBar', () => {
  it('updates text on CrustSelector item selected', () => {
    const DropdownSpy = withPropsHistory();  // or pass an actual Dropdown: withPropsHistory(Dropdown)
    const {queryByText} = render(<PizzaBuilder CrustSelector={DropdownSpy}/>);

    expect(DropdownSpy.propsHistory.length).toEqual(1);
    act(() => DropdownSpy.propsHistory[0].onItemSelected('thin'));
    expect(queryByText('Selected 🍕 crust: thin')).toBeTruthy();
  });
});

No drilling down 50 levels deep to find the dropdown row or simulating any click events.
Just call onItemSelected. That’s the beauty of loosely-coupled components.
Simple. 🍻

API

withPropsHistory(ComponentType) => ComponentType & {propsHistory: Props[]}
Takes an optional input component, returns an enhanced component type with a propsHistory array property.

  • The propsHistory array will be filled with the props after each render.
  • You can trigger functions passed in as props, i.e.
    propsHistory[0].onItemSelected(1, '2', {three: 4}) is equivalent to calling
    prop.onItemSelected(1, '2', {three: 4}) from inside the input component.

Scripts

npm run build

Runs babel and copies TypeScript definitions to /lib.

npm test

Runs relevant unit tests.

npm run test:ci

Runs all unit tests and saves the result in JUnit format.

Continuous Integration (CI)

All commits are tested ✅
TODO: automatically npm publish if all tests pass.
View the Azure Pipeline project: https://dev.azure.com/chuihinwai/react-dispatchable

Dependencies

None, other than react


Alternatively, you can also wrap your component type in jest.fn() if you only use Functional Components