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/webcrypto
in jestsetupFiles
Seems 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.js
PR 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/webcrypto
is 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.crypto
wonโ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
getRandomValues
andrandomUUID
are natively implemented in jsdom.Using @peculiar/webcrypto worked for me.
Ref: https://github.com/jsdom/jsdom/issues/1612#issuecomment-783729297
Trying
crypto.subtle.importKey
on the latest version ofjest-environment-jsdom
(29.5.0
) givesTypeError: Cannot read properties of undefined (reading 'importKey')
under node v20I also forced
jsdom
to the latest22.1.0
and 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/webcrypto
window.crypto = require('@trust/webcrypto');
at the top of jest.setup.js or setupTests.js (create-react-app)