# 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

&#x20; 1\) 新建 root/\_\_tests\_\_/HomeIdentifyElement-test.js\
render Home組件後 toJSON，並且使用console.log印出內容，**這樣我們才知道怎麼找到我們要的元件**

```
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import Home from '../app/Home.js';

it('Identify Element in Home.js', ()=>{
    let tree = renderer.create(<Home />).toJSON();
    console.log(tree);
});
```

&#x20; 2\) 執行此test\
可看到印出來的json，如下圖紅框內

![](https://703864731-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGT_WSMJJJ-6nRhUva4%2F-LHSVo7XFp0eN-JO-P3D%2F-LHSXNgeSefYAo5i9yZK%2Fimage.png?alt=media\&token=e3754413-0b40-4bfd-a00d-ffeba1f93a01)

&#x20; 3\) 其中children就是我們所需要的，所以把 console.log(tree) 改為 **console.log(tree.children)**\
執行test後如下圖

![](https://703864731-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGT_WSMJJJ-6nRhUva4%2F-LHSVo7XFp0eN-JO-P3D%2F-LHSYHSo8iGYxhBs8ffw%2Fimage.png?alt=media\&token=22695cbc-220e-4115-8157-71edf628821b)

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

```
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import Home from '../app/Home.js';


let findElement = function(tree, element){
  for(node in tree.children){
      if(tree.children[node].props.testID == element)
        return true;
  }
  return undifined;
};

it('Identify Element in Home.js', ()=>{
    let tree = renderer.create(<Home />).toJSON();
    // console.log(tree.children);
    
    expect(findElement(tree, 'username')).toBeDefined();
});
```

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

### 參考

* [React-Native Test with jest #3 | Identify element](https://www.youtube.com/watch?v=bGT7vcZNrA8\&list=PL8p2I9GklV46mGMh5X1pzuDWidnRrlHyp\&index=3)
