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?
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/ .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With