关于 react19-test-patterns
面向维护测试套件的开发者,提供 React 19 测试迁移参考,列出已移除的 `react-dom/test-utils` API 的替代方式,并说明如何调整 StrictMode 调用次数断言。
主要功能
- 01更新 `act` 导入
- 02用 `fireEvent` 替换 `Simulate`
- 03将已移除 API 映射到 RTL
- 04调整 StrictMode 效果调用次数
- 05处理异步 `act` 警告
适用场景
- 01将测试从 React 18 迁移到 React 19
- 02替换弃用的 `react-dom/test-utils` 用法
- 03更新 StrictMode 下的效果调用断言
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ github/ awesome-copilot --skill react19-test-patterns安装后在 Claude Code 中输入/react19-test-patterns确认已加载。
详细介绍
React 19 测试迁移模式
React 19 要求的所有测试文件迁移的参考。
优先级顺序
按此顺序修复测试文件;每一层都依赖于上一层:
act导入 最先修复,它能解除其他所有问题的阻塞Simulate→fireEvent紧接 act 之后修复- 完整的 react-dom/test-utils 清理 移除剩余导入
- StrictMode 调用次数 实测实际值,不要猜测
- 异步 act 包装 用于剩余的 "not wrapped in act" 警告
- 自定义 render 辅助函数 每个代码库验证一次,而非每个测试验证一次
1. act() 导入修复
// Before REMOVED in React 19:
import { act } from 'react-dom/test-utils';
// After:
import { act } from 'react';
如果与其他 test-utils 导入混用:
// Before:
import { act, Simulate, renderIntoDocument } from 'react-dom/test-utils';
// After split the imports:
import { act } from 'react';
import { fireEvent, render } from '@testing-library/react'; // replaces Simulate + renderIntoDocument
2. Simulate → fireEvent
// Before Simulate REMOVED in React 19:
import { Simulate } from 'react-dom/test-utils';
Simulate.click(element);
Simulate.change(input, { target: { value: 'hello' } });
Simulate.submit(form);
Simulate.keyDown(element, { key: 'Enter', keyCode: 13 });
// After:
import { fireEvent } from '@testing-library/react';
fireEvent.click(element);
fireEvent.change(input, { target: { value: 'hello' } });
fireEvent.submit(form);
fireEvent.keyDown(element, { key: 'Enter', keyCode: 13 });
3. react-dom/test-utils 完整 API 映射
| 旧(react-dom/test-utils) | 新位置 |
|---|---|
act | import { act } from 'react' |
Simulate | 来自 @testing-library/react 的 fireEvent |
renderIntoDocument | 来自 @testing-library/react 的 render |
findRenderedDOMComponentWithTag | 来自 RTL 的 getByRole、getByTestId |
findRenderedDOMComponentWithClass | getByRole 或 container.querySelector |
scryRenderedDOMComponentsWithTag | 来自 RTL 的 getAllByRole |
isElement、isCompositeComponent | 移除 使用 RTL 时不需要 |
isDOMComponent | 移除 |
4. StrictMode 调用次数修复
React 19 的 StrictMode 在开发环境中不再对 useEffect 进行双重调用。统计 effect 调用次数的 spy 断言必须更新。
策略 始终实测,绝不猜测:
# Run the failing test, read the actual count from the error:
npm test -- --watchAll=false --testPathPattern="[filename]" --forceExit 2>&1 | grep -E "Expected|Received"
// Before (React 18 StrictMode effects ran twice):
expect(mockFn).toHaveBeenCalledTimes(2); // 1 call × 2 (strict double-invoke)
// After (React 19 StrictMode effects run once):
expect(mockFn).toHaveBeenCalledTimes(1);
// Render-phase calls (component body) still double-invoked in React 19 StrictMode:
expect(renderSpy).toHaveBeenCalledTimes(2); // stays at 2 for render body calls
评论
支持 Markdown