在使用 Jest 结合 @testing-library 进行前端测试时,经常会遇到以下类型错误:
describe("Card", () => {  it("should render the name", () => {    const { getByText } = render(<Card pet={petMock} />);    expect(getByText("name")).toBeInTheDocument();  });});当运行 npm test 时,测试用例可以正常通过,但是编辑器会提示以下错误,非常影响了我的心情。
Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'错误原因分析
toBeInTheDocument 是 @testing-library/jest-dom 库提供的扩展匹配器,未在测试文件中显式引入或未通过 Jest 配置自动加载。TypeScript 编译器无法识别未声明的匹配器类型,导致类型检查失败。
解决方案
接下来按步骤来解决这个问题。
- 安装必要依赖
首先需要确保项目中安装了 @testing-library/jest-dom:
# 使用 npmnpm install @testing-library/jest-dom -D# 或使用 pnpmpnpm add @testing-library/jest-dom -D- 配置 tsconfig.json 的 types 字段
在项目的 tsconfig.json 文件中,添加 @testing-library/jest-dom 到 types 字段中:
{  "compilerOptions": {    "types": ["@testing-library/jest-dom"]  }}接下来在根目录创建一个 setupTests.ts 文件,用于引入 @testing-library/jest-dom 匹配器:
import "@testing-library/jest-dom";然后在 Jest 配置文件中,如 jest.config.js 或 package.json 中的 jest 字段中添加 setupFilesAfterEnv 配置项,指定 setupTests.ts 文件的路径:
{  "jest": {    "setupFilesAfterEnv": ["<rootDir>/setupTests.ts"]  }}如果你的 jest-dom 版本是 5.x,那么你需要在 setupTests.ts 文件中引入 @testing-library/jest-dom/extend-expect:
import "@testing-library/jest-dom/extend-expect";通过以上步骤,就可以解决 Property 'toBeInTheDocument' does not exist on type 'Matchers<any>' 的错误提示了。如果你的问题无法解决,欢迎在评论区留言,我会尽力帮助你解决。
 
     
               
              