Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Errors with nanoid v3 when using jest and jsdom #462

Open
anomiex opened this issue Jan 3, 2024 · 22 comments
Open

Errors with nanoid v3 when using jest and jsdom #462

anomiex opened this issue Jan 3, 2024 · 22 comments

Comments

@anomiex
Copy link

anomiex commented Jan 3, 2024

When running tests using jest and jest-environment-jsdom, version 3.3.7 of this package (which is still supposed to be commonjs-compatible) causes a failure:

 FAIL  ./test.js
  ● Test suite failed to run

    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:

    /tmp/test/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

      3 |  */
      4 |
    > 5 | const nanoid = require( 'nanoid' );
        |                ^
      6 |
      7 | test( 'it works', () => {
      8 |     const element = document.createElement('div');

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
      at Object.require (test.js:5:16)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.298 s

The problem is that, with jest-environment-jsdom, the conditions available are "browser", "require" (not "import"), and "default", but nanoid v3's exports assumes "browser" always comes with "import".

A detailed analysis of a similar problem in another package, along with potential workarounds, may be found at microsoft/accessibility-insights-web#5421 (comment).

Reproduction

  1. Create an empty directory for the test.
  2. Run npm add jest jest-environment-jsdom nanoid@^3
  3. Create the following file named test.js:
    /**
     * @jest-environment jsdom
     */
    
    const nanoid = require( 'nanoid' );
    
    test( 'it works', () => {
        const element = document.createElement('div');
        expect( element ).not.toBeNull();
    } );
  4. Run npm exec jest test.js
  5. See error
@ai
Copy link
Owner

ai commented Jan 3, 2024

The problem is that, with jest-environment-jsdom, the conditions available are "browser", "require" (not "import"), and "default", but nanoid v3's exports assumes "browser" always comes with "import".

What we can do on our side if the other module works with package.exports in a wrong way?

@cmdcolin
Copy link

cmdcolin commented Jan 3, 2024

similar thread here #439

@ai
Copy link
Owner

ai commented Jan 3, 2024

(Honestly, the struggle with Jest was a reason why I decided to go to ESM-only. There was just no way to make it work in every environment.)

@anomiex
Copy link
Author

anomiex commented Jan 3, 2024

In what way is jest with jsdom working with package.exports in a "wrong" way here? It's specifying "browser" and "require" (and not "import"), which is exactly what it wants to receive.

@ai
Copy link
Owner

ai commented Jan 3, 2024

Here is current package.exports of v3:

  "exports": {
    ".": {
      "browser": "./index.browser.js",
      "require": {
        "types": "./index.d.cts",
        "default": "./index.cjs"
      },
      "import": {
        "types": "./index.d.ts",
        "default": "./index.js"
      },
      "default": "./index.js"
    }

What changes do you suggest there to fix Jest?

@anomiex
Copy link
Author

anomiex commented Jan 3, 2024

jsdom is supposed to provide a browser-like environment. If it's not browser-like enough, that would be a problem with jsdom. OTOH, if a package assumes "browser" means "import", that's not jsdom's fault.

What changes do you suggest there to fix Jest?

You already appear to have an index.browser.cjs file available in the published package, so something like this would work.

  "exports": {
    ".": {
      "browser": {
        "require": "./index.browser.cjs",
        "default": "./index.browser.js",
      },
      "require": {
        "types": "./index.d.cts",
        "default": "./index.cjs"
      },
      "import": {
        "types": "./index.d.ts",
        "default": "./index.js"
      },
      "default": "./index.js"
    }

Or if you're worried that some browser might supply both "require" and "import", you could do like this to prefer the esm version in that case

      "browser": {
        "import": "./index.browser.js",
        "require": "./index.browser.cjs",
        "default": "./index.browser.js",
      },

Or you could switch it up, put "browser" inside the existing "require" and "import" blocks:

  "exports": {
    ".": {
      "require": {
        "types": "./index.d.cts",
        "browser": "./index.browser.cjs",
        "default": "./index.cjs"
      },
      "import": {
        "types": "./index.d.ts",
        "browser": "./index.browser.js",
        "default": "./index.js"
      },
      "browser": "./index.browser.js",
      "default": "./index.js"
    }

@ai
Copy link
Owner

ai commented Jan 3, 2024

But is it a good idea to use browser’s version in Node.js? Does Jest emulate crypto for Node.js <20?

We didn’t use .browser.cjs especially for that reason since it didn’t work in Node.js.

@anomiex
Copy link
Author

anomiex commented Jan 3, 2024

I'd say that if someone wants to try it, as indicated by passing the "browser" condition, it's their problem if it doesn't work due to a missing Web Crypto API or whatever.

In my case we're running the tests in Node 20 already anyway. But if we were still testing with an earlier version, I'd take it as my responsibility to load an appropriate mock/polyfill in the Jest config to make it work.

@ai
Copy link
Owner

ai commented Jan 3, 2024

Taking require was just work. We have a special Nose.js version exactly to work without polyfill.

OK, can you send PR to dual-publish to add browser.require if it already produces CJS files for browser?

@MikeMulyukin1983
Copy link

any solution for fix this?

@AdiMarianMutu
Copy link

AdiMarianMutu commented Jun 26, 2024

I get the same error, however related to import { webcrypto as crypto } from 'node:crypto'.

Current nanoid version: 5.0.7

Is there any solution to this?

I've temporarily solved the issue by downgrading to 3.3.4

@ai
Copy link
Owner

ai commented Jun 26, 2024

@AdiMarianMutu you have a different issue. You need to update your project to ESM to use 4.0 or 5.0.

@good-idea
Copy link

If this is blocking anyone, you can make a simple jest mock to get around it:

// in jest setup config

jest.mock('nanoid', () => {
  return {
    nanoid: () => Math.random().toString(),
  };
});

@jhackett1
Copy link

have removed from our codebase for this reason sadly :(

@rujorgensen
Copy link

I switched to the native 'crypto.randomUUID()' implementation in the end. One dependency less, haven't been happier.

@ppamorim
Copy link

@ai Any solution for that in mind? We will keep using v3 while this doesn't change. Sadly we can't get the improvements done for the node:18.

@ai
Copy link
Owner

ai commented Oct 24, 2024

@ppamorim sorry, there is no good solution. Jest is just broken with ESM because it hacked Node.js loading mechanism.

All options have a lot of compromises.

@anomiex
Copy link
Author

anomiex commented Oct 26, 2024

The breakage here has nothing to do with jest "hack[ing] the Node.js loading mechanism", it's that this package assumes that "browser" always means "import" despite the loading request specifically indicating "require" (i.e. commonjs) rather than "import" (i.e. esm).

I told you back in January how to fix it in v3, but I can't figure out your custom build system to work out how to fix it for you.

Although it seems like ppamorim may be asking about something else, since this issue is specific to v3 so "We will keep using v3 while this doesn't change" makes little sense in relation to this issue.

@ai
Copy link
Owner

ai commented Oct 26, 2024

it's that this package assumes that "browser" always means "import" despite the loading request specifically indicating "require" (i.e. commonjs) rather than "import" (i.e. esm).

Jest is broken because it is using browser version on Node.js environment.

We provide CJS package for Node.js, but Jest hacked require to use browser version which lead to issue with RNG too.

@anomiex
Copy link
Author

anomiex commented Oct 26, 2024

We already went through that argument above.

me:

In what way is jest with jsdom working with package.exports in a "wrong" way here? It's specifying "browser" and "require" (and not "import"), which is exactly what it wants to receive.

you:

But is it a good idea to use browser’s version in Node.js? Does Jest emulate crypto for Node.js <20?

We didn’t use .browser.cjs especially for that reason since it didn’t work in Node.js.

me:

I'd say that if someone wants to try it, as indicated by passing the "browser" condition, it's their problem if it doesn't work due to a missing Web Crypto API or whatever.

In my case we're running the tests in Node 20 already anyway. But if we were still testing with an earlier version, I'd take it as my responsibility to load an appropriate mock/polyfill in the Jest config to make it work.

@ai
Copy link
Owner

ai commented Oct 26, 2024

Browser version in Node.js environment is still non-standard Node.js behavior and this is why for me, it is a hack.

@Grohden
Copy link

Grohden commented Dec 19, 2024

if it helps with anything, I couldn't mock the module due to having a requireActual in a dep that used nanoid (at least thats why I think the mock didn't work)

However by letting jest transform nanoid it works fine for me:

// jest.config.js

{
 transformIgnorePatterns: [
    '<rootDir>/node_modules/(?!nanoid)',
  ],
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

10 participants