sourcecode

'descript' 이름을 찾을 수 없습니다.테스트 러너에 대한 유형 정의를 설치해야 합니까?

codebag 2023. 2. 22. 21:53
반응형

'descript' 이름을 찾을 수 없습니다.테스트 러너에 대한 유형 정의를 설치해야 합니까?

Jest와 함께 TypeScript를 사용하면 스펙이 실패하고 다음과 같은 오류 메시지가 나타납니다.

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

Visual Studio Code를 IDE 및 Angular 프로젝트에서 사용하고 있는데, tsconfig.json 파일의 유형을 코멘트 아웃/삭제하고 tsconfig.spec.json의 유형에 "jest"를 추가해야 했습니다.

파일 tsconfig.json

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

파일 tsconfig.spec.json

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

IDE(Visual Studio Code)와 TypeScript 모두 tsconfig.json을 사용하기 때문에 조금 까다롭습니다.

초기 문제를 해결하기 위한 간단한 체크리스트:

(TypeScript 및 Jest용)

  1. 있어야 합니다.@types/jest ★★★★★★★★★★★★★★★★★」@types/node★★★★★★★★★★★★★★★★★★.
  2. ' 유형들이에요.tsconfig.json 이렇게."types": ["jest", "node"]
  3. 테스트 또는 테스트 디렉토리가 에서 제외되지 않았는지 확인합니다.tsconfig.jsonexcluded★★★★★★★★★★★★★★★★★★.

전위 부작용

"TypeScript"를 사용하여 "에서 "JavaScript"로tsc ""에 tsconfig.json이 경우 테스트도 변환될 수 있습니다(빌드 디렉토리에서 .transfile 대응이 확인됩니다).

