Invariant Violation: new NativeEventEmitter()

Started 10 months ago by John in React Native

react native test case error with new NativeEventEmitter error

Body

Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.

__tests__/App-test.tsx
  ● Test suite failed to run

    Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.

       5 | import {useSafeAreaInsets} from 'react-native-safe-area-context';
       6 | // import RoundIconButton from "./RoundIconButton";
    >  7 | import DeviceInfo from 'react-native-device-info';
         | ^
       8 | const isIphoneX = DeviceInfo.hasNotch();

      at invariant (node_modules/invariant/invariant.js:40:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:46:16)      at Object.<anonymous> (node_modules/react-native-device-info/lib/commonjs/internal/asyncHookWrappers.ts:29:34)
      at Object.require (node_modules/react-native-device-info/lib/commonjs/index.ts:3:1)
      at Object.require (src/component/molecule/Header/TopHeaderContent.tsx:7:1)
      at Object.require (src/component/molecule/index.tsx:9:1)
      at Object.require (src/screens/main/Homescreen/index.tsx:108:1)
      at Object.require (__tests__/App-test.tsx:5:1)

1 Replies

  • Replied 10 months ago

    Report

    Create a __mocks__ directory: In your project's root directory, create a __mocks__ directory. Inside it, create a file named react-native-device-info.js

    // __mocks__/react-native-device-info.js
    
    const DeviceInfo = jest.genMockFromModule('react-native-device-info');
    
    DeviceInfo.hasNotch = jest.fn().mockReturnValue(false); // Mock the hasNotch function to return false
    
    module.exports = DeviceInfo;
    

     

    Configure Jest to use the mocks: Ensure that Jest is configured to use the __mocks__ directory. In your package.json, add or update the jest section:

    "jest": {
      "preset": "react-native",
      "moduleNameMapper": {
        "^react-native-device-info$": "<rootDir>/__mocks__/react-native-device-info.js"
      }
    }