Jest: How to mock NativeEventEmitter constructor

Created on 2 Feb 2017  路  4Comments  路  Source: facebook/jest

Hi, We are using a third party react-native module that is using NativeEventEmitter calling:

const { RNBackgroundGeolocation } = require('react-native').NativeModules;
const EventEmitter = new NativeEventEmitter(RNBackgroundGeolocation);

Running jest, we got an error:

Invariant Violation: Native module cannot be null.

After investigating, it looks like this is happening because NativeEventEmitter is not mocked. However, most of the examples I found were using Linking.NativeEventEmitter and mock Linking.

I gave it a shot, trying to mock it, here is my setup.js:

jest.mock('Linking', () => {
  return {
    addEventListener: jest.fn(),
    removeEventListener: jest.fn(),
    openURL: jest.fn(),
    canOpenURL: jest.fn(),
    getInitialURL: jest.fn(),
  };
});

class MockNativeEventEmitter {
  addListener = () => jest.fn()
  removeListener = () => jest.fn()
  removeAllListeners = () => jest.fn()
}

jest.mock('NativeEventEmitter', () => MockNativeEventEmitter);

I'm just not sure this is the right way to do it

Most helpful comment

You need to do this:

jest.mock('NativeEventEmitter', () => {
  return class MockNativeEventEmitter {
    addListener = () => jest.fn()
    removeListener = () => jest.fn()
    removeAllListeners = () => jest.fn()
  }
})

All 4 comments

@Maxwell2022 i'm experiencing the same issue, how you fix this ?

@Maxwell2022 @shahen94 you ever figured out how to mock the NativeEventEmitter?

You need to do this:

jest.mock('NativeEventEmitter', () => {
  return class MockNativeEventEmitter {
    addListener = () => jest.fn()
    removeListener = () => jest.fn()
    removeAllListeners = () => jest.fn()
  }
})

@LeoLeBras it works for me thanks

Was this page helpful?
0 / 5 - 0 ratings