React-native - Jest test failing upon use of useFocusEffect() - error Couldn't find a navigation object. Is your component inside NavigationContainer?

Viewed 27

I've modified an existing react-native program. I've added useFocusEffect() hook to fetch data in a screen upon returning from another screen (child component). The program works as expected, however, previously written Jest test cases are failing with the following:

Home › should render screen without error
Couldn't find a navigation object. Is your component inside NavigationContainer?
> 24 |   useFocusEffect(
     |   ^
  25 |     React.useCallback(() => {
  26 |       fetchData();
  27 |     }, [fetchData])

Related test is as follows:

import { Home } from './Home';

jest.mock('hooks/Auth/useLoadAuthStudentsData', () => ({
  useLoadAuthStudentData: jest.fn()
}));

jest.mock('hooks/Student/useStudents', () => ({
  useStudents: jest.fn()
}));

jest.mock('@react-navigation/core', () => {
  return {
    ...jest.requireActual('@react-navigation/core'),
    useNavigation: jest.fn(() => ({}))
  };
});

const useLoadAuthStudentsData = userHook as ReturnType<typeof jest.fn>;
const useStudents = tasksHook as ReturnType<typeof jest.fn>;

  describe('Home', () => {
  beforeEach(() => {
    useStudents.mockReturnValue({
      data: Student.deserializeAsList(studentsStub),
      isLoading: false,
      isSuccess: true,
      isError: false
    });
    useLoadAuthUserData.mockReturnValue({ data: studentStub });
  });

  it('should render screen without error', () => {
    expect(render(<Home />)).toBeTruthy();
  });

  it('should render loader if data is loading', () => {
    useStudents.mockReturnValue({
      data: undefined,
      isLoading: true,
      isSuccess: undefined,
      isError: undefined
    });

    const { getByTestId } = render(<Home />);

    expect(getByTestId('students-layout')).toBeTruthy();
  });
1 Answers

Can you please try changing this:

jest.mock('@react-navigation/core', () => {
  return {
    ...jest.requireActual('@react-navigation/core'),
    useNavigation: jest.fn(() => ({}))
  };
});

to:

jest.mock('@react-navigation/native', () => {
  return {
    ...jest.requireActual('@react-navigation/native'),
    useNavigation: jest.fn(() => ({}))
  };
});

if that's not enough then make sure the screen is wrapped in a navigation container and navigator, since the hook relies on the component being part of the navigation stack

Related