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

使用Create React App+TypeScript创建项目时遇expect及类型错误

解决React TypeScript项目中Jest测试的类型错误

针对你用yarn create react-app <app-name> --template typescript创建项目后遇到的两个测试类型错误,以下是永久解决方法:

错误原因

  1. Cannot find name "expect":TypeScript未识别Jest的全局变量类型
  2. TS2339: Property 'toBeInTheDocument' does not exist...:未加载@testing-library/jest-dom提供的匹配器类型

解决方案

步骤1:确保依赖安装完整

如果项目中缺少@testing-library/jest-dom,执行以下命令安装:

yarn add -D @testing-library/jest-dom

步骤2:配置TypeScript识别Jest和jest-dom类型

有两种可选方式:

方式A:修改tsconfig.json

在compilerOptions中添加types字段,指定需要加载的类型库:

{
  "compilerOptions": {
    // 保留原有配置...
    "types": ["jest", "@testing-library/jest-dom"]
  }
}

方式B:创建测试初始化文件

在src目录下新建setupTests.ts文件,添加以下内容:

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

Create React App会自动在运行测试前执行这个文件,从而引入jest-dom的匹配器类型,同时Jest的全局类型也会被自动识别。

步骤3:验证配置

重启TypeScript语言服务(或编辑器),重新运行测试,错误应该会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:42:44