Finding a TabNavigator tab item with detox in Reac

2019-07-22 06:00发布

问题:

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.

回答1:

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



回答2:

It's all in the docs (almost)