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

执行npm test时提示找不到@testing-library/jest-dom/extend-expect模块求助

问题描述

我在为Web应用编写单元测试时,使用了toBeInTheDocument()断言方法,执行npm test命令后终端提示错误:

Cannot find module '@testing-library/jest-dom/extend-expect' from 'jest.setup.js'

相关代码与配置如下:
测试文件(test.tsx)中的代码:

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

expect(screen.getByText('User does not exist.')).toBeInTheDocument()

jest.setup.js文件内容:

require('@testing-library/jest-dom/extend-expect');

jest.config.js中的配置:

setupFilesAfterEnv: ["./jest.setup.js"]

已确认node_modules目录下存在@testing-library/jest-dom包,且测试文件中也导入了该模块,请问该如何解决这个问题?

解决方案
  • 校验版本兼容性:确保@testing-library/jest-dom的版本与你使用的Jest、@testing-library/react版本匹配。比如Jest 28及以上版本需要搭配@testing-library/jest-dom v5.16+。可以执行npm list @testing-library/jest-dom查看当前版本,若不兼容则重新安装适配版本:npm install @testing-library/jest-dom@对应版本 --save-dev
  • 确认配置文件路径:检查jest.config.js中setupFilesAfterEnv指定的jest.setup.js路径是否正确。如果文件不在项目根目录,需调整为对应相对路径;Windows系统注意路径分隔符问题,建议使用正斜杠。
  • 确保Jest读取到正确配置:若使用Create React App等脚手架,默认会读取src/setupTests.js作为配置文件,若你自定义了jest.setup.js,需确认Jest能加载到该配置。可以尝试将配置内容移到src/setupTests.js,或在package.json的jest字段中明确指定配置文件路径。
  • 重装依赖清除缓存:执行npm cache clean --force清除npm缓存,删除node_modules和package-lock.json文件,再重新运行npm install,确保依赖完整安装。
  • 匹配模块导入方式:如果项目配置为ES模块(比如package.json中设置了"type": "module"),jest.setup.js需使用import替代require:import '@testing-library/jest-dom/extend-expect';;若使用CommonJS模块,确保package.json中未设置"type": "module",避免解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 03:50:07