I am using Jest and Enzyme for my tests. I have no problem testing normal events but I am struggling to find the correct approach for how to trigger and test events within components that come from Native Modules. In my Jest setup I have the following:
jest.mock('NativeEventEmitter', () => class MockNativeEventEmitter{
addListener = () => jest.fn()
removeListener = () => jest.fn()
removeAllListeners = () => jest.fn()
});
However, I am not sure within the test how I go about actually dispatching an event. So, for example I have a Native module for when the user shakes the device. Within the component itself this is setup like so:
shakeEvents: ['shaken],
deviceShakeEmitter: {},
componentDidMount() {
this.deviceShakeEmitter = new NativeEventEmitter(Shake)
this.deviceShakeEmitter.addListener('shaken', this['shaken'])
},
I know for inbuilt events i can use jest.simulate('press') etc, but for the custom event I am struggling to understand how I approach this within the tests.
I wanted to do this as well, and I managed to find the solution in the react-native Github repo. They use the normal JS EventEmitter to mock NativeEventEmitter:
const EventEmitter = require('EventEmitter');
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
/**
* Mock the NativeEventEmitter as a normal JS EventEmitter.
*/
class NativeEventEmitter extends EventEmitter {
constructor() {
super(RCTDeviceEventEmitter.sharedSubscriber);
}
}
Now you just need to setup the mock, and instantiate this emitter to send out any event you like:
jest.mock('NativeEventEmitter');
const nativeEmitter = new NativeEventEmitter();
nativeEmitter.emit('SomeEventYouListenTo');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With