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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With