Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a TabNavigator tab item with detox in React Native

I'm using react-navigation in my React Native project that I'm setting up automated testing for using Detox.

Unfortunately, I don't see anything in the docs about how to tell detox to find (and then of course tap) the Tab of a Tab Navigator.

I tried looking through component tree using react-devtools, but couldn't figure out which element represented the tab button itself.

I also tried finding the element by it's text like so:

await element(by.text('My Tab Button')).tap();

but that through a 'Cannot find UI element' error.

Thanks for any help anyone can offer.

like image 641
evanmcd Avatar asked Dec 24 '22 09:12

evanmcd


2 Answers

I had a similar issue when using react-navigation in my app. I am currently using react-navigation 2.2.0.

Firstly I tried the following:

await element(by.label('Tab Name')).tap();

This worked and I was quite happy until I tried a different tab to go to, where the tab name matched a text item on the page, this meant there were two labels with the same text and Detox got confused. So using by.label is only useful when you can guarantee that there is one instance of that label on the page.

The way I found to get around this was to set the tabBarTestID navigations options for the screen. As long as you use unique ids then there should be no collisions.

Setting the tabBarTestID can be done like so in your screen component:

class TabScreen extends Component {

  static navigationOptions = () => {
    return {
      title: 'Tab Name',
      tabBarLabel: 'Tab Name',
      tabBarAccessibilityLabel: 'Tab Name',
      tabBarTestID: 'Tab Name',
      tabBarIcon: ({ tintColor, focused }) => {
        return getTabIcon('Tab Name', focused);
      }
    };
  };

  render () {
    return (
      <View>
       ...
      </View>
    );
  }
}

export default TabScreen;

This means you should should now be able, in your tests, to use:

await element(by.id('Tab Name')).tap();

like image 94
Andrew Avatar answered Dec 25 '22 23:12

Andrew


In case you are adding in the wrong place, try moving it to createBottomTabNavigator

  createBottomTabNavigator(
    {
      YourStackLabel: {
        screen: YourStackNavigator,
        navigationOptions: {
          tabBarTestID: "yourBottomBarButtonTestId",
        },
      },
    }
  );
like image 21
ofundefined Avatar answered Dec 25 '22 23:12

ofundefined