brix / crypto-js

JavaScript library of crypto standards.
Other
15.89k stars 2.39k forks source link

Unit Test: Jest Mock Failed 'Cannot read property 'toString' of undefined' #381

Open rafameyer opened 3 years ago

rafameyer commented 3 years ago

I'm trying to create a unit test to test some functions from my projects

Screen Shot 2021-09-22 at 10 41 51

My jest mock config is here:

function mockCrypto() {
  return {
    AES: {
      encrypt: jest
        .fn()
        .mockImplementation(() => Math.random().toString(36).substr(3, 6)),
      decrypt: jest
        .fn()
        .mockImplementation(() => Math.random().toString(36).substr(3, 6)),
    },
    enc: {
      Utf8: jest.fn(),
      Base64: jest.fn(),
    },
    lib: {
      WordArray: {
        random: jest.fn(),
        toString: jest.fn().mockImplementation(() => CryptoJS.enc.Base64),
      },
    },
    buffer: {
      toString: jest.fn().mockImplementation(() => CryptoJS.enc.Base64),
    },
  };
}

The problem is about this method, specifically with buffer.toString(CryptoJS.enc.Base64);

const generateRandomBytes = () => {
  const buffer = CryptoJS.lib.WordArray.random(96);
  return buffer.toString(CryptoJS.enc.Base64);
};

How can I mock this functionality?

VIjayGunaraj commented 5 months ago

if you mock the implementation of random then it works fine.

For Example below code random: jest.fn().mockImplementation(() => { return 2; //or return Math.random(); }),