그러나 대부분의 경우 다음 중 하나를 사용할 수 있습니다.

  1. 하다tsconfig.prod.json디폴트 설정을 덮어쓰는 설정으로 합니다.이 많이 요.inlineSource,sourceMaps,inlineSourceMaps 하고 「Disable」를 사용하는 .tsc --project tsconfig.prod.json
  2. "terminal(npm/syslog)" terminal(npm/syslog ") 입니다.예:npx tsc --inlineSourceMap false --declarationMap false --inlineSources false --sourceMap false 때, 이렇게 하면 --excludeFiles ★★★★★★★★★★★★★★★★★」--excludeDirectories플래그를 사용하여 매뉴얼에 따라 테스트를 빌드에서 제외합니다.

다른 방법은 rimraf와 같은 패키지를 사용하여 빌드 프로세스의 일부로 불필요한 파일을 삭제하는 것입니다.구성을 덮어쓰는 것보다 덜 복잡할 수 있으며 빌드 단계로 유지 관리하기가 더 쉽습니다.이 경우 다음 명령을 사용할 수 있습니다.yarn rimraf build/**/*.test.js.

이 방법은 효과가 있었습니다.

import '@types/jest';

이전 답변들 중 어느 것도 제 문제를 해결하지 못했습니다.

수 추가했다"@types/jest"typestsconfig.json 파일의 어레이.

할 수 은 ""를 추가하는 이었습니다.tests/폴더를 tsconfig.json 파일로 "삭제"합니다.

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

ESLint를 가지고 있는 사람도 불만족스럽다면 Jest를 추가해 주세요..eslintrc.json 삭제:

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

tsconfig.json잠시동안, 나는 마침내 그 코멘트를"types": [],과가있있 있있있다다

설정 실패(이전)

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

작업 구성

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

테스트 파일에 Jest를 Import해야 합니다.

import 'jest';

문제를 해결하는 또 다른 방법은 tsconfig.json 파일에 추가하는 것입니다.

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

TSLint 를 사용하고 있는 경우는, tsconfig.json 파일의 말미에 콤마가 필요 없는 경우가 있습니다.다음은 예를 제시하겠습니다.

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

내 경우 (Visual Studio Code, Create React App, Yarn 워크스페이스, Jest v26, @types/jest,"types": ["node", "jest"] 실리다tsconfig.json) 테스트는 정상적으로 실행 중이었지만 IDE는 모든 테스트에 밑줄을 그었습니다.describe §it빨간색으로 표시됩니다.

한참 후에 Visual Studio Code 창을 다시 로드할 때까지 아무 도움도 되지 않았습니다.

이하의 설정이 유효합니다.는 ㅇㅇㅇㅇㅇㅇㅇㅇ다를 넣었습니다.node_modules/@types로로 합니다.typeRoots.

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

tsconfig.json 파일에 테스트 경로를 포함해야 합니다.

를 들어, :: you고 example example 、 로 、 고 、 고 、 고 、 고 、 고 、 example 。tests/root 프로젝트 디렉토리에 저장하여 tsconfig의 "temp" 파라미터로 testes 파일을 검색해야 합니다.

  1. tsconfig.json

  2. 추가:

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

    <file_test_extension>:| etc.ts | js | 등 ts

따로따로 가지세요.tsconfig.json 폴더 " " "에서__tests__:

{
    "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다음 예시와 같이 내선번호에서도 이 기능을 사용해 주세요.

tsconfig.json

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

tests/tsconfig.json

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

빌드 폴더에 포함된 항목은 변경되지 않지만 Visual Studio Code가 Jest 유형을 찾을 수 있습니다.

Greg Woz가 가장 완벽한 답이다.어떤 이유에서인지 첫 번째 tsconfig.json 파일에 포함되어 있습니다."exclude": ["node_modules", "**/__tests__/*"]이것이 근본 원인입니다.후, 저는 그후 after after after after after after를 했습니다."**/__tests__/*"꼭 하세요."types": ["jest"]가 있습니다그건 효과가 있다.

또한 구성 변경 후 Visual Studio Code를 재시작해야 합니다.재기동하지 않고 여러 가지 방법을 시도하면 몇 시간이나 낭비됩니다.

또한 프로젝트 위의 상위 디렉터리에서 Visual Studio Code를 연 경우 문제가 발생할 수 있습니다.Visual Studio 솔루션을 사용하고 있기 때문에 프로젝트뿐만 아니라 솔루션 전체를 오픈하고 있었기 때문입니다.

간단히 말해, Visual Studio Code가 프로젝트의 루트에 열려 있는지 확인합니다.

테스트 경로를 tsconfig.json에 포함해야 합니다.

이 문제를 해결하려면tsconfig.json a. a. a.tsconfig.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,
  ...
}

Lerna 모노리식 저장소 사용자용

Lerna 모노리식 저장소를 운영하고 있는데, 이를 수정하기 위해 다음과 같이 해야 했습니다.

  1. 하다"@types/jest"파일 패키지의 devDependencies에 있습니다.루트 패키지와 개별 패키지의 양쪽 json은packages/되어 있습니다.lerna bootstrap을 하다node_modules

  2. 확인하세요."types": ["node", "jest"]piece에 .

  3. 는 ㅇㅇㅇㅇㅇㅇㅇㅇ다를 넣었습니다.import 'jest';*.test 파일의맨 합니다.test.ts를 선택합니다.

제 경우, 문제는 특정 파일 하나에 있었습니다.하지 못했지만, 자체는 발견하지 못했지만, 되었습니다.import {} from 'jest'파일을 가져올 수 있습니다.

Jest 문제 추적기, 스택 오버플로 또는 도움이 되지 않는 것 외에는 방법이 없습니다.그건 그냥 미친 해결방법으로 고친 미친 버그였어.

그리고 에 나온 ,, 리, 리, 리, 가, 가, 가, the, the, the, the, the, the, the, , the.jest,ts-jest ★★★★★★★★★★★★★★★★★」@types/jest파일을 작성하다.물론입니다.

위의 어떤 솔루션도 도움이 되지 않았습니다.

사용 중:

  • 각도 11
  • 농담
  • Jasmine-Karma 관련 항목 제거
  • .spec파일이 컴포넌트와 같은 폴더에 있습니다(자동 생성).ng g)

