Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock useNavigation hook in react-navigation 5.0 for jest test?

i want to mock useNavigation hook used inside my functional component. Any workaround how to mock it using jest?

import React from 'react';
import { useNavigation } from '@react-navigation/native';
import { TouchableOpacity } from 'react-native';

const MyComponent = () => {
  const { navigate } = useNavigation();

  const navigateToScreen = () => {
    navigate('myScreen', { param1: 'data1', param2: 'data2' })
  }

  return (<TouchableOpacity onPress={navigateToScreen}>
       Go To Screen
     </TouchableOpacity>)
}

how to test params being passed in navigate function ?

like image 815
Renish Ghetia Avatar asked May 13 '20 17:05

Renish Ghetia


1 Answers

I know I'm late, but I had the issue where I needed to know know when the navigate function was called.

For it, I mocked the function the following way, so the mockedNavigate would be a jest function that i could use later if i needed to test if the function was actually called:

const mockedNavigate = jest.fn();

jest.mock('@react-navigation/native', () => {
  const actualNav = jest.requireActual('@react-navigation/native');
  return {
    ...actualNav,
    useNavigation: () => ({
      navigate: mockedNavigate,
    }),
  };
});

This allowed me to use this later and I would know if I could navigate properly in my application:

expect(mockedNavigate).toHaveBeenCalledTimes(1);

Hope this helps.

like image 125
josepholiveira Avatar answered Sep 20 '22 09:09

josepholiveira