Reputation: 7980
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
Upvotes: 243
Views: 235843
Reputation: 7302
It's a bit tricky one because both: your IDE (i.e., Visual Studio Code) and TypeScript use tsconfig.json for their own purposes.
(when using TypeScript and Jest)
@types/jest
and @types/node
installed.tsconfig.json
so that: "types": ["jest", "node"]
tsconfig.json
configuration in excluded
property.Now, if you're building your application with any transpiler from TypeScript to JavaScript that relies on tsconfig.json
(for example: tsc
provided when installing the typescript package) you may notice that your tests will be transpiled too in such case since you have included them to the build. (Check your output/build directory and you'll see their .js correspondence).
If you're confused at this point or it seems too difficult- explore tsconfig.json configuration documentation first and come back.
In most cases you will have either:
tsconfig.prod.json
with a configuration that extends or overwrites the default one. There are many settings like inlineSource
, sourceMaps
, inlineSourceMaps
which you'd probably want to disable too.Example:
tsc --project tsconfig.prod.json
to run the build
--excludeFiles
or --excludeDirectories
flag to exclude your tests from the build as per documentation.Example:
npx tsc --inlineSourceMap false --declarationMap false --inlineSources false --sourceMap false
Then, after the successful code conversion, you can use the library such as rimraf to delete unnecessary files and directories. It might be less difficult than overwriting the configuration and easier to maintain as a build step.
Example:
npx rimraf build/**/*.test.js
Note: Sometimes it may take a moment for your IDE (or exactly TypeScript service) to pick up the changes. Give it a few seconds to sink in and re-index. If you want to perform the restart manually:
Ctrl+Shift+P
or CMD+Shift+P
. You should see a dropdown where you type: ">Typescript" and select: ">TypeScript: restart service."Tip: Review your configuration where from Node and TypeScript are being sourced. Sometimes when installing too many versions or project it may swap or switch to some old place and cause the issues. It should either point to the version you intended to install (for example using nvm
or other version manager) or to your project node_modules
.
Example in Webstorm:
Tip 2: Take your time, try to understand correlation between NodeJS and TypeScript, your files and what's happening behind the scenes. Don't rush with setting up your project and be thorough step by step. Most of the TypeScript issues are easy to solve if you understand what you're trying to achieve at the specific step.
Upvotes: 217
Reputation: 121
I've been work in a project from 2 years and suddenly this message appears from nowhere, I will tell what resolved for me.
Cannot find name 'describe'. Do you need to install...
I spent a lot time to resolve this. I tried a lot of things like restart my vscode, reinstall the packages, change node version and reinstall packages and unfortunately nothing worked.
I read the most upvoted answer and tried everything that he said to do, but the last one I really didn't found how to do. After more failed tries I resolved to read it again and I finally found what to do and I will post it with images to help others. Special thanks to @Greg Wozniak.
So on your VSCode look on bottom bar and try find an annotation {} Typescript:
Do not click on Typescript, click on {} and it will appear something like this:
Click on Typescript Version row and select the version. It will show other menu to select the typescript version that you want to use on you VSCode. Something like this:
Then you need to select the correct version to you, in my case, I selected the Workspace Version and finally all the errors disappeared.
EDIT: I forgot to explain why this happened to me. So this happened because I updated the VSCode version and for some reason that I don't know yet the VSCode toke the version of the typescript from his configs and not from my node_modules.
Upvotes: 2
Reputation: 46
Check if you have the test files in exclude configuration on tsconfig.json:
"exclude": ["node_modules", "dist", **"src/**/*.spec.ts"**, "build.js"]
this will ignore test files from typescript watching remove that and you will be able to use jest function without problems:
"exclude": ["node_modules", "dist", "build.js"]
Upvotes: 0
Reputation: 810
The only solution that worked for me was this
"include": [
"src/**/*.ts",
"*.spec.ts"
]
Upvotes: 0
Reputation: 798
add jest
to tsconfig.json
will solve this issue.
Example:
// tsconfig.json
{
"compilerOptions": {
"types": ["node", "express", "multer", "jest"],
}
}
Upvotes: 0
Reputation: 6067
In the VS Code IDE, if red squiggly lines persist despite installing all the necessary dev dependencies, then run the Developer Reload Window command.
Use the shortcut:
Upvotes: 3
Reputation: 553
Besides other answers, for me, explicit imports helped. Other answers with types didn't help because they were already implemented
import { expect, describe, it, test } from '@jest/globals';
Upvotes: 4
Reputation: 853
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.build.json,
...
}
Upvotes: 12
Reputation: 1334
I was still having the issue with mocha
even after installing the type definition files from @types/mocha
.
Just ensure that if you have configured typeRoots
in your tsconfig.json
, then node_modules/@types
is equally added.
// tsconfig.json
{
"compilerOptions": {
"typeRoots": [
...
"node_modules/@types"
]
}
}
Upvotes: 2
Reputation: 25457
Since at least Jest 25, it has been possible to import the Jest globals directly. This is usually used in conjunction with the injectGlobals: false
config option or with --injectGlobals=false
from the CLI.
For example:
import { describe, expect, it, test } from '@jest/globals';
Upvotes: 8
Reputation: 837
You need to include your test path in file tsconfig.json.
Example: suppose you named your path to tests/
and put it in root project directory, you need to specify in "include" parameter from tsconfig to look out for testes files:
Go to: tsconfig.json
Add:
"include": [
"tests/*.<file_test_extension>",
],
<file_test_extension>:
ts | js | etc.
Upvotes: 15
Reputation: 2331
The packages might have not installed properly. Do check if the package does really exist inside the node_modules folder. Like to this Stack Overflow question, the TypeScript thingy was throwing the error, because its node_modules directory was empty.
Upvotes: 1
Reputation: 93
In my case, I created babel.config.js
, and it caused a problem. Also, we added **/*.js
to .gitignore
for compile files; our team has different environments.
If we use ts-jest
, we don't need babel.config.js
.
Upvotes: 0
Reputation: 39
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). It turns out I had to actually create the tsonfig file via a TypeScript utility/package.
Then, adding "jasmine" and "node" to the types array in tsconfig worked fine.
Here is the link I came across: TypeScript Compiler Configuration
Upvotes: 0
Reputation: 1541
The solution suggested by Freewalker in comments can easily be missed. Removing "typeRoots" from the tsconfig file, which was apparently overriding "types" - resolved the issue.
Upvotes: 7
Reputation: 643
There can be multiple reasons:
If @types/jest
is not installed, try installing it. In the tsconfig.json file, define the types, for example, "typeRoots": ["node_modules/@types/", "./src/@types/", ".src/**/@types/"]
Visual Studio Code issue: try to open Visual Studio Code in the project directory rather than opening it in its parent directory.
Upvotes: 3
Reputation: 81
Another thing that could be wrong is if you have opened Visual Studio Code 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 Visual Studio Code is open to the root of your project.
Upvotes: 8
Reputation: 1683
I'm running a Lerna monolithic repository and here's what I had to do to fix it:
Ensure "@types/jest"
is in the devDependencies of file package.json of both the root package as well as the individual package in the packages/
directory, and you have run lerna bootstrap
to install / link those packages in your node_modules
directories
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.
Upvotes: 6
Reputation: 3511
None of the previous solutions above helped me.
I was using:
.spec
files are in same folder as components (auto-gen from ng g
)Adding exclude
to tsconfig.app.json (not tsconfig.json) to ignore all specification files when serving the app worked for me.
tsconfig.app.json
"exclude": [
"**/*.spec.ts"
]
ng s
and npm test
now work for me.
Upvotes: 4
Reputation: 11
If you need to install the 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',
Upvotes: 1
Reputation: 1162
I was missing tsconfig.json
, and all I had to do was run tsc --init
and Visual Studio Code did not complain about "describe" any more:
{
"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. */
}
}
Upvotes: 0
Reputation: 1084
In my case (Visual Studio Code, Create React App, Yarn workspaces, Jest v26, @types/jest, "types": ["node", "jest"]
present in tsconfig.json
) tests were running OK, but the IDE was underlining all describe
s and it
s with red.
Nothing helped until I reloaded the Visual Studio Code window after trying quite long.
Upvotes: 21
Reputation: 511
What worked for me:
This is happening in Visual Studio 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.
Upvotes: 2
Reputation: 6033
Greg Woz's is the most complete answer. For my case, for some reason, the initial tsconfig.json file contains "exclude": ["node_modules", "**/__tests__/*"]
, which is the root cause. After that I removed "**/__tests__/*"
. And make sure it also includes: "types": ["jest"]
. It works.
Also, it is important to restart Visual Studio Code after configuration changes. It wastes me hours of time trying all the different ways without restarting it.
Upvotes: 7
Reputation: 1091
I installed ts-jest
with npm i -D ts-jest
and the error disappeared.
Upvotes: 0
Reputation: 2639
None of the previous answers fixed my issue.
I had to add "@types/jest"
to the types
array in the tsconfig.json file.
Upvotes: 58
Reputation: 864
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
}
Upvotes: 42
Reputation: 4756
I am using Mocha, Chai and chai-http
for testing a Node.js Express.js project. I was not using types
in compilerOptions
earlier, but adding the below setting in file tsconfig.json made it work for me:
{
"compilerOptions": {
// ...rest of my settings
"types": ["mocha", "chai", "chai-http"]
}
}
Upvotes: 1
Reputation: 345
You have to import Jest in your test file:
import 'jest';
Another way to solve it is adding it 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 file, for example:
{
"compileOnSave": true,
"include": [
"src"
], // Remove this comma
}
Upvotes: 24