|
| 1 | +# Third-Party Library Integration |
| 2 | + |
| 3 | +React Native Testing Library (RNTL) is designed to simulate core React Native behaviors. |
| 4 | +However, it does not replicate the internal logic of third-party libraries. This guide |
| 5 | +explains how to integrate your library with RNTL. |
| 6 | + |
| 7 | +## Handling Events in Third-Party Libraries |
| 8 | + |
| 9 | +RNTL provides two subsystems for simulating events: |
| 10 | + |
| 11 | +- Fire Event: A lightweight event simulation system that can trigger event handlers defined on both host and composite components. |
| 12 | +- User Event: A more realistic interaction simulation system that can only trigger event handlers defined on host components. |
| 13 | + |
| 14 | +In many third-party libraries, event handling involves native code. In such cases, RNTL cannot |
| 15 | +fully simulate the event flow. To address this, you can use testOnly_onXxx props on host components |
| 16 | +to expose custom events to RNTL's event subsystems. Both subsystems will first attempt to locate the standard onEvent handlers. If these are not available, they will fall back to testOnly_onXxx handlers. |
| 17 | + |
| 18 | +### Example: React Native Gesture Handler |
| 19 | + |
| 20 | +React Native Gesture Handler (RNGH) provides a composite `Pressable` component with `onPress` props. |
| 21 | +These props are part of the library's internal event flow, which involves native modules and |
| 22 | +`EventEmitters`. As a result, they are not directly exposed to the host components rendered by |
| 23 | +`Pressable`, making them inaccessible to RNTL's event subsystems. |
| 24 | + |
| 25 | +To enable RNTL to interact with RNGH's `Pressable` component, the library exposes `testOnly_onPress` |
| 26 | +props on the `NativeButton` host component rendered by `Pressable`. This allows RNTL to simulate |
| 27 | +interactions during testing. |
| 28 | + |
| 29 | +```tsx title="Simplified RNGH Pressable component" |
| 30 | +function Pressable({ onPress, onPressIn, onPressOut, ... }) { |
| 31 | + // Component logic... |
| 32 | + |
| 33 | + const isTestEnv = process.env.NODE_ENV === 'test'; |
| 34 | + |
| 35 | + return ( |
| 36 | + <GestureDetector gesture={gesture}> |
| 37 | + <NativeButton |
| 38 | + { /* Other props... */ } |
| 39 | + testOnly_onPress={isTestEnv ? onPress : undefined} |
| 40 | + testOnly_onPressIn={isTestEnv ? onPressIn : undefined} |
| 41 | + testOnly_onPressOut={isTestEnv ? onPressOut : undefined} |
| 42 | + /> |
| 43 | + </GestureDetector> |
| 44 | + ); |
| 45 | +} |
| 46 | +``` |
0 commit comments