Skip to content
Advertisement

How to use Jest to test functions using crypto or window.msCrypto

When running unit tests with Jest in react the window.crypto API is causing problems. I haven’t found a way to incorporate crypto in Jest without installing other packages which is something I can’t do. So without using another npm package is there a way to test functions that use: crypto.getRandomValues() in them that doesn’t crash Jest? Any links, advice, or tips are appreciated

Advertisement

Answer

Use the following code to set up the crypto property globally. It will allow Jest to access

  • window.crypto in the browser environment
  • global.crypto in non-browsers environments. (Node/Typescript scripts).

It uses the globalThis which is now available on most of the latest browsers as well as Node.js 12+

const crypto = require('crypto');

Object.defineProperty(globalThis, 'crypto', {
  value: {
    getRandomValues: arr => crypto.randomBytes(arr.length)
  }
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement