【问题标题】:Cannot find name 'describe'. Do you need to install type definitions for a test runner?找不到名称“描述”。您是否需要为测试运行器安装类型定义?
【发布时间】:2019-06-05 22:35:14
【问题描述】:

当将 TypeScript 与 Jest 结合使用时,我的规范会失败并显示如下错误消息:

test/unit/some.spec.ts:1:1 - error TS2582: 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`.
test/unit/some.spec.ts:2:3 - error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
test/unit/some.spec.ts:3:7 - error TS2304: Cannot find name 'expect'.
test/unit/some.spec.ts:7:1 - error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.

类型已安装。

我用:

    "@types/jest": "^23.3.12",
    "jest": "^23.6.0",
    "ts-jest": "^23.10.5",
    "typescript": "^3.1.6"

我使用jest --forceExit --coverage --verbose 运行测试

【问题讨论】:

    标签: typescript jestjs


    【解决方案1】:

    我使用 VSCode 作为我的 IDE,在我的 Angular 项目中,我必须在 tsconfig.json 中注释掉/删除类型,并在 tsconfig.spec.json 中添加 jest。

    tsconfig.json

    {
      "compilerOptions": {
        // "types": []
      }
    }
    

    tsconfig.spec.json

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

    【讨论】:

    • 我还必须从我的 tsconfig 文件中删除“typeRoots”,这显然覆盖了“types”。
    • @Freekwalker -- 删除 typeRoots 为我修复了它
    • 注意:如果您的 tsconfig 中已经定义了 "jest",则只需将 compilerOptions.types 添加到 compilerOptions.types。如果完全省略,该设置的默认行为是包含node_modules/@jest 下的所有类型。我遇到了这个问题,因为我的项目被错误地配置为types: [],但是在完全删除它之后,我得到了正确输入的 Jest 内容。通过按照此解决方案中显示的方式定义它,您将失去在 node_modules/@types 下隐含包含其他类型(这还不错,只是需要注意的副作用)。
    • 我帮助一位同事解决了这个问题;你需要typescompilerOptions下。仅供遇到此问题并碰巧错过此详细信息的其他人
    【解决方案2】:

    这有点棘手,因为您的 IDE(即 VSCode)和 TypeScript 都将 tsconfig.json 用于自己的目的。

    解决初始问题的简单清单:

    (用于 TypeScript 和 Jest)

    1. 确保您已安装 @types/jest@types/node
    2. 确保您已在tsconfig.json 中链接这些类型,以便:types: ["jest", "node"]
    3. 确保您没有从tsconfig.json 配置中的excluded 属性中排除您的测试或测试目录

    对转译的副作用

    如果您使用 tsc 或任何依赖于 tsconfig.json 的自定义模块从 TypeScript 转换为 JavaScript,那么您可能会注意到在这种情况下您的测试也会被转换(您将在构建中看到它们的 .js 对应关系目录)。

    但是,在大多数情况下,您将有:

    1. tsconfig.prod.json 与覆盖默认配置的配置分开。有许多设置,例如 inlineSourcesourceMapsinlineSourceMaps,您可能也想禁用这些设置,然后使用 tsc --project tsconfig.prod.json 来构建
    2. 使用特定标志覆盖默认配置的终端(npm/yarn 脚本)命令。示例:npx tsc --inlineSourceMap false --declarationMap false --inlineSources false --sourceMap false。此时,您可以使用--excludeFiles--excludeDirectories 标志根据documentation 从构建中排除您的测试。

    替代方法是使用 rimraf 之类的包,并在构建过程中删除不必要的文件。可能没有覆盖配置那么复杂,并且作为构建步骤更易于维护。在这种情况下,您可以使用命令:yarn rimraf build/**/*.test.js

    【讨论】:

    • 我发现如果我从tsconfig.json的“excluded”属性中删除“*/.spec.ts”,然后VS Code中的红色下划线.spec 文件中的“描述”消失了,但是这些文件现在作为包的一部分输出到 /lib 文件夹中。似乎没有办法从包中排除 .spec 文件,但包含部分文件以消除“描述”错误?
    • @Ross 刚刚修改了我的帖子
    • 对我来说,我还需要将“test/”目录添加到我的tsconfig.json 的“include”部分,然后它就可以工作了。这个答案让我想到这可能是需要做的事情。
    • 我认为这是最完整的答案,但是重启VSCode非常重要。就我而言,我没有重新启动,这浪费了我很多时间。
    • @Janiwu Chen,就我而言,关闭并重新打开文件就足够了,无需重新启动(Ubuntu 上的 VSCode),但公平的建议!。
    【解决方案3】:

    这对我有用:

    import '@types/jest';
    

    【讨论】:

    • 不错的快速修复!
    【解决方案4】:

    以上都没有解决我的问题。 我必须将"@types/jest" 添加到tsconfig.json 文件中的types 数组中。

    【讨论】:

    • 谢谢,它适用于我使用 typescript 和 typescript-eslint 的项目
    • 谢谢!顺便说一句,在我的情况下,它是一个包含多个包的单一存储库,这个答案是唯一解决问题的答案。我在根 tsconfig.json 上添加了它
    【解决方案5】:

    在摆弄tsconfig.json 一段时间后,我终于想到,评论"types": [], 会起作用。

    配置失败(之前)

    // tsconfig.json
    {
      "compilerOptions": {
        "types": []
      }
    }
    

    工作配置

    // tsconfig.json
    {
      "compilerOptions": {
        // "types": []
      }
    }
    

    【讨论】:

    • 或在类型中添加笑话:"types": ["jest"]
    • @Madeo 您是否将 @types/jest 添加到 package.json 中的开发依赖项中?
    • 是的,我已经添加了,另外我已经将它们导入到我的测试文件中。我玩过excludestypes,但没有。一切运行良好,只是来自编译器的抱怨 =(
    • 2019年11月作品
    【解决方案6】:

    我能够解决此问题的唯一方法是将tests/ 文件夹添加到tsconfig.json 文件中的“包含”:

    "include": [
      "src/**/*.ts",
      "tests/*.ts"
    ] 
    

    对于那些也有eslint 投诉的人,您需要将jest 添加到您的.eslintrc.json 文件中:

    "env": {
      "es2020": true,
      "node": true,
      "jest": true
    }
    

    【讨论】:

    • 谢谢,添加到 include 也是这里唯一有帮助的东西!
    【解决方案7】:

    你必须在你的测试文件中导入 jest:

    import 'jest';
    

    另一种解决方法是在您的 tsconfig.json 文件中添加:

       "compilerOptions": {
         "types": [ "node", "jest" ],
         "moduleResolution": "node"
       }
    

    如果您使用的是 tslint,问题可能是 tsconfig.json 末尾的一个不必要的逗号,例如:

    {
      "compileOnSave": true,
      "include": [
        "src"
      ],  // remove this comma
    }
    

    【讨论】:

    • 是的,额外的逗号是我的问题。谢谢
    • import 'jest' 有帮助,我正在尝试使用自定义 tsconfig.json 位置
    【解决方案8】:

    您需要在 tsconfig.json 中包含您的测试路径。

    示例:假设您将路径命名为 tests/ 并将其放在项目根目录中,您需要在 tsconfig 的“include”参数中指定以查找睾丸文件:

    1. 转至:tsconfig.json
    2. 添加:
    "include": [
        "tests/*.<file_test_extension>",
    ],
    
    • &lt;file_test_extension&gt;:ts | js |等

    希望能帮到你

    【讨论】:

    • 但这将开始将测试文件复制到将被部署的 lib 文件夹
    【解决方案9】:

    以下配置对我有用。我将node_modules/@types 添加到typeRoots

    {
      "compilerOptions": {
        // ...rest of my settings
        "typeRoots": ["node_modules/@types"],
        "types": ["jest", "node"]
      }
    }
    

    【讨论】:

    • 这对我有用,我已将 node_modules/@types 添加到 typeRoots 并从 tsconfig 中删除了 types 字段
    【解决方案10】:

    就我而言(与代码、create-react-app、yarn 工作区、jest@26、@types/jest、"types": ["node", "jest"] 存在于tsconfig.json 中)测试运行正常,但 IDE所有describeit用红色下划线。在我尝试了很长时间后重新加载 VS Code 窗口之前没有任何帮助?‍♂️?

    【讨论】:

    • 是的,我完全关闭并重新打开了 VS Code,然后它工作了 =) 谢谢
    【解决方案11】:

    你可以在测试文件夹__tests__中有一个单独的tsconfig.json

    {
        "extends": "../tsconfig.json",
        "compilerOptions": {
            "baseUrl": "./",
            "outDir": "../build",
            "noEmit": true,
            "rootDir": "../",
        },
        "exclude": ["node_modules"],
    }
    

    它扩展了根文件夹中的那个:

    {
      "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "moduleResolution": "node",
        "outDir": "./lib",
        "rootDir": "./src",
        "strict": true,
        "noImplicitAny": true,
        "esModuleInterop": true,
      },
      "exclude": ["node_modules", "**/*.test.ts", "__tests__"]
    }
    

    通过这种方式,您的测试文件仍然会从公共构建中排除,但仍然可以共享所有常用选项。

    如果您使用includes 代替excludes 或与excludes 结合使用,请确保在您的扩展程序中也使用它,例如:

    tsconfig.json
    
    {
      "includes": ["src"],
      ...
    }
    
    tests/tsconfig.json
    
    {
      "extends": "../tsconfig.json"
      "includes": ["../"]
    }
    

    这不会改变你的构建文件夹中包含的内容,但它会让 VSCode 找到你的笑话类型

    【讨论】:

      【解决方案12】:

      您需要在 tsconfig.json 中包含您的测试路径。

      我通过在我的项目根目录中添加tsconfig.jsontsconfig.build.json 解决了这个问题。 tsconfig.json 包含所有选项,包括

      "include": ["src/**/*", "test/**/*"],
      

      tsconfig.build.json:

      {
        "extends": "./tsconfig.json",
        "include": ["src/**/*"]
      }
      

      然后在package.json(干净的脚本可选):

      "scripts": {
        "clean": "rm -rf dist",
        "build": "npm run clean && tsc --build tsconfig.prod.json,
        ...
      }
      

      【讨论】:

      • 这对我来说是解决办法。我在我的 tsconfig.json 文件中排除了测试,因为我不希望它们编译到 dist 文件夹。我最终创建了一个单独的 tsconfig.build.json,其中包含排除项,但将其包含在 tsconfig.json 中,现在警告消失了,并且测试从构建中排除。谢谢!
      【解决方案13】:

      @Greg Woz 是最完整的答案,就我而言,出于某种原因,最初的tsconfig.json 文件包含"exclude": ["node_modules", "**/__tests__/*"],这是根本原因。删除"**/__tests__/*" 后。并确保它还包括:"types": ["jest"]。它有效。

      在配置更改后重新启动 Vscode 也很重要。在不重新启动它的情况下尝试所有不同的方式会浪费我数小时的时间。

      【讨论】:

      • 哦,天哪,谢谢您提到您需要重新启动 VSCODE!这一直是我的问题。我花了一个小时试图更改我的配置无济于事,不知道需要重启 vscode。
      • 谢谢男人。 :) .... f**** restart 让我从上面的答案中完成所有步骤:P
      【解决方案14】:

      对于 lerna monorepo 用户

      我正在运行一个 lerna monorepo,这是我必须做的修复它:

      1. 确保"@types/jest" 位于根包以及packages/ 目录中单个包的package.json 的devDependencies 中,并且您已运行lerna bootstrap 以安装/链接@987654324 中的这些包@目录
      2. 确保 "types": ["node", "jest"] 片段位于您的根 tsconfig.json 中。
      3. 我将import 'jest'; 添加到我的个人 *.test.ts 文件的顶部。

      【讨论】:

      • 我是 lerna monorepo 用户,我同意此消息
      • 我是 lerna monorepo 用户,我绝对拒绝在我的测试文件中添加“import jest”。幸运的是,前两个步骤似乎是我所需要的。
      【解决方案15】:

      另一件可能出错的事情是,如果您在项目上方的父目录中打开了 vscode。这发生在我身上,因为我们使用的是 Visual Studio 解决方案,而且我打开了整个解决方案,而不仅仅是项目。

      简单地说,确保 vscode 对你的项目的根目录是开放的。

      【讨论】:

        【解决方案16】:

        就我而言,问题出在一个特定的文件中。我没有发现问题本身,但通过在文件的导入中添加 import {} from 'jest' 解决了它。

        开玩笑的问题跟踪器或 SO 或其他没有帮助的方法。只是一些疯狂的解决方法修复了一些疯狂的错误?‍♂️

        是的,我当然在 package.json 中添加了最新的 jestts-jest@types/jest

        【讨论】:

        • 如果你要导入一些东西,那么最好从 jest 导入“describe”和“it”函数或者你需要的任何东西
        • 我使用了 mocha,但遇到了同样的问题,VSCode 抱怨 describe 和其他类型丢失,即使 .eslintrc 用 mocha 覆盖 env。在我的测试目录中添加一个文件只做import { describe, before, it } from 'mocha' 解决了VSCode中的错误。
        【解决方案17】:

        上述解决方案都没有帮助我

        我正在使用:

        • 角 11
        • 开玩笑
        • 卸载了与 Jasmine/Karma 相关的任何内容
        • .spec 文件与组件在同一文件夹中(自动生成自 ng g


        对我有用的是将exclude 添加到 tsconfig.app.json(不是 tsconfig.json)以在提供应用程序时忽略所有规范文件。

        tsconfig.app.json

        "exclude": [
            "**/*.spec.ts"
        ]
        

        ng snpm test 现在对我有用。

        【讨论】:

          【解决方案18】:

          @Freewalker 在 cmets 中建议的解决方案很容易被忽略。从 tsconfig 文件中删除“typeRoots”,这显然覆盖了“types” - 解决了这个问题。

          【讨论】:

            【解决方案19】:

            什么对我有用。

            这发生在 VS Code 中。您需要运行npm i --save-dev @types/jest,并在您的

            tsconfig.json

            你需要放置

            "jest""compilerOptions"下的类型中

            喜欢

            "types": ["gapi", "gapi.auth2", "jest"],

            你就完成了。

            【讨论】:

              【解决方案20】:

              我正在使用 mochachaichai-http 来测试 Node Express.js 项目。我之前没有在compilerOptions 中使用types,但是在tsconfig.json 中添加以下设置使它对我有用:

              {
                "compilerOptions": {
                  // ...rest of my settings
                  "types": ["mocha", "chai", "chai-http"]
                }
              }
              

              【讨论】:

                【解决方案21】:

                你需要在你的项目中安装ts-jest依赖吗

                yarn add ts-jest -D
                

                在您的jest.config.ts 文件中,您需要将包含preset: undefined 的行设置为preset: 'ts-jest'

                // A preset that is used as a base for Jest's configuration
                preset: 'ts-jest',
                

                【讨论】:

                  【解决方案22】:

                  可能有多种原因:

                  1. 如果未安装@types/jest,请尝试安装它并在tsconfig.json 中定义类型,例如 "typeRoots": ["node_modules/@types/", "./src/@types/", ".src/**/@types/"]

                  2. VS 代码问题:尝试在项目目录中打开 vs 代码,而不是在其父目录中打开它。

                  【讨论】:

                    【解决方案23】:
                    import {} from 'jasmine';
                    

                    将上述行添加到代码中。希望这能解决问题。

                    【讨论】:

                      【解决方案24】:

                      我用npm i -D ts-jest 安装了ts-jest 并且错误消失了

                      【讨论】:

                        【解决方案25】:

                        我错过了tsconfig.json,我所要做的就是运行tsc --init,vs 代码不再抱怨“描述”:

                        {
                          "compilerOptions": {
                            /* Visit https://aka.ms/tsconfig.json to read more about this file */
                        
                            /* Basic Options */
                            // "incremental": true,                   /* Enable incremental compilation */
                            "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
                            "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
                            // "lib": [],                             /* Specify library files to be included in the compilation. */
                            // "allowJs": true,                       /* Allow javascript files to be compiled. */
                            // "checkJs": true,                       /* Report errors in .js files. */
                            // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
                            // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
                            // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
                            // "sourceMap": true,                     /* Generates corresponding '.map' file. */
                            // "outFile": "./",                       /* Concatenate and emit output to single file. */
                            // "outDir": "./",                        /* Redirect output structure to the directory. */
                            // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
                            // "composite": true,                     /* Enable project compilation */
                            // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
                            // "removeComments": true,                /* Do not emit comments to output. */
                            // "noEmit": true,                        /* Do not emit outputs. */
                            // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
                            // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
                            // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
                        
                            /* Strict Type-Checking Options */
                            "strict": true,                           /* Enable all strict type-checking options. */
                            // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
                            // "strictNullChecks": true,              /* Enable strict null checks. */
                            // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
                            // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
                            // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
                            // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
                            // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
                        
                            /* Additional Checks */
                            // "noUnusedLocals": true,                /* Report errors on unused locals. */
                            // "noUnusedParameters": true,            /* Report errors on unused parameters. */
                            // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
                            // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
                            // "noUncheckedIndexedAccess": true,      /* Include 'undefined' in index signature results */
                        
                            /* Module Resolution Options */
                            // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
                            // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
                            // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
                            // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
                            // "typeRoots": [],                       /* List of folders to include type definitions from. */
                            // "types": [],                           /* Type declaration files to be included in compilation. */
                            // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
                            "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
                            // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
                            // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */
                        
                            /* Source Map Options */
                            // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
                            // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
                            // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
                            // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
                        
                            /* Experimental Options */
                            // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
                            // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
                        
                            /* Advanced Options */
                            "skipLibCheck": true,                     /* Skip type checking of declaration files. */
                            "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
                          }
                        }
                        
                        

                        【讨论】:

                          【解决方案26】:

                          我发现类似的问题是由@types/jestjest 之间的版本号不匹配引起的

                          【讨论】:

                            【解决方案27】:

                            我今天在整理 POC 时遇到了这个问题。我正在使用 Protractor 和 Jasmine(而不是 jest 或 mocha)。原来我必须通过 Typescript 实用程序/包实际创建 tsonfig 文件。
                            然后,将“jasmine”和“node”添加到 tsconfig 中的 types 数组中效果很好。

                            这是我遇到的链接:https://howtodoinjava.com/typescript/tsconfig-json/

                            【讨论】:

                              猜你喜欢
                              • 2016-12-25
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2018-05-04
                              • 1970-01-01
                              • 2023-03-22
                              • 2019-06-11
                              • 2018-06-18
                              相关资源
                              最近更新 更多