skip to Main Content

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

2

Answers


  1. 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)"],
    };
    
    
    Login or Signup to reply.
  2. just try this modification in your package.json

    "dependencies": {

    //your previous modules

    "cross-env": "^7.0.3",

    }

    "scripts": {

    "start": "cross-env NODE_OPTIONS=--max-old-space-size=8096 react-scripts --openssl-legacy-provider start",
    "build": "cross-env NODE_OPTIONS=--max-old-space-size=8096 react-scripts --openssl-legacy-provider build",
    "test": "cross-env NODE_OPTIONS=--max-old-space-size=9096 react-scripts --openssl-legacy-provider test",
    "eject": "react-scripts eject"
    

    },

    mine was working !

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search