" " " excludetsconfig.app.json(tsconfig.json이 아님)으로 이동하여 앱을 제공할 때 모든 사양 파일을 무시하도록 했습니다.

tsconfig.app.json

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

ng s ★★★★★★★★★★★★★★★★★」npm test이제 날 위해 일해

용도:

import {} from 'jasmine';

위의 행을 코드에 추가합니다.

프리워커가 댓글로 제시한 솔루션은 놓치기 쉽다.tsconfig 파일에서 "typeRoots"를 삭제하면 분명히 "type"보다 우선합니다.이 문제는 해결되었습니다.

가 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★@types/jest ★★★★★★★★★★★★★★★★★」jest

나에게 효과가 있었던 것:

비주얼 스튜디오 코드★★★★★★★★★★★★★★★★를 실행할 필요가 있습니다.npm i --save-dev @types/jest 이 에는 '어울리지 않다'라고 씁니다.

tsconfig.json

를 배치해야 합니다.

"jest" "compilerOptions"

맘에 들다

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

그럼 끝이야

적어도 제스트 25부터는 제스트 글로벌을 직접 수입하는 것이 가능해졌다.이것은 보통 config 옵션 또는 CLI와 함께 사용합니다.

예를 들어 다음과 같습니다.

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

모카, 차이 그리고chai-http Node.jsExpress.js 프로젝트를 테스트합니다.사용하지 않았습니다.typescompilerOptions이전에 tsconfig.json 파일에 다음 설정을 추가해서 사용할 수 있게 되었습니다.

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

를 할 가 있는 .ts-jest'CHANGE: 'CHANGE: 'CHANGE:

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',

여러 가지 이유가 있을 수 있습니다.

  1. if@types/jest인스톨 되어 있지 않습니다.인스톨 해 주세요.tsconfig.json 파일에서 예를 들어 다음과 같은 유형을 정의합니다."typeRoots": ["node_modules/@types/", "./src/@types/", ".src/**/@types/"]

  2. Visual Studio 코드 문제: Visual Studio 코드를 상위 디렉터리에서 열지 않고 프로젝트 디렉터리에서 열려고 합니다.

★★★★★★★★★★★★★★를 설치했습니다.ts-jestnpm i -D ts-jest오류가 사라졌습니다.

tsconfig.jsontsc --initVisual Studio Code(비주얼 스튜디오 코드)는 "descript(설명)"입니다.

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

는 오늘 POC를 작성하다가 이 문제를 발견했습니다.(Jest나 Mocha아닌) Protractor와 Jasmine을 사용하고 있습니다.실제로 TypeScript 유틸리티/패키지를 사용하여 tsonfig 파일을 작성해야 했습니다.

그런 다음 tsconfig의 유형 배열에 "jasmin"과 "node"를 추가하면 정상적으로 작동합니다.

제가 찾은 링크는 다음과 같습니다.TypeScript 컴파일러 구성

★★★★★★★★★★★★★★★★★★★★★★★★★★」babel.config.js ,를 추가했습니다.**/*.js로로 합니다..gitignore컴파일 파일의 경우, 저희 팀은 다른 환경을 가지고 있습니다.

를 사용하는 ts-jest.babel.config.js.

패키지가 올바르게 설치되지 않았을 수 있습니다.패키지가 node_modules 폴더 내에 실제로 존재하는지 확인하십시오.이 Stack Overflow 질문과 마찬가지로 node_modules 디렉토리가 비어 있었기 때문에 TypeScript에서 오류가 발생했습니다.

언급URL : https://stackoverflow.com/questions/54139158/cannot-find-name-describe-do-you-need-to-install-type-definitions-for-a-test

반응형