You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级@testing-library/react遇TypeError: prettyFormat.format is not a function错误求助

解决@testing-library/react升级后prettyFormat.format is not a function错误

问题原因

你遇到的错误是版本兼容性冲突:@testing-library/react@13 依赖的 @testing-library/dom 包需要更高版本的 prettyFormat,但当前使用的 Jest@26.6.3 自带的 prettyFormat 版本过低,导致调用 format 方法时触发不存在的报错。

另外,screen.getByText 能正常工作是因为元素找到时不会触发错误格式化逻辑;而 getByTestId 找不到元素(或触发错误输出)时会调用 prettyDOM,进而用到有问题的 prettyFormat,因此报错。

解决方案

1. 升级Jest到兼容版本

@testing-library/react@13 要求 Jest 版本至少为 27.x(你的 Node 14.15.1 支持 Jest 27,Jest 29 需要 Node 16+,推荐升级到27.x系列):

先卸载旧的Jest相关依赖:

npm uninstall jest @types/jest jest-environment-jsdom

再安装兼容版本:

npm install --save-dev jest@^27.5.1 @types/jest@^27.5.2 jest-environment-jsdom@^27.5.1

2. 修复依赖版本冲突

执行命令查看项目中prettyFormat的版本情况,确保没有多版本并存:

npm ls prettyFormat

如果存在多个版本,删除node_modules和package-lock.json,重新执行npm install,让依赖版本统一。

3. 确认@testing-library/jest-dom安装正确

虽然当前错误不是这个导致的,但toBeInTheDocument断言需要依赖@testing-library/jest-dom,请确保已安装:

npm install --save-dev @testing-library/jest-dom

并在测试的setup文件(比如src/setupTests.ts)中添加导入:

import '@testing-library/jest-dom';

内容的提问来源于stack exchange,提问作者Viral Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 14:12:45