Finding a TabNavigator tab item with detox in React Native

血红的双手。 提交于 2019-12-11 02:32:45

问题


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) 😀 https://github.com/wix/detox/blob/master/docs/Troubleshooting.RunningTests.md#debug-view-hierarchy

Basically, react native creates a native layout, and Detox is trying to match views from that native layout. In order to examine the layout hierarchy you need to use the tools provided by each platform.

For iOS, use Debug View Hierarchy
For Android, use Hierarchy Viewer



来源:https://stackoverflow.com/questions/49103465/finding-a-tabnavigator-tab-item-with-detox-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!