2

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?

user842225
  • 5,445
  • 15
  • 69
  • 119

2 Answers2

0

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?

eskiltb
  • 92
  • 8
  • 1
    Having exact the same package.json and babel.config.cjs with values under "babel" key I'm still getting `SyntaxError: Cannot use import statement outside a module` error. Also tried `ts-jest` and `transformIgnorePatterns`, nothing works – VityaSchel Nov 04 '22 at 13:53
0

Adapting the answer from here worked for me in my jest.config.js. Specifically:

module.exports = {
  transformIgnorePatterns: ['/node_modules\/(?!crypto-random-string)(.*)']
}
amin_nejad
  • 989
  • 10
  • 22