Search code examples
typescriptunit-testingphpstormjestjsjetbrains-ide

Use of async/await in Jest unit tests raises an error in PhpStorm (or any JetBrains IDE)


This is my tsconfig.json file:

{
  "compilerOptions": {
    "lib": ["es2017"],
    "module": "commonjs",
    "noImplicitReturns": true,
    "outDir": "lib",
    "sourceMap": true,
    "target": "es6"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules"
  ]
}

Directory structure:

.
├── lib
├── src
│   └── module.ts
├── tests
│   └── module.spec.ts
└── tsconfig.json

I can write async/await code in the src dir, but when I try to use async/await syntax in unit test then my IDE (PhpStorm or any JetBrains product) complains that:

TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration form the 'Promise' constructor or include 'es2015' in your --lib options.

enter image description here

IMO this notice doesn't make sense because I have "lib": ["es2017"] in my tsconfig.json. But even If I replace it with "lib": ["es2015"] (which doesn't make sense, I know), then the error remains the same.

It's probably not a real error, because the code compiles properly and I can run the test.

Is it just a bug in the IDE or is it me doing something wrong?


Update

I've just found that the problem is not related to async/await only. There's a similar problem with Promises. When I use the Promise constructor or Promise.all() then I get the following error:

TS2693: 'Promise' only refers to a type, but is being used as a value here.


Solution

  • In your tsconfig.json, you have

    "include": [
        "src"
      ]
    

    so, only files from src folder are processed according to tsconfig.json settings; files from tests folder are excluded from compilation. If PhpStorm can't find a tsconfig.json file your current file is included in, it uses default compilation settings - so "lib": ["es2017"] is not used when linting your spec files with Typescript service, and you see TS errors.

    If you don't like to include test files in your main tsconfig.json, create a separate tsconfig.json with appropriate options in your tests folder: PhpStorm will use this config when linting your *.spec.ts files