【问题标题】:Angular Type Definitions for Unit Tests Not Recognized by VSCodeVSCode 无法识别的单元测试的 Angular 类型定义
【发布时间】:2026-02-01 13:45:01
【问题描述】:

问题

我有一个 Angular 9 应用程序,并且刚刚向组件添加了一个小单元测试。但是 VSCode 无法识别 describebeforeEachit 等类型。虽然我有一个tsconfig.spec.json 文件,其中jasmine 在其types 定义中:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": ["jasmine", "node", "jest"]
  },
  "files": ["src/test.ts", "src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

我得到的实际错误如下:

Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.ts(2582)

我尝试过的(但没有用)

  1. 通过yarn add -D @types/jasmine重新安装@types/jasmine
  2. jasmine 添加到typestsconfig.json
  3. tsconfig.spec.json 中删除types 定义
  4. 重新安装我项目的所有依赖项
  5. jasmine 添加到我的monorepo 根目录中tsconfig.jsontypes

自己试试

如果你想仔细看看,你可以自己尝试一下

git clone https://github.com/flolu/cents-ideas
git checkout 45bda5235f832ab801d6439d0179dd6c0e76c4cc

那么/services/client/src/app/hello-world/hello-world.component.spec.ts就是有错误的文件

旁注:测试通过了,所以只是VSCode找不到类型的问题。

【问题讨论】:

    标签: angular typescript unit-testing visual-studio-code jasmine


    【解决方案1】:

    我的 tsconfig.spec.json 没问题。只需从

    修复我的 tsconfig.json 中的typeRoots 路径
    "typeRoots": ["node_modules/@types"]
    

    "typeRoots": ["../../node_modules/@types"]
    

    因为在我的 monorepo 中,我只有项目根目录下的 node_modules 文件夹。

    【讨论】:

      【解决方案2】:

      请尝试导入

        import {} from 'jasmine';
      

      【讨论】:

        最近更新 更多