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

@edx/react-unit-test-utils

v2.1.1

Published

React toolkit for writing and testing react components

Downloads

6,530

Readme

react-unit-test-utils

Library for maintaining tools to allow simple unit testing of React apps.

The purpose of this library is to support testing patterns for react apps that focus on isolated unit tests and component snapshots. It provides a shallow renderer similar to Enzyme's, build from react-test-renderer, as well as a number of utilities focused on providing support for a react unit-testing ecosystem

Utilities

shallow - Shallow Renderer

Provides a shallow render of a given react component.

Usage

import renderer

import { shallow } from '@edx/react-unit-test-utils';

Mock local components for shallow rendering

jest.mock('./LocalComponent', () => 'LocalComponent');

Mock used component libraries (such as paragon) using provide mockComponents utility (see below).

Generate render element

const el = shallow(<MyComponent {...props} />);

Validate snapshots

expect(el.snapshot).toMatchSnapshot();
expect(el.instance.findByType(LocalComponent)[0].snapshot).toMatchSnapshot();

Inspect rendered component props and children.

const localChild = el.instance.findByType(LocalComponent)[0];
const localDiv = el.instance.findByType('div')[0];
const localTestEl = el.instance.findByType('my-test-id')[0];
// returned object is of the shape { props, type, children }
expect(localChild.props.label).toEqual(myLabel);
expect(localDiv.children[0].type).toEqual('h1');
expect(localDiv.children[0].matches(<h1>My Header</h1>)).toEqual(true);

mockComponents - Component library mocking utility

Component library mocking utility intended for imported libraries of many complex components to be mocked.

Usage

jest.mock('@openedx/paragon', () => jest.requireActual('@edx/react-unit-test-utils').mockComponents({
  Button: 'Button',
  Icon: 'Icon',
  Form: {
    Group: 'Form.Group',
    Control: 'Form.Control',
  },
}));

// Provides mocks for <Button>, <Icon>, <Form>, <Form.Group>, and <Form.Control> with appropriate mocks to appear legibly in the snapshot.

useKeyedState and mockUseKeyedState - React state hook wrapper and testing utility

This is a pair of methods to test react useState hooks, which are otherwise somewhat problematic to test directly.

Usage

Define a keystore (for checking against) of state keys;

import { useKeyedState, StrictDict } from '@edx/react-unit-test-utils';
const state = StrictDict({
  field1: 'field1',
  field2: 'field2',
  field3: 'field3',
]);
// when initializing, use a state key as the first argument to make the calls uniquely identifiable.
const useMyComponentData = () => {
  const [field1, setField1] = useKeyedState(stateKeys.field1, initialValue);
};

When testing, initialize mock state utility outside of your tests

import { mockUseKeyedState } from '@edx/react-unit-test-utils';
import * as hooks from './hooks';
const state = mockUseState(hooks.stateKeys);

For hooks that use these state hooks, first mock the state object for that test, and then test initialization arguments.

state.mock();
const out = myHook();
state.expectInitializedWith(state.keys.field1, initialValue);

setState object contains jest functions for each state key. Access setState object to validate changes and track effects/callbacks.

state.mock();
const out = myHook();
expect(out.setField1).toEqual(state.setState.field1);
out.handleClick(); // out.handleClick = () => { setField2(null); }
expect(state.setField.field2).toHaveBeenCalledWith(null);

getEffect - React useEffect hook testing utility method.

Simple utility for grabbing useEffect calls based on a list of prerequisite values.

Usage

import React from 'react';
import { getEffects } from '@edx/react-unit-test-utils';

jest.mock('react', () => ({
  ...jest.requireActual('react'),
  useEffect: jest.fn(),
}));

const useMyHook = ({ val0, val1, method1 }) => {
  useEffect(() => {
    method1(val0);
  }, []);
  useEffect(() => {
    method1(val1);
  }, [val1, method1]);
};

describe('useMyHook', () => {
  describe('behavior', () => {
    const val0 = 'initial-value';
    const val1 = 'test-value';
    const method1 = jest.fn();
    beforeEach(() => { jest.clearAllMocks(); });
    it('calls method1 with val0 on initial load', () => {
      useMyHook({ val0, val1, method1 });
      const cb = getEffect([], React)[0];
      cb();
      expect(method1).toHaveBeenCalledWith(val0);
    });
    it('calls method1 with val1 when either changes', () => {
      useMyHook({ val0, val1, method1 });
      const cb = getEffect([val1, method1], React)[0];
      cb();
      expect(method1).toHaveBeenCalledWith(val1);
    });
  });
});

formatMessage - i18n mocking method

Simple mocking utility for i18n libraries.

Usage

mock react-intl or @edx/frontend-platform/i18n (preferably in setupTest.js

jest.mock('@edx/frontend-platform/i18n', () => ({
  formatMessage: jest.requireActual('@edx/react-unit-test-utils').formatMessage,
}));

import for validation against shallow renders.

import { shallow, formatMessage } from '@edx/react-unit-test-utils';
...
expect(el.children[0]).toEqual(formatMessage(myMessage));

StrictDict and keyStore - Strict dictionary for keystore referencing

Defines object that complain when called with invalid keys. useful for when using defined modules, where you want to treat invalid keys as an error behavior (such as when using an object as a key-store). Primarily, this is a method to avoid using "magic strings" in javascript code and tests.

Usage

Wrap an object in StrictDict, and it will raise an error if called with invalid keys.

const selectors = StrictDict({
  validSelector1: () => ({}),
  validSelector2: () => ({}),
});
const selector = selectors.invalidSelector; // raises an error

use keyStore to quickly grab the keys from an object or StrictDict as a StrictDict themselves.

const selectorKeys = keyStore(selectors);
selectorKeys.validSelector1; // 'validSelector1';
selectorKeys.invalidSelector; // raises an error;