ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
https://zelark.github.io/nano-id-cc/
MIT License
24.22k stars 790 forks source link

Challenges using nanoid under jest with jsdom environment? #439

Closed cmdcolin closed 1 year ago

cmdcolin commented 1 year ago

Hi there

I am trying to use nanoid with jest with the jsdom environment, but this seems to import the specialized index.browser.js bundle, which uses pure-ESM statements, and then that causes challenges with jest when it's not configured for pure-ESM.

setting up a pure-ESM environment is hard, so I was hoping there might be a alternative solution. I would like to avoid custom jest configurations, because I want to use nanoid in a library, and don't really want my downstream users who may use jest to have to custom configure their jest either.

here is a small repro https://github.com/cmdcolin/browser-nanoid-jest-repro

this issue happens with either nanoid v3 or v4 ( can change version in the repro package.json to see)

I know these bundle/esm issues are kind of tedious, if it is too specialized a use case, can close

ai commented 1 year ago

I recommend avoiding Jest because it too hacky and everything with ESM made it unusable. You can try uvu or vitest.

Another option is to use Jest option to change import path of nanoid and load Node.js version (but you need to use Nano ID 3).

cmdcolin commented 1 year ago

Another option is to use Jest option to change import path of nanoid and load Node.js version (but you need to use Nano ID 3).

is this documented by chance?

ai commented 1 year ago

is this documented by chance?

No. It is a hacky and non-recommended way. The only non-hacky way is to migrate to ESM.

ai commented 1 year ago

Some even bigger hacks can be found here

https://github.com/ai/nanoid/issues/395

cmdcolin commented 1 year ago

thank you for these examples! I will just close for now