J. Hesters
J. Hesters

Reputation: 14768

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.

Upvotes: 3

Views: 2671

Answers (2)

iWorld
iWorld

Reputation: 113

This is more like an addition to the solution above. If you want to test let's say onPress event on nav header buttons. You can access them without any problems, in addition to the above solution just do something like this:

navigationOptions.headerLeft.props.onPress()

Upvotes: 1

Moyote
Moyote

Reputation: 1217

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();
});

Upvotes: 9

Related Questions