Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6208

How to verify that navigation has been called or not in react native testing?

$
0
0

Here is my code

component.tsx

export function myComponent(navigation: Navigation) {

   // some logic...

   return (
     <TouchableWithoutFeedback 
        testID="notificationCard"
        onPress={() => navigation.navigate(NEW_ROUTES.profile, { id: rawId })}
              >
        <Card style={styles.stackedCard} ></Card>
    <TouchableWithoutFeedback />

  )
} 

Here I need to verify the navigate function that has been called or not, when tap on TouchableWithoutFeedback But I am not able to get the navigation

component.test.tsx

const { environment, getByTestId, navigationTestRenderer } = renderWithNavigation(myComponent);
  const notificationCards = getByTestId("notificationCards");
  const notificationCard = getAllByTestId(notificationCards, "notificationCard");
  fireEvent.press(notificationCard[0]);
  // no idea about next line, here I am getting some *NavigationContainer* don't know what to do with this
  expect(navigationTestRenderer).toHaveBeenCalled();

navigationTestRenderer :

{ [Function: NavigationContainer]
      router:
       { childRouters: { ROUTE: null },
         getComponentForState: [Function: getComponentForState],
         getComponentForRouteName: [Function: getComponentForRouteName],
         getActionCreators: [Function: getActionCreators],
         getStateForAction: [Function: getStateForAction],
         getPathAndParamsForState: [Function: getPathAndParamsForState],
         getActionForPathAndParams: [Function: getActionForPathAndParams],
         getScreenOptions: [Function] },
      navigationOptions: null,
      defaultProps: { theme: 'light' } }

expected result will be like below

  expect(navigation).toHaveBeenCalled() or expect(navigation).toHaveBeenCalledWith("home")

helper.tsx

import { render } from "@testing-library/react-native";

export function renderWithNavigation(
  screen: React.FC<{ readonly navigation: NavigationScreenProp<NavigationRoute> }>,
) {
  const AppNavigationStack = createStackNavigator(
    { ROUTE: { screen } },
    { initialRouteName: "ROUTE" },
  );

  const environment = createMockEnvironment();
  const App = createAppContainer(AppNavigationStack);

  return {
    ...render(
      <ReactRelayContext.Provider value={{ environment, variables: {} }}>
        <App detached />
      </ReactRelayContext.Provider>,
    ),
    environment,
    navigationTestRenderer: App,
  };
}

Viewing all articles
Browse latest Browse all 6208

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>