Today I Learned

4 posts about #react-native

Jest.js haveBeenCalledWith anything()

Sometimes we want to check if the callback has been called with some arguments, but providing all of them can be hard (some nested structure with other callbacks, etc.)

We can check however some of the calling arguments and replace rest with expect.anything()

  it('should trigger confirmation when clicking on report lost button', () => {
    const { container, getByTestId } = render(<ReportScreen />);
    Alert.alert = jest.fn();
    const reportLostButton = getByTestId('reportLostButton');
    act(() => {
      fireEvent.press(reportLostButton);
    })
    expect(Alert.alert).toHaveBeenCalledWith(
      'Report as lost', 
      expect.anything(), 
      expect.anything(), 
      expect.anything()
    );
  });

Dealing with TabBar scenes

When we are using react-navigation for navigation in our React-Native app, often we use TabBar Navigator, because of the simplicity. But unfortunately sometimes it brings restrictions. Main one: Every Tab is mounted from begining and will never unmount by default.

To handle Tab changes we can use less known listeners which helps very much in building smooth and user-friendly apps:

componentDidMount() {
  this._navListener = this.props.navigation.addListener('willBlur', () =>
    this.scrollView.scrollTo({ x: 0, animated: true }),
  )
}

componentWillUnmount() {
  this._navListener.remove()
}

Docs reference

P.S. Always remember to remove listeners incase of memory leak :)

Always remember to remove listeners with MobileApp

It’s good practice to remember about EventListeners, especially in mobile apps. Just a few additional lines give you several times less probability to crash the app.

const onLogOut = () => {
  if (Platform.OS === 'ios') {
    PushNotificationIOS.removeEventListener('notification')
    PushNotificationIOS.removeEventListener('register')
  } else {
    androidNotificationListeners.map(listener => listener.remove())
  }
}