Search code examples
javascripttypescriptjestjsts-jestbabel-jest

Ts-jest SyntaxError: Cannot use import statement outside a module


Issue

I'm running into error SyntaxError: Cannot use import statement outside a module for my jest unit tests after switching one of the packages in our dependencies. The package is a hard requirement and we cannot do anything with it. After looking into the issue, I believe it's because the package doesn't ship a cjs output and Jest couldn't understand esm syntax.

I've seen tons of discussions/solutions for this topic and tried pretty much every solution I could find online. But unfortunately none of them worked for me. I've created a repo as a minimal repro of the issue. Here is the link.

What I have tried

  • Different presets for ts-jest
  • Adding babel-jest together with different plugins to deal with the js files in the 3rd party package. Tried different formats of the config (js file, json, .bablerc)
  • Modifying transform setup in Jest configuration as '^.+\\.jsx?$': 'babel-jest', '^.+\\.tsx?$': 'ts-jest' and all other possibilities around this.
  • In Jest configuration, testPathIgnorePatterns, transformIgnorePatterns. I thought this would be the solution but it didn't. Maybe I was not doing it correctly?
  • Adding useESM to ts-jest config
  • And so on

What I have not tried

The experimental esm support provided by jest, as it's experimental and doesn't meet our requirement.

I'd appreciate it if you could play around with the repro repo and give me some suggestions


Solution

  • Since you allowJS in to be used in your tsconfig

    you can change the transform pattern to allow js files as well and add the package to the transformIgnorePatterns

    module.exports = {
      preset: "ts-jest",
      testEnvironment: "jsdom",
      globals: {
        "ts-test": {
          tsConfig: "tsconfig.test.json",
        },
      },
      transform: {
        "^.+\\.[jt]s?$": ["ts-jest"],
      },
      transformIgnorePatterns: ["node_modules/(?!@me/test-package)"],
    };