Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test react-native files in jest/enzyme which contain the useIsFocussed() navigation hook?

I have created a container in react-native and have added animations to the screen. For checking if the screen is focused or not, I am using the useIsFocussed hook from @react-navigation/native library.

const isFocused = useIsFocused()
  useEffect(() => {
    if (isFocused) {
      pulse()
    } else {
      posAnim.setValue({ x: Width, y: 0 })
      fadeModal.setValue(0)
      posModal.setValue({ x: 0, y: (50 / 812) * Height })
    }
  }, [isFocused])

In the code above, if the boolean isFocused is true, animation works and if its false(screen not focused) the animated components reset. I am also testing this screen using jest/enzyme. Below is the code for the screen test

const createTestProps = () => ({
  navigation: {
    navigate: jest.fn()
  }
})
describe('Screen', () => {
  let wrapper
  let props
  beforeEach(() => {
    props = createTestProps({})
    wrapper = shallow(<Screen {...props} />) // no compile-time error
  })
  it('should match to snapshot', () => {
    expect(wrapper).toMatchSnapshot()
  })
  it('Navigate ', () => {
    wrapper.find(TouchableOpacity).at(0).props().onPress()
    expect(props.navigation.navigate).toHaveBeenCalledWith('Screen2')
  })
})

But on running the test, I am facing this issue

 Couldn't find a navigation object. Is your component inside a screen in a navigator?

Can anyone tell me how to resolve this error?

like image 972
Sudipta_Pradhan Avatar asked Jun 22 '20 06:06

Sudipta_Pradhan


1 Answers

Calling the useIsFocused() hook fails because the component isn't wrapped in a <NavigationContainer>.

Try mocking @react-navigation/native by adding jest.mock('@react-navigation/native'); after the import statements in the test file. Also ensure that you have followed the guidelines at https://reactnavigation.org/docs/testing/ .

like image 167
Lauri Harpf Avatar answered Sep 19 '22 11:09

Lauri Harpf