cuid2: TypeError: Expected input type is Uint8Array (got object)
Been trying to upgrade to cuid2 from cuid on-off for a while now but never been able to solve this issue. Hoping maintainers or community can help.
I installed with the following:
yarn remove cuid
yarn add @paralleldrive/cuid2
And my diffs are essentially
- import cuid from "cuid"
+ import cuid2 from "@paralleldrive/cuid2"
- cuid()
+ cuid2.createId()
But I’m always seeing the error:
TypeError: Expected input type is Uint8Array (got object)
> 1 | import cuid2 from "@paralleldrive/cuid2"
Same with:
TypeError: Expected input type is Uint8Array (got object)
> 1 | import { createId } from "@paralleldrive/cuid2"
Only seems to be a problem on my web package, my api is not complaining.
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 19
JSDOM environment in Jest
This seems to be related to the use of
jsdom
as it buildsglobal
object which doesn’t match the one provided by Node.js. There is a known issue in Jest whenjsdom
environment is used and results ofnew TextEncoder().encode()
andnew Uint8Array()
are different, refer to https://github.com/jestjs/jest/issues/9983.The easy fix for the example provided by @AlaricWhitney would be to use custom environment which overwrites
Uint8Array
provided byjsdom
:jest-environment-jsdom
. Make sure to use the same version as yourjest
(incuid2-issue
example it was v27), ref. https://stackoverflow.com/a/72124554jsdom-env.js
file in the rootP.S. Change will make tests in the example fail, since expectations were not updated to match results from
createId
.JSDOM lacks features
Also it is known that
jsdom
doesn’t supportTextEncoder
andTextDecoder
, refer https://github.com/jsdom/jsdom/issues/2524. The workaround would be similar, see this comment.The bottom line is that when Unit Tests are executed via Jest, features like
Uint8Array
/TextEncoder
/TextDecoder
may be available injsdom
environment but will produce results different from those expected in Node.js or browser. It might be resolved byjsdom
at some point, but there is no clear ETA on the issue. I personally don’t think it’s oncuid2
to adjust and use something else, but owner of the package may fill differently 🙃@AlaricWhitney, @ericelliott I have validated that this works, hopefully it works for you too.
jest.config.mjs
jest-environment-jsdom.js
This was a frustrating issue…
Since it doesn’t look like this is something we can easily fix with a code change, I have updated the Readme Troubleshooting section.