Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 311
CoderLee Avatar asked Oct 02 '18 15:10

CoderLee


People also ask

How do you mock crypto?

You can use jest. spyOn(object, methodName) to mock crypto.

What is Jest test function?

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.

Can Jest be used for node JS?

For your NodeJS applications, Jest can be used for Unit Testing.


2 Answers

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 image 115
Hardik Modha Avatar answered Sep 16 '22 15:09

Hardik Modha


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"], }; 
like image 44
mitchelc Avatar answered Sep 19 '22 15:09

mitchelc