Skip to content

How to handle navigating by reference for react-navigation tests #750

@matt-dalton

Description

@matt-dalton

We've set-up out navigation using these docs here, so that we can call the navigation function imperatively (e.g. from middleware functions etc).

In RootNavigation component, we set this up like this (note setting the ref on the NavigationContainer):

const RootNavigator = () => {
      const setNavRef = useCallback((ref: NavigationContainerRef) => {
        if (ref) {
            setTopLevelNavigator(ref)
        }

    }, [])


  return (
     <NavigationContainer ref={setNavRef}>
             <RootStack.Navigator>
                    <RootStack.Screen
                        name="RootCards"
                        component={RootCardNavigator}
                    />
              </RootStack.Navigator>
     </NavigationContainer>
  )
}

I've then tried to recreate this in the tests:

const setNavRef = ref => {
            if (ref) {
                setTopLevelNavigator(ref)
            }
        }
const component = (
                        <NavigationContainer ref={setNavRef}>
                            <RootCardNavigator {...props} />
                        </NavigationContainer>
        )

const { findByText, findByTestId, toJSON, debug } = render(component)

const button = await findByTestId('applanding-nextbtn')
fireEvent(button, 'press')
//...test we're on the next screen

This actually works (we go to the next screen and the test passes), however I get this warning:

Warning: An update to CardContainer inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */
    
    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
        in CardContainer (created by CardStack)

I can hack round it by adding update(component) after the initial render in the tests, but is there a more elegant way to handle this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions