如何测试自定义传参的react-aria-components?遇useContext报错求助
如何为react-aria-library组件编写测试?
我项目里用react-aria-components的组件在本地服务器渲染和功能都正常,但不知道怎么给这些组件写单元/集成/端到端测试。虽然官方已经测试过组件,但我还是想把它们纳入自己的测试流程里。
我写了一个基础测试示例:
import { render, screen } from "@testing-library/react"; import { describe, it, expect } from "vitest"; import { Button } from "react-aria-components"; describe("Button Component", () => { it("renders a regular button", () => { render(<button />); const buttonElement = screen.getByRole("button"); expect(buttonElement).toBeInTheDocument(); }); it("renders a react-aria-button", () => { render(<Button />); }); });
测试环境已经搭好,依赖也都导入了,但运行测试时,原生按钮的测试通过了,react-aria的Button组件测试直接失败,报错信息如下:
TypeError: Cannot read properties of null (reading 'useContext') ❯ Button Component (2) ✓ renders a regular button (passed) × renders a react-aria-button (failed) ... Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app
还没加断言就触发了错误,查了Adobe文档才知道这个库的每个组件都用到了Context Hook,所有组件都会出现这个问题。我是测试新手,求解决办法。
解决步骤
1. 检查React版本一致性
先确认项目中react、react-dom和测试依赖(比如@testing-library/react)的版本是否匹配。在项目根目录执行命令查看版本:
npm list react react-dom @testing-library/react
如果版本不匹配,统一升级或降级到兼容版本,确保react和react-dom版本完全一致,@testing-library/react的版本也适配当前React版本。
2. 排查多份React副本问题
如果项目中存在多份React(比如依赖嵌套安装导致),会触发Hook调用错误。可以通过以下方式解决:
- 在项目根目录的
package.json中添加resolutions字段(npm需配合npm-force-resolutions工具,yarn直接支持),强制所有依赖使用同一版本的React:
{ "resolutions": { "react": "^18.2.0", "react-dom": "^18.2.0" } }
- 执行
npm install或yarn install重新安装依赖,确保所有子依赖使用指定版本的React。
3. 正确包裹React Aria组件
React Aria的部分组件需要在特定的Context Provider下才能正常工作,尝试用ReactAriaProvider包裹组件(如果你的react-aria版本提供这个Provider):
import { ReactAriaProvider } from "react-aria-components"; // 在测试中包裹组件 it("renders a react-aria-button", () => { render( <ReactAriaProvider> <Button>Test Button</Button> </ReactAriaProvider> ); const buttonElement = screen.getByRole("button"); expect(buttonElement).toBeInTheDocument(); });
4. 检查测试环境配置
如果用Vitest,确保vite.config.ts中的测试配置正确,比如使用@vitejs/plugin-react插件,并且设置正确的DOM环境:
import { defineConfig } from 'vitest/config'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], test: { environment: 'jsdom', globals: true, }, });
内容的提问来源于stack exchange,提问作者Domas
相关产品推荐
相关产品推荐

