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

修复Jest报错Cannot find name 'describe'的TypeScript问题

Jest测试环境TypeScript报错排查方案

配置项目测试环境时遇到如下TypeScript报错:

Cannot find name 'describe'. Do you need to install type definitions for a test runner?
  • 运行环境:Docker
  • 包管理工具:yarn
  • 依赖安装情况截图:
    依赖安装截图

已尝试多种主流解决方案均未生效,已试过的操作包括:

  • 注释tsconfig.json中的types属性,新建tsconfig.spec.json配置文件
  • 对照常规检查清单逐一排查配置项
  • 在tsconfig.json的types属性中添加@types/jest
  • 新建独立tests测试目录

当前项目目录结构

- src
    - tests
      -- sample.test.ts
- babel.config.js
- jest.config.ts
- tsconfig.json
- package.json

现有配置文件内容

sample.test.ts

describe('utils', () => { // <---------------------- 此处及下方代码行报TypeScript错误
  describe('utils#getMessage()', () => {
    it.todo('should return a message');
  });
});

jest.config.ts

export default {
  clearMocks: true,
  verbose: true,
  preset: 'ts-jest',
  collectCoverage: true,
  collectCoverageFrom: ['src/tests/*.ts', '**/*.ts', '!**/*.d.ts'],
  testEnvironment: 'node',
  testRegex: '(src/tests/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
  moduleFileExtensions: ['ts', 'js', 'json', 'node'],
};

tsconfig.json

{
  "compilerOptions": {
    "module": "esnext",
    "target": "es2017",
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "types": ["@types/jest", "jest", "node"],
    "resolveJsonModule": true,
    "outDir": "./dist",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src", "tests", "src/tests"]
}

tsconfig.spec.json

{
  "compilerOptions": {
    "types": ["@types/jest", "jest", "node"]
  }
}

babel.config.js

module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-react',
    '@babel/preset-typescript',
  ],
};

package.json依赖片段

{
  "dependencies": {
    "@types/jest": "^28.1.3",
    "jest": "26.6.0",
    "ts-jest": "^28.0.5"
  }
}

修复步骤

核心问题是Jest相关依赖大版本不匹配,叠加配置项冗余错误,按以下步骤操作即可解决:

  1. 统一Jest生态依赖版本
    你当前安装的jest@26.6.0和@types/jest@28.x、ts-jest@28.x跨了2个大版本,类型定义、运行接口完全不兼容,这是报错的根本原因。执行以下命令替换为版本匹配的依赖,同时注意所有测试类依赖必须放在devDependencies下,不要放在生产依赖dependencies中:

    yarn remove jest @types/jest ts-jest
    yarn add -D jest@26.6.3 ts-jest@26.5.6 @types/jest@26.0.24
    

    规则提示:jest、ts-jest、@types/jest三个包必须保持大版本号一致,否则会出现类型丢失、运行时异常等各类兼容问题。

  2. 修正tsconfig配置

    • 删除compilerOptions.types数组中冗余的"jest"项:Jest全局类型由@types/jest提供,不需要额外声明jest
    • 清理include中的无效路径:你当前不存在根目录tests文件夹,直接用通配符覆盖src下所有文件即可
    • 修正后相关配置片段如下:
    {
      "compilerOptions": {
        // 其余原有配置保持不变
        "types": ["@types/jest", "node"]
      },
      "include": ["src/**/*"]
    }
    

    如果你要保留独立的tsconfig.spec.json作为测试专用配置,必须在后续jest配置中显式指定该文件路径,否则TS服务默认读取根目录tsconfig,该文件不会生效。

  3. 修正jest.config.ts配置
    你已经使用ts-jest处理TS文件,不需要再通过Babel的TypeScript preset处理测试代码,否则会出现类型识别冲突。调整后的配置如下:

    export default {
      clearMocks: true,
      verbose: true,
      preset: 'ts-jest',
      collectCoverage: true,
      collectCoverageFrom: ['src/**/*.{ts,tsx}', '!**/*.d.ts', '!**/node_modules/**'],
      // 项目是React应用则把testEnvironment改为jsdom,纯Node项目保留node即可
      testEnvironment: 'jsdom',
      testRegex: '.*\\.(test|spec)\\.[jt]sx?$',
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
      transform: {
        '^.+\\.tsx?$': 'ts-jest'
      },
      // 若要使用tsconfig.spec.json,打开下面这段注释
      // globals: {
      //   'ts-jest': {
      //     tsconfig: 'tsconfig.spec.json'
      //   }
      // }
    };
    
  4. 清理缓存重启服务
    在容器内删除node_modules/.cache目录,重启IDE的TypeScript服务即可:VS Code可通过快捷键Ctrl+Shift+P调出命令面板,选择TypeScript: Restart TS Server执行重启。

临时规避方案:如果暂时不想调整依赖版本,可以在测试文件顶部添加三斜线指令显式引入Jest类型,可临时消除报错:

/// <reference types="@types/jest" />
describe('utils', () => {
  // 测试逻辑
});

该方案仅做临时救急使用,不解决根本的版本兼容问题,后续运行测试仍可能出现其他异常。


内容的提问来源于stack exchange,提问作者アリ・ナディム

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 22:39:15