Partially mock `react-native` module

Viewed 575

I'm running unit tests in React Native that need the NativeEventEmitter and NativeModules mocked but leave everything else as passthrough to the real code.

This part seems to be working except when running I get this error.

    Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'DevSettings' could not be found. Verify that a module by this name is registered in the native binary.

      at invariant (../node_modules/invariant/invariant.js:40:15)
      at Object.getEnforcing (../node_modules/react-native/Libraries/TurboModule/TurboModuleRegistry.js:39:3)
      at Object.<anonymous> (../node_modules/react-native/Libraries/NativeModules/specs/NativeDevSettings.js:30:37)
      at Object.<anonymous> (../node_modules/react-native/Libraries/Utilities/DevSettings.js:10:1)

Mocking:

jest.mock(
  'react-native',
  () => ({
    ...jest.requireActual('react-native'),
    NativeEventEmitter: class MockNativeEventEmitter {
      // ...
    },
    NativeModules: {
      // ...
    },
    Platform: {
      OS: 'android',
    },
  })
);

Online searches for this error all point to problems compiling in dev vs release mode, nothing remotely close to what I'm trying to do.

1 Answers

Have you tried importing DevSettings from react-native and adding the same imported module in your mock? This would be the process for every Component/Module being used in your tested component. Something like:

import { DevSettings } from 'react-native`

jest.mock(
  'react-native',
  () => ({
    ...jest.requireActual('react-native'),
    NativeEventEmitter: class MockNativeEventEmitter {
      // ...
    },
    NativeModules: {
      // ...
    },
    Platform: {
      OS: 'android',
    },
    DevSettings
  })
);
Related