How to call const function in functional component react native?

32 Views Asked by At
const goToLoginPage = () => {       
  navigation.navigate(AppConstants.LOGIN_SCREEN)
});

<TouchableOpacity onPress={goToLogin}>
  <Text>OK</Text>
</TouchableOpacity>   

how to call this method using Jest ?

1

There are 1 best solutions below

0
Mister_CK On

You'll need to mock navigation to be able to check if it was called

// Mock the useNavigation hook to return a navigation object
const mockNavigation = jest.fn();
jest.mock('@react-navigation/native', () => {
  const actualNavigation = jest.requireActual('@react-navigation/native');
  return {
    ...actualNavigation,
    useNavigation: () => ({
      navigate: mockNavigation,
    }),
  };
});

it('test if callback is being called', () => {
  // GIVEN
  render(
    <NavigationContainer>
      <theComponent>
    </NavigationContainer>
  )
  const button  = screen.getByText('OK')

  //WHEN
  fireEvent.press(button)

  //THEN
  expect(mockNavigation).toHaveBeenCalledWith(AppConstants.LOGIN_SCREEN)
})