Running Jest test get error "Cannot use import statement outside a module"

Viewed 1796

In my node.js (with typescript) project, I try to use crypto-random-string package for generating random string value.

I use pnpm installed it:

pnpm i crypto-random-string

In my production code I use it as:

import cryptoRandomString from 'crypto-random-string';

const cryptoStr = () => cryptoRandomString({ length: 10, type: 'ascii-printable' });

I have a jest code to unit test it, but when run jest, it complains:

my-project/node_modules/.pnpm/crypto-random-string@5.0.0/node_modules/crypto-random-string/index.js:3
    import {promisify} from 'node:util';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import cryptoRandomString from 'crypto-random-string';

My jest.config.ts:

export default {
  jest: {
    preset: 'ts-jest',
    testEnvironment: 'node',
    transform: {
      'node_modules/variables/.+\\.(j|t)sx?$': 'ts-jest',
    },
    transformIgnorePatterns: ['node_modules/(?!variables/.*)'],
  },
};

I tried the solutions from here, but not helpful for me.

How to solve this issue?

1 Answers

You need to use babel. In server package.json:

  "devDependencies": {
  "@babel/preset-env": "^7.16.11"    
  "babel-jest": "^27.5.1",
  "jest": "^27.5.1",
  },

  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "targets": {
            "node": "current"
          }
        }
      ]
    ]
  }

And client package.json:

  "devDependencies": {
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "jest": "^27.5.1",
    "jest-babel": "^1.0.1",
    "parcel": "^2.3.2"
  },
  "babel": {
    "presets": [
      "@babel/preset-react",
      [
        "@babel/preset-env",
        {
          "targets": {
            "node": "current"
          }
        }
      ]
    ]
  }

If that does not work, could you also provide the test file?

Related