User event testing

I use Jest and Enzyme for my tests. I have no problems testing ordinary events, but I try my best to find the right approach to how to trigger and test events inside 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'm not sure about testing how I go, actually sending an event. So, for example, I have my own module when the user shakes the device. Inside the component itself, this is configured as follows:

 shakeEvents: ['shaken], deviceShakeEmitter: {}, componentDidMount() { this.deviceShakeEmitter = new NativeEventEmitter(Shake) this.deviceShakeEmitter.addListener('shaken', this['shaken']) }, 

I know that for embedded events, I can use jest.simulate ('press'), etc., but for a custom event, I am struggling to understand how I approach this in tests.

+5
source share
1 answer

I also wanted to do this, and I managed to find a solution in the Github registry with a reaction. They use the regular JS EventEmitter to mock the 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 customize the layout and create an instance of this emitter to send any event that you like:

 jest.mock('NativeEventEmitter'); const nativeEmitter = new NativeEventEmitter(); nativeEmitter.emit('SomeEventYouListenTo'); 
0
source

Source: https://habr.com/ru/post/1269584/


All Articles