Orbit-db: Jest and Orbit issue

Created on 8 Feb 2018  路  2Comments  路  Source: orbitdb/orbit-db

Orbity keystore depends on elliptic which depends on the brorand library. When running Jest tests with --env=jsdom, the brorand library throws an error.

jsdom lacks crypto: https://github.com/jsdom/jsdom/issues/1612. As a result, brorand/index (lines 30-50) looks for self.crypto and doesn't find it, concludes that we are on Safari, and throws an error.

This error can be avoided in one of two ways (so far): (1) Use node as the environment. (2) Install a monkey patch before the environment is set up (in a config file, not in the test file), like this:

import crypto from 'crypto';
self.crypto = crypto;
self.crypto.getRandomValues = (arr) => {
  crypto.randomBytes(arr.length);
};

This is really a Jest/jsdom issue but thought I'd document here for posterity!

Most helpful comment

If anyone needs a quickfix for that:

const crypto = require('crypto');
Object.defineProperty(global.self, 'crypto', {
  value: {
    getRandomValues: arr => crypto.randomBytes(arr.length),
  },
});

And then passing it to jest config should work:

"jest": {
    "setupFiles": ["fixCrypto.js"]
}

All 2 comments

There is an open PR for brorand about this (https://github.com/indutny/brorand/pull/5) but it's been stuck there for years now

If anyone needs a quickfix for that:

const crypto = require('crypto');
Object.defineProperty(global.self, 'crypto', {
  value: {
    getRandomValues: arr => crypto.randomBytes(arr.length),
  },
});

And then passing it to jest config should work:

"jest": {
    "setupFiles": ["fixCrypto.js"]
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

varcario picture varcario  路  5Comments

whyrusleeping picture whyrusleeping  路  3Comments

cristiano-belloni picture cristiano-belloni  路  5Comments

maroodb picture maroodb  路  3Comments

crazyrabbitLTC picture crazyrabbitLTC  路  6Comments