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
You can use jest. spyOn(object, methodName) to mock crypto.
Jest was created by Facebook engineers for its React project. Unit testing is a software testing where individual units (components) of a software are tested. The purpose of unit testing is to validate that each unit of the software performs as designed. A unit is the smallest testable part of any software.
For your NodeJS applications, Jest can be used for Unit Testing.
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) } });
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"], };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With