# @edx/react-unit-test-utils 中文文档

规范地址：https://npmcn.com/package/%40edx/react-unit-test-utils/

版本：4\.0\.0
npm 元数据更新时间：2026-07-10T14:29:59.785Z
中文译文更新时间：2026-11-13T07:59:59.195Z
软件包许可：AGPL-3\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40edx/react-unit-test-utils
原文对照：https://npmcn.com/package/%40edx/react-unit-test-utils/?lang=original
项目主页：https://github.com/openedx/react-unit-test-utils#README
源码仓库：https://github.com/openedx/react-unit-test-utils

弃用说明：Package no longer supported\. Contact Support at https://www\.npmjs\.com/support for more info\.

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：155 kB，36 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- 运行依赖：10 个
- 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
- 首次发布：2023-06-16T15:09:54.852Z
- 最新版本发布：2025-03-28T11:59:13.327Z
- 近 30 天下载量：3065（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：27（近 12 个月 0 个）

## 中文简介

用于写作和测试的反应工具包

## 安装

```sh
npm install @edx/react-unit-test-utils
```

也可以使用：`pnpm add @edx/react-unit-test-utils`、`yarn add @edx/react-unit-test-utils`、`bun add @edx/react-unit-test-utils`

## README

# 反应- 单位- 测试- 使用

用于维护工具的库,以允许简单的单位测试 React apps.

这个库的目的是支持针对反应应用的测试模式,这些应用侧重于孤立的单位测试和组件快照. 它提供了一种与Enzyme的相类似浅浅的渲染器,由Ezyme所建 `react-test-renderer`,以及一些公用事业,重点是为反应单位测试生态系统提供支持

## 公用事业

### `shallow` - 浅色渲染器

提供特定反应成分的浅度渲染.

#### 使用量

导入渲染器

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

模拟局部组件以进行浅渲染

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

使用 paragon 的模拟组件库 `mockComponents` 函数(见下文).

生成渲染元素

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

验证快照

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

检查了组件道具和儿童.

```js
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` - 组件库模拟工具

组件库用于模拟许多复杂组件的进口图书馆.

#### 使用量

```js
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` 财务报告和审定财务报表 `mockUseKeyedState` - 反应状态钩包装和测试工具

这是测试使用状态钩子反应的一对方法,否则直接测试会有些问题.

#### 使用量

定义用于检查状态密钥的密钥;

```js
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);
};
```

测试时, 在测试之外初始化模拟状态工具

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

对于使用这些状态钩子的钩子,首先为该测试而嘲笑状态对象,再测试初始化参数.

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

set State 对象包含每个状态密钥的拼接函数. 访问设置状态对象以验证更改和跟踪效果/调用 .

```js
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` - 反应使用效钩测试方法.

基于一个先决条件值列表的简单工具来抓取使用效果调用 .

#### 使用量

```js
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 嘲弄方法

I18n 库的简单模拟工具.

#### 使用量

模拟反应- intl 或 @ edx/ frontend- platform/ i18n (最好在 setupTest.js中)

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

导入以校验浅度.

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

### `StrictDict` 财务报告和审定财务报表 `keyStore` - 键盘参考的严格词典

定义使用无效密钥调用时的投诉对象 。 用于在使用定义模块时,将无效的密钥作为错误行为处理(例如使用对象作为密钥存储)。 主要是这种方法可以避免在javascript代码和测试中使用"魔法弦".

#### 使用量

将对象装入严格命令中, 如果调用无效的密钥, 则会引发错误 .

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

使用情况 `keyStore` 从对象或严格命令中快速抓取密钥作为严格命令本身.

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

## 常见问题

### @edx/react-unit-test-utils 是什么？

用于写作和测试的反应工具包注意：该包已被作者标记为弃用——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。作者已将其标记为弃用，新项目建议寻找替代方案。

