Search code examples
unit-testingreact-nativejestjs

How to unit test PanResponder in React Native?


I am working on a React Native component handling gestures via PanResponder.

I would like to test that when certain dx, dy values are passed to the onPanResponderRelease method, expected action will be executed. Please find below an example of what I would like to test:

export default class MyComponent extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this._panResponder = this._initPanResponder();
  }

  _initPanResponder(): PanResponder {
    const panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderMove: Animated.event([
        null,
        { dx: this._animation.x, dy: this._animation.y }
      ]),
      onPanResponderRelease: (e, gestureState) => {
        const { dx, dy } = gestureState;

        if (dy > 100) {
          doSomething(); // <---- what I would like to unit test
        }
      }
    });
    return panResponder;
  }
}

Is there any straightforward way to unit test the following with Jest?


Solution

  • I tend to leave testing the wiring code out, since testing an actual PanResponder involves a UI test that is hard to write, is usually flaky, and gives little value.

    What you can do, is extract the event handling function out, and test it independently.

    In that case, the test would very simple, as all you need to do is invoke the handler in the test and see you're getting what you expected.