jsdom: window.crypto is undefined
iโm trying to run tests using jsdom and mocha but I got this error:
ReferenceError: crypto is not defined
Is crypto really defined in jsdom?
About this issue
- Original URL
- State: open
- Created 8 years ago
- Reactions: 20
- Comments: 28 (2 by maintainers)
Please consider adding
crypto.randomUUID(). ๐I used
@peculiar/webcryptoin jestsetupFilesSeems to be working fine.
If you only require random numbers to be polyfilled, then you can also do
Note: Youโll need Node v10 if you want buffer to be able to be Uint32Array as in v8 only Uint8Array and Buffer are supported
Put these codes into
jest.steup.js, then you can visit window.crypto:I just added the following to my
jest.setup.jsPR for
crypto.getRandomValues(array)(only that one) at #3352.Thanks , it is working fine for me also . https://www.npmjs.com/package/@peculiar/webcrypto - It is also maintained. you save my day ๐ It was struggling from last one hour for this issue .
Note that
@trust/webcryptois no longer maintained. See anvil.io.This solution worked for me: https://stackoverflow.com/a/66687075/4064775
in your setup file (for jest). With node 15.
Just ran in to this with Jest 29 on Node18. Overcame with the following custom environment:
Hope it helps others landing here ๐
Thanks! ๐๐ป๐ค
Overriding
global.cryptowonโt work in v20 as itโs read-only now. Might be possible with--no-experimental-global-webcrypto, though. Also the lib only covers a subset of features. Def better than none for sure.@theogravity Iโm facing the same issue it would seem only
getRandomValuesandrandomUUIDare natively implemented in jsdom.Using @peculiar/webcrypto worked for me.
Ref: https://github.com/jsdom/jsdom/issues/1612#issuecomment-783729297
Trying
crypto.subtle.importKeyon the latest version ofjest-environment-jsdom(29.5.0) givesTypeError: Cannot read properties of undefined (reading 'importKey')under node v20I also forced
jsdomto the latest22.1.0and it also gives that.This is still not working for me, keep getting error:
I added the following config options in package.json:
jest.setup.js
npm i @trust/webcryptowindow.crypto = require('@trust/webcrypto');at the top of jest.setup.js or setupTests.js (create-react-app)