找不到名称“ description”。是否需要为测试运行程序安装类型定义?

当与 Jest 一起使用 TypeScript 时,我的 specs 会出现以下错误消息:

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进行测试

140187 次浏览

在摆弄了一会儿 tsconfig.json之后,我最终认为注释 "types": [],是可行的。

配置失败(之前)

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

工作配置

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

我使用 Visual Studio Code 作为 IDE 和 Angular 项目中的 IDE,我必须在文件 Tsconfig.json中注释掉/删除类型,并在 Json中添加类型中的“ jest”。

文件 Tsconfig.json

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

文件 Json

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

在我的例子中,问题出现在一个特定的文件中。我没有发现这个问题本身,但是通过将 import {} from 'jest'添加到文件的导入中可以解决这个问题。

没有其他办法从玩笑问题跟踪器,堆栈溢出或什么没有帮助。这只是一些疯狂的错误修复了一些疯狂的变通方法。

是的,我添加了最新的 jestts-jest@types/jest文件 包裹 Json当然。

您需要在文件 Tsconfig.json中包含您的测试路径。

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

  1. 转到: tsconfig.json

  2. 地址:

    "include": [
    "tests/*.<file_test_extension>",
    ],
    

    等等。

这个问题有点棘手,因为 IDE (例如 Visual Studio Code)和 TypeScript 都使用 Tsconfig.json实现自己的目的。

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

(适用于打字机及玩笑)

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

翻译的副作用

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

然而,在大多数情况下,你会有以下两种选择:

  1. 使用覆盖默认值的配置来分离 tsconfig.prod.json。有许多设置,如 inlineSourcesourceMapsinlineSourceMaps,你可能想禁用,然后使用 tsc --project tsconfig.prod.json来建立
  2. 终端(npm/纱线脚本)命令,用特定的标志覆盖默认配置。例子: npx tsc --inlineSourceMap false --declarationMap false --inlineSources false --sourceMap false。此时,可以使用 --excludeFiles--excludeDirectories标志从构建 根据文件中排除测试。

另一种方法是使用类似 Rimraf的软件包,并删除不必要的文件作为构建过程的一部分。与重写配置相比,它可能不那么复杂,并且作为构建步骤更容易维护。在这种情况下,可以使用命令 yarn rimraf build/**/*.test.js

您可以在测试文件夹 __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一起使用,请确保在您的扩展中也使用 includes,例如:

tsconfig.json


{
"includes": ["src"],
...
}


tests/tsconfig.json


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

这不会更改生成文件夹中包含的内容,但是它将允许 VisualStudio 代码查找 Jest 类型。

您必须在测试文件中导入 Jest:

import 'jest';

另一种解决方法是将它添加到 Tsconfig.json文件中:

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

如果您使用的是 TSLint,问题可能是在您的 Tsconfig.json文件的结尾没有必要的逗号,例如:

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

我正在使用 摩卡阿漆chai-http测试 Node.js 快递项目。我之前没有在 compilerOptions中使用 types,但是在 Tsconfig.json文件中添加了以下设置,使它对我有效:

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

我能够解决这个问题的唯一方法是添加 tests/文件夹到 Tsconfig.json文件中的“ include”:

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

对于那些也有 埃斯林特抱怨,你需要添加 开玩笑的到你的 .eslintrc.json文件:

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

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

我通过在项目根目录中使用 tsconfig.jsontsconfig.build.json解决了这个问题

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

返回文章页面

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

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

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

以前的答案都没有解决我的问题。

我必须将 "@types/jest"添加到 Tsconfig.json文件中的 types数组中。

我用 npm i -D ts-jest安装了 ts-jest,错误消失了。

Greg Woz 的 是最完整的答案。对于我的情况,由于某种原因,最初的 Tsconfig.json文件包含 "exclude": ["node_modules", "**/__tests__/*"],这是根本原因。之后我移除了 "**/__tests__/*"。并确保它也包括: "types": ["jest"]。有用。

此外,在配置更改后,重新启动 VisualStudio 代码也很重要。它浪费我数小时的时间尝试所有不同的方式,而不是重新启动它。

对我有效的方法是:

这是在 VisualStudio 代码中发生的。您需要运行 npm i --save-dev @types/jest,并且在

Tsconfig.json

你需要

"compilerOptions"下的类型中的 "jest"

喜欢

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

你就完了。

在我的例子中(Visual Studio Code,创建应用程序纱线 workspace,开玩笑的 v26,@types/jest,tsconfig.json中的 "types": ["node", "jest"]) 测试正常,但 IDE 是 下划线,所有的 describeit都是红色的。

没有任何帮助,直到我 重新装弹的 VisualStudio 代码窗口后,尝试了相当长的时间。

下面的配置适合我。我添加了 node_modules/@typestypeRoots

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

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

{
"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. */
}
}

如果需要在项目中安装 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',

以上的解决方案都没有帮助到我。

我用的是:

  • 角度 11
  • 开玩笑的
  • 卸载任何与 茉莉卡玛相关的程序
  • .spec文件与组件位于同一文件夹中(自动生成 ng g)

添加 excludeJson(而不是 Tsconfig.json)忽略所有规格文件时,服务的应用程序为我工作。

Json

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

ng snpm test现在为我工作。

对于 蕾娜 整体式储存库用户

我正在运行一个 Lerna 整体仓库,以下是我必须做的修复工作:

  1. 确保 "@types/jest"位于根包和 packages/目录中的单个包的 包裹 Json文件的 devDependency 中,并且运行 lerna bootstrapnode_modules目录中安装/链接这些包

  2. 确保 "types": ["node", "jest"]部分位于根 tsconfig.json 中。

  3. 我将 import 'jest';添加到个人 * . test.ts 文件的顶部。

这对我很有效:

import '@types/jest';

另一个可能出错的地方是,如果在项目上方的父目录中打开了 VisualStudio 代码。这种情况发生在我身上是因为我们使用的是 视觉工作室解决方案,我打开了整个解决方案,而不仅仅是项目。

简单地说,确保 VisualStudio 代码打开到项目的根目录。

原因可能有很多:

  1. 如果没有安装 @types/jest,尝试安装它

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

用途:

import {} from 'jasmine';

将上面的代码行添加到代码中。

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

我今天碰到这个问题,因为我正在组装一个 POC。我使用量角器和 茉莉(相对于 开玩笑的摩卡)。实际上,我必须通过 TypeScript 实用程序/包创建 tsonfig 文件。

然后,在 Tsconfig类别阵列中加入“茉莉花”和“节点”就可以了。

这是我碰到的链接: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

在我的例子中,我创建了 babel.config.js,它导致了一个问题。另外,我们为编译文件添加了 **/*.js.gitignore; 我们的团队有不同的环境。

如果我们使用 ts-jest,我们不需要 babel.config.js

软件包可能没有正确安装。请检查该包是否确实存在于 Http://stackoverflow. com/questions/63294260/what-is-the-aim-of-the-node-module-file”> node _ module 文件夹中。像这个 堆栈溢出问题一样,TypeScript 东西抛出了错误,因为它的 Node _ module目录是空的。

它们通过在 tesconfig 文件中添加@type/jest 来解决我的问题:

Enter image description here

至少从 Jest 25开始,直接导入 Jest 全局变量就成为可能。这通常与 injectGlobals: false配置选项或来自 CLI 的 --injectGlobals=false一起使用。

例如:

import { describe, expect, it, test } from '@jest/globals';