15

As I understand it should be done so that useFocusEffect would work as useEffect for testing (mock). I use useFocusEffect for fetchData:

useFocusEffect(
  useCallback(() => {
    fetchData();
  }, [fetchData]),
);

Error message: react-navigation hooks require a navigation context but it couldn't be found. Make sure you didn't forget to create and render the react-navigation app container. If you need to access an optional navigation object, you can useContext(NavigationContext), which may return

Package versions:

"jest": "^24.9.0",
"react-native": "0.61.2",
"react-navigation": "^4.0.10",
"react-navigation-hooks": "^1.1.0",
"@testing-library/react-native": "^4.0.14",
Vasyl Nahuliak
  • 1,912
  • 2
  • 14
  • 32

7 Answers7

18

Assuming you're rendering your component in your test, you need to wrap it in a fake <NavigationContext>. Doing so lets useFocusEffect look up the things it needs to determine if the component has been focused by your app's navigation.

This example uses render from react-native-testing-library. I think it's analogous to other rendering methods though.

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

// fake NavigationContext value data
const navContext = {
  isFocused: () => true,
  // addListener returns an unscubscribe function.
  addListener: jest.fn(() => jest.fn())
}

// MyComponent needs to be inside an NavigationContext, to allow useFocusEffect to function.
const { toJSON } = render(
  <NavigationContext.Provider value={navContext}>
    <MyComponent />
  </NavigationContext.Provider>
)
meshantz
  • 1,566
  • 10
  • 17
5

This is just a fuller version of the above answer from @meshantz.

import { NavigationContext } from '@react-navigation/native';
import { render } from '@testing-library/react-native';
import React from 'react';

// This would probably be imported from elsewhere...
const ComponentUnderTest = () => {
  useFocusEffect(
    useCallback(() => {
      fetchData();
    }, [fetchData]),
  );
  
  return null;
};

const mockFetchData = jest.fn();
jest.mock('fetchData', () => mockFetchData);

describe('testing useFocusOnEffect in ComponentUnderTest', () => {
  afterAll(() => {
    jest.restoreAllMocks();
  });

  describe('when the view comes into focus', () => {
    it('calls fetchData', () => {
      const navContextValue = {
        isFocused: () => false,
        addListener: jest.fn(() => jest.fn()),
      };

      render(
        <NavigationContext.Provider value={navContextValue}>
          <ComponentUnderTest />
        </NavigationContext.Provider>,
      );

      expect(mockFetchData).toBeCalledTimes(0);

      render(
        <NavigationContext.Provider
          value={{
            ...navContextValue,
            isFocused: () => true,
          }}
        >
          <ComponentUnderTest />
        </NavigationContext.Provider>,
      );

      expect(mockFetchData).toBeCalledTimes(1);
    });
  });
});

ourmaninamsterdam
  • 1,915
  • 15
  • 11
  • I'm getting the error ```TypeError: navigation.isFocused is not a function```. @meshantz. can you pls advise. – Brad Apr 20 '21 at 23:48
  • Updates: My apologies, it is working. What i did was mocking the react which is this ```jest.mock('react', () => ({ ...jest.requireActual('react') useContext: () => { user: 'sdfsf' } }));``` This turned out to be detrimental to what it is expected. Hence removing that, helped. Thanks for the solution @meshantz. – Brad Apr 21 '21 at 01:21
  • 2
    This is awesome! Thanks a lot. Do you know how to write this with typescript? I tried but then navContext is missing some types like: dispatch, navigate, reset, goBack. – cinemanja May 27 '21 at 08:05
  • 1
    @mohwarf to satisfy the TypeScript compiler you'll either have to add those properties (you can stub them out) to `navContextValue`, or just add any properties you want to use/mock in your test then cast `const navContextValue` like so `const navContextValue = { ... } as NavigationContext` which will stop you seeing the types message. The former is probably a better option but I sometimes to do the latter. – ourmaninamsterdam May 27 '21 at 20:52
3

For TypeScript, it is also required to satisfy type requirements as well, so in my case, it was done by using jest.requireActual:

    const withProvider = (element, store = defaultStore) => {
      // fake NavigationContext value data
      const actualNav = jest.requireActual("@react-navigation/native");
      const navContext = {
        ...actualNav.navigation,
        navigate: () => {},
        dangerouslyGetState: () => {},
        setOptions: () => {},
        addListener: () => () => {},
        isFocused: () => true,
      };
      return (
        <NavigationContext.Provider value={navContext}>
          <MyComponent />
        </NavigationContext.Provider>
      );
    };
    
    it("renders correctly", () => {
      render(withProvider(() => <SportsBooksScreen {...defaultProps} />));
    });
Omer Gurarslan
  • 979
  • 11
  • 15
1

Instead of useFocusEffect, use useIsFocused with useEffect, and the code just works fine.

In Your component:

import React, { useEffect } from 'react';
import { useIsFocused } from '@react-navigation/native';

const Component = () => {
  const isFocused = useIsFocused();
useEffect(() => {
    if (isFocused) {
      fetchData();
    }
  }, [isFocused]);
  return (<><View testID="child_test_id">{'render child nodes'}</View></>)
}



For Testing:


import Component from '--path-to-component--';
jest.mock('--path-to-fetchData--');
jest.mock('@react-navigation/native', () => {
  return {
    useIsFocused: () => true
  };
});

it('should render child component when available', async () => {
  const mockedData = [];
  fetchData.mockImplementation(() => mockedData);
  let screen = null;
  await act(async () => {
    screen = renderer.create(<Component  />);
  });
  const childNode = screen.root.findByProps({ testID: 'child_test_id' });
  expect(childNode.children).toHaveLength(1);
});
Debabrata Nayak
  • 457
  • 4
  • 5
1

I had problems/limitations with proposed solutions in this thread, so I ended up mocking "useFocusEffect" with "React.useEffect".

It did the job well: my tests are green now!

jest.mock('@react-navigation/native', () => {
  const { useEffect } = require('react');
  const actualModule = jest.requireActual('@react-navigation/native');

  return {
    ...actualModule,
    useFocusEffect: useEffect,
  };
});
evasyuk
  • 325
  • 3
  • 11
  • Or mock mockImplementation `jest.mock('@react-navigation/native', () => ({ ...jest.requireActual('@react-navigation/native'), useFocusEffect: jest.fn().mockImplementation((func) => func()), }));` – Vasyl Nahuliak Apr 04 '22 at 19:28
-1

Create component FocusEffect

import { useFocusEffect } from "@react-navigation/native";
import { BackHandler } from "react-native";
import React from "react";

export default function FocusEffect({ onFocus, onFocusRemoved }) {
  useFocusEffect(
    React.useCallback(() => {
      onFocus();

      return () => onFocusRemoved();
    }, [onFocus, onFocusRemoved]),
  );
  return null;
}

Usage Example :

import React from 'react';
import { Text, View } from 'react-native';
import { FocusEffect } from './components';
    
const App = () => {

onFocus = () => {
   // ============>>>> onFocus <<<<==============
   fetchData();
};

onFocusRemoved = () => {
   // ============>>>> onFocusRemoved <<<<==============
};

return (
    <View>
       <FocusEffect
            onFocus={this.onFocus}
            onFocusRemoved={this.onFocusRemoved}
       />
       <Text>Hello, world!</Text>
   </View>
   )
}
export default App;
Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39
-2

If the code within useFocusEffect() is not consequential to your testing, you can mock the hook as follows:

jest.mock("@react-navigation/native", () => ({
  useFocusEffect: jest.fn(),
  // ...
}));
Hatchmaster J
  • 543
  • 1
  • 6
  • 15