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 · 9 comments
Open

Errors with nanoid v3 when using jest and jsdom #462

anomiex opened this issue Jan 3, 2024 · 9 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?

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

3 participants