identify element

1.新建Home.js

檔案位於 root/app/Home.js

import React, { Component } from 'react';
import { StyleSheet, View, TextInput } from 'react-native';

export default class Home extends Component {

  render() {
    return (
      <View style={styles.wrapper}>
        <TextInput
          testID={'username'}
          style={{backgroundColor: 'gray', marginBottom: 35}} 
          placeholder={'Enter User Name'} />
        
        <TextInput
          testID={'password'}
          style={{backgroundColor: 'gray'}} 
          placeholder={'Enter Password'} />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  wrapper: {
    flex:1, 
    justifyContent: 'center'
  },
})

2.撰寫test case

1) 新建 root/__tests__/HomeIdentifyElement-test.js render Home組件後 toJSON,並且使用console.log印出內容,這樣我們才知道怎麼找到我們要的元件

2) 執行此test 可看到印出來的json,如下圖紅框內

3) 其中children就是我們所需要的,所以把 console.log(tree) 改為 console.log(tree.children) 執行test後如下圖

​ 4) 寫個 function(findElement) 去抓是否有指定的 testID 存在,HomeIdentifyEelement-test.js 完整如下

5)再次執行test,因為 'username'是存在的,所以會成功 可以自行嘗試修改 testID 的部分

參考

Last updated