1

I try mock the module NativeModules in react-native.

To avoid copying and pasting at each test, I try to create a 'mocks/react-native.js' file where I mock the module in question. I found this tutorial which helps to do but it doesn't work https://altany.github.io/react-native/0.61/jest/mocking/upgrade/2020/01/25/mocking-react-native-0.61-modules-with-jest.html

here is my mock file

import * as ReactNative from 'react-native';

export const NativeModules = {
  ...ReactNative.NativeModules,
  SettingsManager: {
    settings: {
      AppleLocale: 'en_US',
    },
  },
};

export const Platform = {
  ...ReactNative.Platform,
  OS: 'ios',
  Version: 123,
  isTesting: true,
  select: (objs) => objs.ios,
};

export const keyboardDismiss = jest.fn();
export const Keyboard = {
  dismiss: keyboardDismiss,
};

export default Object.setPrototypeOf(
  {
    NativeModules,
    Platform,
    Keyboard,
  },
  ReactNative,
);

here is the errors produced :

TypeError: Cannot read property 'create' of undefined

      1 | import {StyleSheet} from 'react-native';
      2 | 
    > 3 | export default StyleSheet.create({

TypeError: Cannot read property 'get' of undefined

do you know of another way to simulate the NativeModules module using the mock file ? or do you know how to solve these errors?

diego
  • 408
  • 8
  • 21

1 Answers1

0

The mock should define * import, not default. And ES module * export cannot be defined programmatically.

This should to be done by using CommonJS modules, and there's no need to do this with prototype inheritance:

const ReactNative = require('react-native');
...
module.exports = {
  ...ReactNative,
  __esModule: true,
  NativeModules,
  Platform,
  Keyboard,
};
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 1
    I have adapted my mock to your example but I have this error that occurs. `Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'DevSettings' could not be found. Verify that a module by this name is registered in the native binary.` I don't understand how to solve – diego Sep 08 '20 at 16:00
  • 1
    Was it workable without the mock? The answer addresses the problem with Jest mocking, I can't guarantee that RN will be workable with these mocks, as it may require a good understanding of RN internals to mock it the right way. As for the error, it seems to be common, https://stackoverflow.com/questions/59713472/invariant-violation-turbomoduleregistry-getenforcing-devsettings-could – Estus Flask Sep 08 '20 at 16:10