I am trying to mock DeviceEventEmitter
from react-native
using jest
. The actual code adds and removes a listener on component mount and unmount respectively. I have tried a lot of solutions but none of them worked.
These are few ways which I tried to mock.
// type 1
jest.mock('react-native/Libraries/EventEmitter/RCTDeviceEventEmitter', () => {
return {
addListener: mockAddListener,
remove: mockRemove
}
});
// type 2
jest.mock('react-native/Libraries/EventEmitter/RCTDeviceEventEmitter', () => {
const DeviceEventEmitter = jest.requireActual('react-native/Libraries/EventEmitter/RCTDeviceEventEmitter');
return DeviceEventEmitter;
});
Any suggestions?
After a lot of experiment in trying to mock this, finally the below mock worked.
// Make sure you are using the right path for node_modules depending on your test file location
jest.mock('../../node_modules/react-native/Libraries/vendor/emitter/EventEmitter', () => {
return class EventEmitter {
emit = jest.fn()
// Add other methods which ever you need to mock
};
});
So basically DeviceEventEmitter
extends EventEmitter
. So mocking EventEmitter
and implementing the required methods worked.