3

I am using the validator library with tree-shakable esm imports for efficient bundle size.

When I try to test the file that uses the imports for esm modules, using jest, I get the following error -

Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    helpers/node_modules/validator/es/lib/isEmpty.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import assertString from './util/assertString';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import isEmpty from 'validator/es/lib/isEmpty';
        | ^
      2 | import isURL from 'validator/es/lib/isURL';
      3 | import isEmail from 'validator/es/lib/isEmail';
      4 | import matches from 'validator/es/lib/matches';

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (src/validator.ts:1:1)

Now I know jest cannot parse ESM modules so I tried adding the validator library to the transformIgnorePatterns. So this is how my jest.config.js looks like

module.exports = {
  preset: 'ts-jest',
  roots: ['<rootDir>/src'],
  testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'],
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
  },
  transformIgnorePatterns: ['<rootDir>/node_modules/(?!(validator/es/lib)/)'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
};

But this didn't work.

I also tried this answer and added babel for transpiling, with the same config mentioned in the answer but I still got the same error.

Although the tests work with the non-ESM imports, like,

import isEmpty from 'validator/lib/isEmpty';
Prateek Surana
  • 672
  • 9
  • 29

1 Answers1

1

Try to add this line to your jest.config.js

module.exports = {
  ...
  transformIgnorePatterns: [
    '/node_modules/(?!(validator)/)'
  ],
  ...
}

or try to update jest from package.json

"jest": {
  "transformIgnorePatterns": [
     "/node_modules/(?!(validator)/)"
  ]
},
Alireza Esfahani
  • 701
  • 7
  • 16