'Cannot find name 'describe'. Do you need to install type definitions for a test runner?
When using TypeScript in conjunction with Jest, my specs would fail with error messages like:
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`.
The types are already installed.
I use:
"@types/jest": "^23.3.12",
"jest": "^23.6.0",
"ts-jest": "^23.10.5",
"typescript": "^3.1.6"
I run tests using jest --forceExit --coverage --verbose
Solution 1:[1]
I'm using VSCode as my IDE and in my Angular project, I had to comment-out/remove types in tsconfig.json and add jest in types at tsconfig.spec.json.
tsconfig.json
{
"compilerOptions": {
// "types": []
}
}
tsconfig.spec.json
{
"compilerOptions": {
"types": ["jest", "node"]
}
}
Solution 2:[2]
It's a bit tricky one because both: your IDE (i.e. VSCode) and TypeScript use tsconfig.json for their own purpose.
Simple checklist to solve the initial problem:
(for TypeScript and Jest)
- Make sure you have
@types/jestand@types/nodeinstalled. - Make sure you have linked these types in
tsconfig.jsonso that:"types": ["jest", "node"] - Make sure you don't have your tests or the tests directory excluded from
tsconfig.jsonconfiguration inexcludedproperty.
Side-effect on transpilation
If you transpile from TypeScript to JavaScript using tsc or any custom module that relies on tsconfig.json then you may notice that your tests will be transpiled too in such case (you'll see their .js correspondence in your build directory).
However, in most cases you will have either:
- separate
tsconfig.prod.jsonwith a configuration that overwrites the default one. There are many settings likeinlineSource,sourceMaps,inlineSourceMapswhich you'd probably want to disable too and then usetsc --project tsconfig.prod.jsonto build - terminal (npm/yarn script) command that overwrites the default config with the specific flags. Example:
npx tsc --inlineSourceMap false --declarationMap false --inlineSources false --sourceMap false. At that point you can use--excludeFilesor--excludeDirectoriesflag to exclude your tests from the build as per documentation.
The alternative is to use package like rimraf and delete unnecessary files as a part of the build process. Might be less complex than overwriting the configuration and easier to maintain as a build step. In such case you may use the command: yarn rimraf build/**/*.test.js
Solution 3:[3]
This worked for me:
import '@types/jest';
Solution 4:[4]
None of the above fixed my issue.
I had to add "@types/jest" to the types array in the tsconfig.json file.
Solution 5:[5]
The only way I was able to fix this, was by adding the tests/ folder to "include" in the tsconfig.json file:
"include": [
"src/**/*.ts",
"tests/*.ts"
]
For those who also have eslint complaining, you need to add jest to your .eslintrc.json file:
"env": {
"es2020": true,
"node": true,
"jest": true
}
Solution 6:[6]
You have to import jest in your test file:
import 'jest';
Another way to solve is adding in your tsconfig.json file:
"compilerOptions": {
"types": [ "node", "jest" ],
"moduleResolution": "node"
}
If you are using tslint, the problem may be a not necessary comma at the end of your tsconfig.json, for example:
{
"compileOnSave": true,
"include": [
"src"
], // remove this comma
}
Solution 7:[7]
In my case (vs code, create-react-app, yarn workspaces, jest@26, @types/jest, "types": ["node", "jest"] present in tsconfig.json) tests were running OK but IDE was underlining with red all describe and it. Nothing helped until I reloaded VS Code Window after trying quite long ?????
Solution 8:[8]
The below configuration works for me. I added node_modules/@types to typeRoots.
{
"compilerOptions": {
// ...rest of my settings
"typeRoots": ["node_modules/@types"],
"types": ["jest", "node"]
}
}
Solution 9:[9]
You need to include in tsconfig.json your test path.
Example: suppose you named your path to tests/ and put it in root project directory, you need to specify in "include" param from tsconfig to look out for testes files:
- Go to:
tsconfig.json - Add:
"include": [
"tests/*.<file_test_extension>",
],
<file_test_extension>:ts | js | etc.
Hope to help
Solution 10:[10]
You can have a separate tsconfig.json in the test folder __tests__:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"baseUrl": "./",
"outDir": "../build",
"noEmit": true,
"rootDir": "../",
},
"exclude": ["node_modules"],
}
which extends the one in the root folder:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./lib",
"rootDir": "./src",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
},
"exclude": ["node_modules", "**/*.test.ts", "__tests__"]
}
This way you tests files still get excluded from the public build, but still get to share all the common options.
If you are using includes instead of or in conjunction with excludes, make sure to use that in your extension as well, eg:
tsconfig.json
{
"includes": ["src"],
...
}
tests/tsconfig.json
{
"extends": "../tsconfig.json"
"includes": ["../"]
}
This won't change what gets included in your build folder, but it will allow VSCode to find your jest types
Solution 11:[11]
You need to include in tsconfig.json your test path.
I solved the problem by having a tsconfig.json and a tsconfig.build.json in my project root. tsconfig.json contains all options including
"include": ["src/**/*", "test/**/*"],
tsconfig.build.json:
{
"extends": "./tsconfig.json",
"include": ["src/**/*"]
}
Then in package.json (clean script optional):
"scripts": {
"clean": "rm -rf dist",
"build": "npm run clean && tsc --build tsconfig.prod.json,
...
}
Solution 12:[12]
@Greg Woz is the most completed answer, for my case, for some reason, the initial tsconfig.json file contains "exclude": ["node_modules", "**/__tests__/*"], Which is the root cause. After removed "**/__tests__/*". And make sure it also include: "types": ["jest"]. It works.
Also important to restart Vscode after configuration changes. It wastes me hours of time trying all the different ways without restarting it.
Solution 13:[13]
For lerna monorepo users
I'm running a lerna monorepo and here's what I had to do to fix it:
- Ensure
"@types/jest"is in the devDependencies of package.json of both the root package as well as the individual package in thepackages/directory, and you have runlerna bootstrapto install / link those packages in yournode_modulesdirectories - Ensure the
"types": ["node", "jest"]piece is in your root tsconfig.json. - I added
import 'jest';to the top of my individual *.test.ts files.
Solution 14:[14]
Another thing that could be wrong is if you have opened vscode in a parent directory above your project. This happened to me because we are using Visual Studio solutions and I had the entire solution open not just the project.
Simply put, make sure vscode is open to the root of your project.
Solution 15:[15]
In my case, the problem was in one particular file. I hadn't found the issue itself but it was cured by adding import {} from 'jest' to file's imports.
No other way from jest issue tracker or SO or wherenot did help. Just some crazy bug fixed by some crazy workaround ????
Yes, and I added the latest jest, ts-jest and @types/jest to package.json of course
Solution 16:[16]
None of the above solutions above helped me
I was using:
- Angular 11
- Jest
- Uninstalled anything related to Jasmine/Karma
.specfiles are in same folder as components (auto-gen fromng g)
What worked for me was adding exclude to tsconfig.app.json (not tsconfig.json) to ignore all spec files when serving the app.
tsconfig.app.json
"exclude": [
"**/*.spec.ts"
]
ng s and npm test now works for me.
Solution 17:[17]
The solution suggested by @Freewalker in comments can easily be missed. removing "typeRoots" from tsconfig file, which was apparently overriding "types" - resolved the issue.
Solution 18:[18]
What worked for me.
This is happening in VS Code. You need to run npm i --save-dev @types/jest, and in your
tsconfig.json
you need to place
"jest" in the types under "compilerOptions"
like
"types": ["gapi", "gapi.auth2", "jest"],
and you are done.
Solution 19:[19]
import {} from 'jasmine';
Add the above line to the code. Hope this would solve the issue.
Solution 20:[20]
I am using mocha, chai and chai-http for testing a Node Express.js project. I was not using types in compilerOptions earlier, but adding below setting in tsconfig.json made it work for me:
{
"compilerOptions": {
// ...rest of my settings
"types": ["mocha", "chai", "chai-http"]
}
}
Solution 21:[21]
Do you need install ts-jest dependency in your project
yarn add ts-jest -D
In your jest.config.ts file you need to set the line containing preset: undefined to preset: 'ts-jest'
// A preset that is used as a base for Jest's configuration
preset: 'ts-jest',
Solution 22:[22]
There can be multiple reasons:
If
@types/jestis not installed try installing it and in thetsconfig.jsondefine the types for example"typeRoots": ["node_modules/@types/", "./src/@types/", ".src/**/@types/"]VS code issue: try to open the vs code in the project directory rather than opening it in its parent directory.
Solution 23:[23]
I installed ts-jest with npm i -D ts-jest and error disappeared
Solution 24:[24]
I was missing tsconfig.json, and all I had to do was run tsc --init and vs code did not complain about "describe" anymore:
{
"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. */
}
}
Solution 25:[25]
I found a similar issue was caused by a version number mismatch between @types/jest and jest
Solution 26:[26]
I came across this issue today, as I was putting together a POC. I am using Protractor and Jasmine (as opposed to jest or mocha). Turns out I had to actually create the tsonfig file via Typescript utility/package.
Then, adding "jasmine" and "node" to the types array in tsconfig worked fine.
Here is the link I came across: https://howtodoinjava.com/typescript/tsconfig-json/
Solution 27:[27]
In my case, I created babel.config.js and it caused problem. Also we added **/*.js to .gitignore for compile files, our team have different environment.
If we use ts-jest we don't need babel.config.js.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
