@edx/react-unit-test-utils

中文文档
4.0.0发布于 2025/03/28AGPL-3.0CommonJS近 30 天下载 3065

React toolkit for writing and testing react components

此软件包已被标记为弃用

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

原始使用文档
文档目录7 节
  1. Utilities
  2. shallow - Shallow Renderer
  3. mockComponents - Component library mocking utility
  4. useKeyedState and mockUseKeyedState - React state hook wrap…
  5. getEffect - React useEffect hook testing utility method.
  6. formatMessage - i18n mocking method
  7. StrictDict and keyStore - Strict dictionary for keystore re…

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;

版本与发布记录

@edx/react-unit-test-utils 共发布 27 个版本,首次发布于 2023/06/16;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.0.0latest2025/03/281.6 年前
3.1.02025/03/181.7 年前
2.1.12024/05/162 年前
3.0.02024/05/162 年前
2.1.02024/05/152 年前
2.0.02024/01/312 年前

关于 @edx/react-unit-test-utils 的常见问题

@edx/react-unit-test-utils 是什么?

React toolkit for writing and testing react components注意:该包已被作者标记为弃用——Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

如何安装 @edx/react-unit-test-utils?

在项目目录运行 npm install @edx/react-unit-test-utils,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.0.0)、@openedx/paragon(^22.0.0 || ^23.0.0)、@edx/frontend-platform(^8.3.1)、@openedx/frontend-build(^14.3.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@edx/react-unit-test-utils 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/edx__react-unit-test-utils 是否存在。

@edx/react-unit-test-utils 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@edx/react-unit-test-utils 可以商用吗?

@edx/react-unit-test-utils 使用 AGPL-3.0 许可。最严格的 Copyleft:除分发外,通过网络向用户提供基于它的服务也需要开源对应源码。闭源 SaaS 使用前务必评估。以上为概括,不构成法律意见,请以许可原文为准。

@edx/react-unit-test-utils 的下载量有多少?

根据 npm 官方下载统计,@edx/react-unit-test-utils 在 2026/10/13 – 2026/11/11 这 30 天内被下载 3,065 次,日均约 102 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@edx/react-unit-test-utils 还在维护吗?

最新版本 4.0.0 发布于 2025/03/28(1.6 年前);至今共发布 27 个版本,其中过去 12 个月发布了 0 个;首次发布于 2023/06/16。作者已将其标记为弃用,新项目建议寻找替代方案。