nanoid: SyntaxError about import when using in jsdom testEnvironment

When testEnvironment: 'jsdom' is set it tries to load node_modules/nanoid/index.browser.js and shows an error about the import syntrax.

note: in testEnvironment: 'node' import has no problem

jest config:

export default {
  testEnvironment: 'jsdom',
  moduleFileExtensions: ['js', 'ts', 'tsx', 'json'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
};

tsconfig

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["./src"]
}

error:

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /<path-to-project>/node_modules/.pnpm/nanoid@3.3.4/node_modules/nanoid/index.browser.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { urlAlphabet } from './url-alphabet/index.js'
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import { nanoid } from 'nanoid';
        | ^

node: v14.17.5
nanoid 3.3.4

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 18 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Adding nanoid to transformIgnorePatterns and moduleNameMapper to the jest.config.ts helped in my case with the same error:

import type { Config } from "@jest/types";

const esModules = ["lodash-es", "nanoid"].join("|");

const config: Config.InitialOptions = {
    ... // rest of your config
    transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
    moduleNameMapper: {
        "^lodash-es(/(.*)|$)": "lodash$1",
        "^nanoid(/(.*)|$)": "nanoid$1",
    }
};

export default config;
jest.mock("nanoid", () => { return {
  nanoid : ()=>{}
} });

use mock in setupTests.js of jest

It is unfortunate to have these type of issues where there are multiple solutions to the same problem that IMHO should not exist. Imagine not knowing how to debug or even google this. It requires a good understanding of interactions between different systems, ESM vs CJS, browser vs node, the list goes on… (I for one do not understand all of it or necessarily “care” to understand all of it).

A zeroconf solution is really the only way this doesn’t continue biting developers.

@ai I’m not sure this is only a polyfill error, because it’s not really complaining about crypto, but about import. As you can see in the screenshot, I’m specifically telling him which file to import.

Tried all of the ideas in this issue, none of them worked for me. Would anyone be so kind and share their tsconfig.json and jest.config.js?

No matter what I do, I’m getting this: CleanShot 2022-06-18 at 12 23 55

Thanks!

@jacquesg thanks! I finally found a working combo this very minute, sharing it here if anyone runs into this issue:

The solution has 2 parts:

  1. jest.config.ts needs to process nanoid (because it’s an ESM), so we add it to transformIgnorePatterns. We also MUST add the js pattern to be transformed by ts-jest (this was the missing piece for me).
  2. We need to add the crypto polyfill @ai mentioned.

CleanShot 2022-06-18 at 12 42 35

@Pavel910

I have the following in src/tests/resolver.js:

function Resolver(path, options) {
  return options.defaultResolver(path, {
    ...options,
    packageFilter: pkg => {
      if (pkg.name === 'nanoid') {
        // eslint-disable-next-line
        delete pkg.exports;
        // eslint-disable-next-line
        delete pkg.module;
      }
      return pkg;
    },
  });
}

module.exports = Resolver;

and finally in jest.config.ts:

  resolver: `<rootDir>/src/tests/resolver.js`,

@ai I believe both uuid and nanoid have the same problem. Please see this thread for the full explanation: https://github.com/microsoft/accessibility-insights-web/pull/5421#issuecomment-1109168149.

My understanding is that some changes are required to make it compliant?

I added a note about Jest c9df0ab