2

NAVIGATOR

export type RootStackNavigator = {
   Welcome: undefined
   List: undefined
}

const Stack = createStackNavigator<RootStackNavigator>()
const { Navigator, Screen } = Stack

const Navigation = () => {
   return (
      <NavigationContainer>
         <Navigator initialRouteName={'Welcome'} headerMode="none">
            <Screen name="Welcome" component={Welcome} />
            <Screen name="List" component={List} />
         </Navigator>
      </NavigationContainer>
   )
}

WELCOME SCREEN

interface WelcomeProps {
   navigation: StackNavigationProp<RootStackNavigator, 'Welcome'>
}

const Welcome = ({ navigation }: WelcomeProps) => {
   return (
      <Screen style={styles.screen}>
         <TouchableWithoutFeedback onPress={() => navigation.navigate('List')} testID="touchable" style={styles.touchable}>
            etc ...
         </TouchableWithoutFeedback>
      </Screen>
   )
}

TEST

describe('Welcome Screen', () => {
   it('Navigates to List Screen when clicked', () => {
      const navigate = jest.fn()
      const { getByTestId } = render(<Welcome navigation={{ navigate }} />)
      fireEvent.press(getByTestId('touchable'))
      expect(navigate).toBeCalledWith('List')
   })
})

With all of this, I am getting this error from typescript:

Type '{ navigate: jest.Mock<any, any>; }' is not assignable to type 'StackNavigationProp<RootStackNavigator, "Welcome">'.

How can I solve this?

I am trying to test if I click in the screen the app renders the List Screen component.

Thank you.

PS: btw, the test is passing

1
  • I forgot to say that the test is passing anyway Commented Jun 1, 2021 at 17:44

1 Answer 1

1

I'm with the same problem. I found a way but I'm not confident that it's the best or right way.

What I do is add only the used functions from navigation prop. I did it using Pick like below:

type PrivateScreenProps = {
  navigation: Pick<
    StackNavigationProp<MainStackRoutesType, Navigation.MainRoutes.PRIVATE>,
    'navigate'
  >;
};

export const PrivateScreen = ({ navigation }: PrivateScreenProps) => {
}

This will only add in the navigation, the navigate function. So, in tests I only need to defined the navigate function inside navigation mock.

const navigation = {
  navigate: jest.fn(),
};

render(<PrivateScreen navigation={navigation} />);

If I need to use another function like goBack, I add it in the type:

type PrivateScreenProps = {
  navigation: Pick<
    StackNavigationProp<MainStackRoutesType, Navigation.MainRoutes.PRIVATE>,
    'navigate' | 'goBack'
  >;
};

// in tests
const navigation = {
  navigate: jest.fn(),
  goBack: jest.fn(),
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.