Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test static navigationOptions with Jest and Enzyme while using React Navigation and TypeScript?

I'm building a React Native app with TypeScript. I'm doing my component tests using Jest and Enzyme. I'm also using React Navigation.

One of my screens has the following navigationOptions:

static navigationOptions = ({ navigation }: NavigationScreenProps) => ({
headerLeft: Platform.select({
  android: (
    <Icon
      name="md-menu"
      type="ionicon"
      containerStyle={styles.icon}
      onPress={navigation.toggleDrawer}
    />
  ),
  ios: null
}),
headerTitle: strings.homeTitle

});

I want to write unit test ensuring that the <Icon /> component gets rendered. Similar to here:

const props = createTestProps({});
const wrapper = shallow<HomeScreen>(<HomeScreen {...props} />);

it("should render a <View />", () => {
  expect(wrapper.find(View)).toHaveLength(1);
});

My problem is, I can't figure out the selector to select it. How can I select static navigationOptions?

I also tried going over the wrapper like this:

expect(wrapper.instance().navigationOptions)

But the wrapper's instance does not have the navigationOptions.

like image 303
J. Hesters Avatar asked Dec 09 '25 17:12

J. Hesters


1 Answers

Since its static function, you can call it without creating a new instance.

test('navigation options', () => {
  const naviProp = { navigation: { navigate: () => {} } };
  const navigationOptions = HomeScreen.navigationOptions(naviProp);

  expect(navigationOptions).toMatchSnapshot();
});
like image 94
Moyote Avatar answered Dec 12 '25 11:12

Moyote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!