Error Cannot read property 'getRandomBase64' of undefined when running test file

Viewed 2323

I try use package uuid and react native get random values to create random uuid. Everything is fine and working. But when I try run my test file using jest, and I get an error Cannot read property 'getRandomBase64' of undefined. How to solve this error?

Thanks.

enter image description here

4 Answers

react-native-get-random-values is a native module, so you need to mock it when running unit tests.

One way to do it is as follow: Go to your __mocks__ folder (or create it in the root of the project if it's not there) and place a file named react-native-get-random-values.js (the name is important) with the following content:

export default {
  getRandomBase64: jest.fn().mockImplementation(() => {
    console.log("getRandomBase64 mock called");
    return "mockedBase64";
  })
};

To learn more about mocking an entire module, read the Jest docs

I encountered the same problem but none of the response above worked for me.

Adding this mock on the top of my test file solved the issue:

jest.mock('react-native-get-random-values', () => ({
  getRandomBase64: jest.fn(),
}));

Solution found by aav7fl on this GitHub issue.

I know this question is 5 months old, but it may help other people.

Try import 'react-native-get-random-values' in root app

import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import '@react-native-firebase/crashlytics';
import 'react-native-get-random-values';
console.disableYellowBox = true
AppRegistry.registerComponent(appName, () => App);

This is link issue https://github.com/react-native-webview/react-native-webview/issues/1312

Finally I can fixing this error by adding react native get random values and uuid inside transform ignore pattern in my package.json file, something like this.

"transformIgnorePatterns": [
      "/node_modules/(?!native-base|@react-native-community/netinfo|@react-native-community/async-storage|@react-native-community/geolocation|react-native-permissions|uuid|react-native-get-random-values)/"
    ]
Related