Check if navigation.navigate is called in react native testing

I've been using 'react-test-renderer' for testing react-native, Mostly on it's functions. Lately I've found out that there is a testing library for react-native which is @testing-library/react-native. What I wanted to do is to check if navigation.navigate or alert has been called in a function. I don't know which of these libraries can achieve that and how.

onSubmitPress = () => {
  if (true) {
  else { 
     showAlert( "Not Allowed);

1 answer

  • answered 2020-06-02 11:59 B. Mohammad

    You can use 'react-test-renderer':

    like this:

    const fakeNavigation = {
      navigate: jest.fn(),
    const tree = renderer.create(
            <YourComponent navigation={fakeNavigation}  />

    after that you can use jest expect function to test if mock navigation.navigate is called someThing like this:

    const instance = tree.getInstance();

    for react-native-testing-library it's a bit different as you test mostly what user sees depending of the behavior of your component.

    Basically you look for your button that calls onSubmit and then use fireEvent from react-native-testing-library to press it, after that you expect the text of your alert to be shown in screen or not.

    If you have a button like this in your component=

    <TouchableOpacity onPress={onSubmit}>

    You can test the behavior of you function like this:

    const {getByText} = render(<YourComponent/>)
    let buttonText = getByText('Submit');
    fireEvent(buttonText.parent, 'press'); //parent to get to TouchabalOpacity
    alertText = getByText('Not Allowed');