> For the complete documentation index, see [llms.txt](https://twins-bamboo.gitbook.io/react-native-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://twins-bamboo.gitbook.io/react-native-note/test/jest/snapshot-testing.md).

# snapShot Testing

{% hint style="info" %}
以下 root 為 React Native Project 的主目錄
{% endhint %}

### 1.新增畫面&#x20;

新建 root/app/Home.js (若無該路徑則新建)

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

export default class Home extends Component {

  render() {
    return (
      <View style={styles.wrapper}>
        <Text style={styles.text}>Home Component</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  wrapper: {
    flex:1, 
    alignItems: 'center',
    justifyContent: 'center'
  },
  text: {
    fontSize: 24,
  }
})
```

### 2.修改App入口

因此新建此Project時，react native版本為0.55.4，所以入口為 **root/App.js** 此檔\
修改此檔案，如下Code (若react native較舊版時，App的入口分別為index.android.js 或者 index.ios.js)\
&#x20;   1\) import 步驟1 新建的 js\
&#x20;   2\) 修改 render function

```
import Home from './app/Home';

...

export default class App extends Component<Props> {
  render() {
    return (
      <Home />
    );
  }
}
```

### 3.新建test

在 \_\_tests\_\_/下 新建 Home-test.js\
ps.在新建此react native專案時，不知為何\_\_tests\_\_此資料夾沒有自動產生，所以手動新建

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

test('Home snapShot', ()=>{
  const snap = renderer.create(
    <Home />
  ).toJSON();

  expect(snap).toMatchSnapshot();
});
```

### 4.執行 (在此使用Android模擬器)

畫面如圖

![](https://703864731-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGT_WSMJJJ-6nRhUva4%2F-LHJfW3CPvfEsoL65QtN%2F-LHJg8gvm2kWPJrURCI7%2Fimage.png?alt=media\&token=960646fe-22c6-4994-9709-11d4ceb434e6)

### &#x20;5.執行test

打開terminal(或者PowerShell等等...)，執行npm test(或者yarn test)

```
$ yarn test
```

\
因為是第一次執行test，可看見 **1 snapshot written.** ，可看到新建了 root/\_\_tests\_\_/\_\_snapshots\_\_/Home-test.js.snap  \
執行後結果如下圖，也附上專案結構。

![](https://703864731-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGT_WSMJJJ-6nRhUva4%2F-LHJfW3CPvfEsoL65QtN%2F-LHJgI0cJFbIMtkCnq2j%2Fimage.png?alt=media\&token=a57f1c50-c6f5-4c82-b716-456f630def4e)

![](https://703864731-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGT_WSMJJJ-6nRhUva4%2F-LHJfW3CPvfEsoL65QtN%2F-LHJgTMwcaAPz3voTYiI%2Fimage.png?alt=media\&token=90de272b-5e58-41bb-8462-af1abed8542c)

### 參考

* [React native with Jest | snapshot testing](https://www.youtube.com/watch?v=pz2k6azJghk\&list=PL8p2I9GklV46mGMh5X1pzuDWidnRrlHyp)
