score:34

Accepted answer

this should do it. use the following code to set up the crypto property globally. this will allow jest to access window.crypto and won't cause any issue.

const crypto = require('crypto');

object.defineproperty(global.self, 'crypto', {
  value: {
    getrandomvalues: arr => crypto.randombytes(arr.length)
  }
});

score:0

building upon what others suggested here, i resolved the issue with window.crypto.subtle.digest with the following:

object.defineproperty(global.self, "crypto", {
  value: {
    getrandomvalues: (arr: any) => crypto.randombytes(arr.length),
    subtle: {
      digest: (algorithm: string, data: uint8array) => {
        return new promise((resolve, reject) =>
          resolve(
            createhash(algorithm.tolowercase().replace("-", ""))
              .update(data)
              .digest()
          )
        );
      },
    },
  },
});

or, if not using typescript:

object.defineproperty(global.self, "crypto", {
  value: {
    getrandomvalues: (arr) => crypto.randombytes(arr.length),
    subtle: {
      digest: (algorithm, data) => {
        return new promise((resolve, reject) =>
          resolve(
            createhash(algorithm.tolowercase().replace("-", ""))
              .update(data)
              .digest()
          )
        );
      },
    },
  },
});

the reformating of the string is optional. it is also possible to hardcode the algorithm, e.g. by stating 'sha256' or 'sha512' or alike.

score:1

i have this problem in angular 8 with jest tests for lib that are using uuid generator. in jest test setup i mock this:

object.defineproperty(global.self, 'crypto', {
  value: {
    getrandomvalues: arr => arr
  },
});

score:1

const crypto = require('crypto');
global.crypto = crypto;

score:1

dspacejs's answer almost worked for me, except i had the same problem as mozgor. i got an error saying that window.crypto is readonly. you can use object.assign instead of directly trying to overwrite it.

install @peculiar/webcrypto with yarn add -d @peculiar/webcrypto or npm i --save-dev @peculiar/webcrypto

then add the following to your jest setup file:

import { crypto } from "@peculiar/webcrypto";

object.assign(window, {
  crypto: new crypto(),
})

score:1

in the default configuration, jest assumes you are testing a node.js environment. but when you are getting errors using methods of the window object, you are probably making a web app.

so if you are making a web app, you should use "jsdom" as your "testenvironment". to do this, insert "testenvironment": "jsdom", into your jest configurations.

if you maintain a "jest.config.js" file, then add it like:

module.exports = {
   ...
   "testenvironment": "jsdom",
   ...
};

or if, like me, you keep the jest configs in "package.json":

{
    ...,
    "jest": {
        ...,
        "testenvironment": "jsdom",
        ...
    },
    ...
}

score:2

add crypto global for your jest environment as if it were in browser. your jest.config.js should look like:

const {defaults} = require('jest-config');

module.exports = {
  globals: {
    ...defaults.globals,
    crypto: require('crypto')
  }
};

ref: https://jestjs.io/docs/en/configuration#globals-object

score:2

the default crypto dependency didn't work for me during testing with jest.

instead i used the @peculiar/webcrypto library:

yarn add -d @peculiar/webcrypto

then in your jest setup file, just add this:

import { crypto } from "@peculiar/webcrypto";


window.crypto = new crypto();

score:3

deriving from aiveligs answer:

since i use "node" environment in jest i had to use

module.exports = {
  preset: "ts-jest",
  testenvironment: "node",
  globals: {
    crypto: {
      getrandomvalues: (arr) => require("crypto").randombytes(arr.length),
    },
  },
};

score:3

i'm using vue-jest, and what worked for me is the following configuration in jest.config.js file:

module.exports = {
   ...
   setupfiles: [
      '<rootdir>/tests/settings/jest.crypto-setup.js',
   ],
};

and in jest.crypto-setup.js:

global.crypto = { 
     getrandomvalues: (arr) => require('crypto').randombytes(arr.length) 
};

adding the getrandomvalues function definition directly in module.exports didn't work since the globals object must be json-serializable (as it is specified here: https://jestjs.io/docs/configuration#globals-object).

score:4

the polyfills in the current answers are incomplete, since crypto.getrandomvalues() modifies its argument in-place as well as returning it. you can verify this by running something like const foo = new int8array(8); console.log(foo === crypto.getrandomvalues(foo)) in your browser console, which will print true.

getrandomvalues() also does not accept an array as its argument, it only accepts integer typedarrays. node.js' crypto.randombytes() function is not appropriate for this polyfill, as it outputs raw bytes, whereas getrandomvalues() can accept signed integer arrays with elements up to 32 bits. if you try crypto.getrandomvalues(new int32array(8)) in your browser, you might see something like [ 304988465, -2059294531, 229644318, 2114525000, -1735257198, -1757724709, -52939542, 486981698 ]. but if you try node -e 'console.log([...require("crypto").randombytes(8)])' on the command line, you might see [ 155, 124, 189, 86, 25, 44, 167, 159 ]. clearly these are not equivalent, and your component under test might not behave as expected if tested with the latter.

the latest versions of node.js solve this problem with the webcrypto module (should be a matter of setting globalthis.crypto = require('crypto').webcrypto). if you're using an older version of node (v14 or below) you might have better luck using crypto.randomfillsync(), which should be useable as a drop-in replacement for getrandomvalues() as it modifies a passed buffer/typedarray in-place.

in your jest setup file (can't be set via the globals configuration as it only allows json-compatible values):

const { randomfillsync } = require('crypto')

object.defineproperty(globalthis, 'crypto', {
  value: { getrandomvalues: randomfillsync },
})

score:5

for nodejs + typescript, just use global instead of global.self

import crypto from 'crypto'

object.defineproperty(global, 'crypto', {
  value: {
    getrandomvalues: (arr:any) => crypto.randombytes(arr.length)
  }
});

score:7

since node 15.x you can use crypto.webcrypto

eg.

import crypto from "crypto";

object.defineproperty(global.self, "crypto", {
  value: {
    subtle: crypto.webcrypto.subtle,
  },
});

score:19

like @rwwl, the accepted answer did not work for me. i found that the polyfill used in this library did work: commit with polyfill

//setuptests.tsx
const nodecrypto = require('crypto');
window.crypto = {
  getrandomvalues: function (buffer) {
    return nodecrypto.randomfillsync(buffer);
  }
};
//jest.config.js
module.exports = {
 //...
  setupfilesafterenv: ["<rootdir>/src/setuptests.tsx"],
};

Related Query

More Query from same tag