Jest doesn't seem to understand "import type"

2.7k views Asked by At

We recently updated our monorepository to:

  • Nx 14.3.6
  • Angular 14.0.3
  • Jest 28.1.1
  • TypeScript 4.7.4

After the upgrade the compilation succeeded, but at runtime we got lots of errors like "emitDecoratorMetadata causes runtime errors by referencing type-only imports with namespaces" (https://github.com/microsoft/TypeScript/issues/42624). This error was also reported by ESLint.

We solved this by (for all types and interfaces) replacing all "import" statements to "import type" statements. This fixed the runtime errors and the application worked again. To fix the ESLint error we also had to install and use the "eslint-plugin-import" extension.

So far so good, but now our tests stopped working. It seems that Jest doesn't understand the "import type" statement. In every unit test of a class that uses "import type", the tests fail with this error:

ReferenceError: Zyz is not defined

(where xyz is an imported type in the tested class, e.g.

// some-component.ts
import type { Xyz } from '...';
...

If we remove the "type" from the "import type" statement the test works but then the runtime errors reoccur.

I've searched quite a bit already (mostly by trying to use/reconfigure babel, because I found this post: https://github.com/babel/babel/issues/10981) but for now I'm unable to solve this problem.

1

There are 1 answers

1
johey On BEST ANSWER

Seems to be fixed by the workaround explained here: https://github.com/thymikee/jest-preset-angular/issues/1199#issuecomment-1168802943

So in tsconfig.spec.json configure the "include" property to contain all typescript files:

// tsconfig.spec.json
{
  ...
  "include": ["**/*.ts"]
}

Previously we had:

// tsconfig.spec.json
{
  ...
  "include": ["**/*.spec.ts", "**/*.test.ts", "**/*.d.ts", "jest.config.ts"]
}

Edit: In addition to the above configuration it seems that ts-jest also requires non-isolatedModules. We were using isolatedModules: true, but it caused the same problem with type-only imports.

If anyone knows why or has a better idea: please let me know.