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

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)
  }
});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)