create account

[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기 by anpigon

View this thread on: hive.blogpeakd.comecency.com
· @anpigon · (edited)
$1.51
[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기
이전글 ["\[React\] Mobx-state-tree 학습하기 #2 : Mobx-state-tree 모델에서 Actions을 사용하기"](/zzan/@anpigon/react-native-manage-application-state-with-mobx-state-tree-2)에서 이어지는 내용입니다. 참고로 이 포스팅은 제가 학습한 내용을 노트에 정리하듯이 기록하여 올리는 글이기 때문에 보팅 안해주셔서 됩니다. 


<br>

***

![](https://files.steempeak.com/file/steempeak/anpigon/sYISPibs-E1848CE185A6E18486E185A9E186A820E1848BE185A5E186B9E18482E185B3E186AB20E18483E185B5E1848CE185A1E1848BE185B5E186AB.png)
* 출처: https://egghead.io/courses/manage-application-state-with-mobx-state-tree
***

<br>

# Test mobx-state-tree Models by Recording Snapshots or Patches

> 강의 링크: https://egghead.io/lessons/react-test-mobx-state-tree-models-by-recording-snapshots-or-patches

3번째 레슨입니다. 모델을 테스트하는 것은 매우 간단합니다. MST는 state가 어떻게 변하는지 정확하게 추적 할 수 있는 도구를 제공합니다. snapshots, 액션 호출 또는 patches를 추적하여 액션이 올바르게 작동하는 지를 확인 할 수 있습니다.

우리는 다음을 배우게 됩니다.

* `getSnapshot`를 사용하여 state의 immutable한 snapshots 얻기
* `onSnapshot`을 사용하여 snapshots 기록하기
* `onPatch`를 사용하여 시간의 흐름에 따른 변화을 저장하고 테스트하기
* Jest의 snapshots 테스트 기능을 사용하여 snapshots과 patches 검증하기
* That MST can infer the type of a snapshot for you

<br>

***

<br>

# `getSnapshot` 함수를 사용하여 테스트 하기

Model의 전체 속성을 테스트하기 위해서 `getSnapshot` 함수를 사용합니다.  `getSnapshot`는 모델의 전체 트리 상태를 immutable하고 순수한 JSON 데이터로 만들어줍니다. 테스트 코드는 다음과 같이 작성합니다.
[여기](https://mobx-state-tree.gitbook.io/docs/concepts/snapshots)에 추가 설명이 있습니다.

`src/models/WhishList.test.js`
```
import { getSnapshot } from 'mobx-state-tree';

it("can add new items", () => {
  const list = WishList.create();
  list.add(
    WishListItem.create({
      name: "Chesterton",
      price: 10
    })
  );

  expect(getSnapshot(list)).toEqual({
    items: [
      {
        name: "Book of G.K. Chesterton",
        price: 10,
        image: ""
      }
    ]
  });
});
```

그리고 `toMatchSnapshot` 함수를 사용하면 스냅샷을 기록합니다.
```
it("can add new items", () => {
  const list = WishList.create();
  // ...

  expect(getSnapshot(list)).toMatchSnapshot();
});
```

<br>위 테스트를 실행하면 다음과 같이 `__snapshots__` 폴더에 스냅샷 파일이 생성됩니다.

![](https://files.steempeak.com/file/steempeak/anpigon/xLhaLw7g-E18489E185B3E1848FE185B3E18485E185B5E186ABE18489E185A3E186BA202019-08-182000.59.10.png)

<br>
<br>

# `onSnapshot` 함수를 사용하여 테스트하기

`onSnapshot` 함수를 사용하여 모델이 변경될 때마다 스냅샷을 states에 저장합니다. 그리고 `toMatchSnapshot` 함수를 사용하여 스냅샷이 어떻게 변화 했는지 기록합니다.

```
import { getSnapshot, onSnapshot } from "mobx-state-tree";

it("can add new items", () => {
  const list = WishList.create();

  const states = [];
  onSnapshot(list, snapshot => {
    states.push(snapshot);
  });

  //...

  expect(states).toMatchSnapshot();
}

```

<br>테스트를 수행하고 나서 스냅샷 기록을 보면 스냅샵이 어떻게 바뀌었는지를 살펴볼 수 있습니다.
![스냅샷 기록](https://files.steempeak.com/file/steempeak/anpigon/YLMLCCqQ-E18489E185B3E1848FE185B3E18485E185B5E186ABE18489E185A3E186BA202019-08-182001.10.34.png)

<br>
<br>

# `onPatch` 함수를 사용하여 테스트하기

```
import { getSnapshot, onSnapshot, onPatch } from "mobx-state-tree";

it("can add new items - 2", () => {
  const list = WishList.create();

  const patches = [];
  onPatch(list, patch => {
    patches.push(patch);
  })

  list.add(
    WishListItem.create({
      name: "Chesterton",
      price: 10
    })
  );

  list.items[0].changeName("Book of G.K. Chesterton");

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

<br>`onPatch` 함수를 사용한 테스트를 수행하고 나서 기록을 보면 모델의 변화에 대해서 살펴볼 수 있습니다. 어떤 작업을 수행했는지, 몇번째 항목의 값이 어떻게 변경되었는지를 확인 할 수 있습니다.

![](https://files.steempeak.com/file/steempeak/anpigon/GFWYYwru-E18489E185B3E1848FE185B3E18485E185B5E186ABE18489E185A3E186BA202019-08-182001.17.54.png)

<br>오늘의 학습 끝.

<br>
<br>

 `댓글`, `팔로우`, `좋아요` 해 주시는 모든 분께 감사합니다.

항상 행복한 하루 보내시길 바랍니다.

*** 

<center><img src='https://steemitimages.com/400x0/https://cdn.steemitimages.com/DQmQmWhMN6zNrLmKJRKhvSScEgWZmpb8zCeE2Gray1krbv6/BC054B6E-6F73-46D0-88E4-C88EB8167037.jpeg'><h5>vote, reblog, follow <code><a href='/@anpigon'>@anpigon</a></code></h5></center> 



***
<center><sup>Originally posted on [안피곤님의 블로그](http://anpigon.dblog.org/react-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree). Steem blog powered by [ENGRAVE](https://engrave.website).</sup></center>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 43 others
properties (23)
authoranpigon
permlinkreact-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree
categoryzzan
json_metadata{"format":"markdown","app":"busy/2.5.6","tags":["zzan","kr","kr-dev","dev","busy","jjm"],"image":["https://files.steempeak.com/file/steempeak/anpigon/sYISPibs-E1848CE185A6E18486E185A9E186A820E1848BE185A5E186B9E18482E185B3E186AB20E18483E185B5E1848CE185A1E1848BE185B5E186AB.png","https://files.steempeak.com/file/steempeak/anpigon/sYISPibs-E1848CE185A6E18486E185A9E186A820E1848BE185A5E186B9E18482E185B3E186AB20E18483E185B5E1848CE185A1E1848BE185B5E186AB.png","https://files.steempeak.com/file/steempeak/anpigon/xLhaLw7g-E18489E185B3E1848FE185B3E18485E185B5E186ABE18489E185A3E186BA202019-08-182000.59.10.png","https://files.steempeak.com/file/steempeak/anpigon/YLMLCCqQ-E18489E185B3E1848FE185B3E18485E185B5E186ABE18489E185A3E186BA202019-08-182001.10.34.png","https://files.steempeak.com/file/steempeak/anpigon/GFWYYwru-E18489E185B3E1848FE185B3E18485E185B5E186ABE18489E185A3E186BA202019-08-182001.17.54.png"],"links":["https://egghead.io/courses/manage-application-state-with-mobx-state-tree","https://egghead.io/lessons/react-test-mobx-state-tree-models-by-recording-snapshots-or-patches","https://mobx-state-tree.gitbook.io/docs/concepts/snapshots)%EC%97%90","https://steemitimages.com/400x0/https://cdn.steemitimages.com/DQmQmWhMN6zNrLmKJRKhvSScEgWZmpb8zCeE2Gray1krbv6/BC054B6E-6F73-46D0-88E4-C88EB8167037.jpeg'%3E%3Ch5%3Evote,"],"engrave":{"domain":"anpigon.dblog.org","permlink":"react-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree","url":"https://anpigon.dblog.org/react-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree","featured_image":"https://files.steempeak.com/file/steempeak/anpigon/sYISPibs-E1848CE185A6E18486E185A9E186A820E1848BE185A5E186B9E18482E185B3E186AB20E18483E185B5E1848CE185A1E1848BE185B5E186AB.png","categories":["5d8b1dc94302ae00124415b9"]},"community":"busy","good":true}
created2019-08-19 04:55:36
last_update2019-09-30 14:38:06
depth0
children10
last_payout2019-08-26 04:55:36
cashout_time1969-12-31 23:59:59
total_payout_value1.176 HBD
curator_payout_value0.337 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,095
author_reputation17,258,940,000,931
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,689,070
net_rshares4,594,242,847,547
author_curate_reward""
vote details (107)
@cyberrn.zzang ·
저도 패쑤~~~~~^^
properties (22)
authorcyberrn.zzang
permlinkpwhnr2
categoryzzan
json_metadata{"tags":["zzan"],"app":"steemzzang/0.1"}
created2019-08-19 14:47:27
last_update2019-08-19 14:47:27
depth1
children1
last_payout2019-08-26 14:47:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length12
author_reputation18,209,597,234,782
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,706,378
net_rshares0
@anpigon ·
패쑤인척 하면서 슈윳~~~~^^
감사합니다. ㅎㅎ
properties (22)
authoranpigon
permlinkre-cyberrnzzang-pwijzk
categoryzzan
json_metadata{"tags":["zzan"],"app":"steempeak/1.14.17"}
created2019-08-20 02:23:45
last_update2019-08-20 02:23:45
depth2
children0
last_payout2019-08-27 02:23:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length27
author_reputation17,258,940,000,931
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,725,699
net_rshares0
@fur2002ks ·
패쓰~~~~~~~~~~~~~~~~~~~~~ 즐거운 한주 되세요^^ 화이팅!
properties (22)
authorfur2002ks
permlinkpwgyn5
categoryzzan
json_metadata{"tags":["zzan"],"app":"steemit/0.1"}
created2019-08-19 05:45:06
last_update2019-08-19 05:45:06
depth1
children1
last_payout2019-08-26 05:45:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length41
author_reputation215,309,454,101,823
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,690,102
net_rshares0
@anpigon ·
스루 패쓰~~~~~~~~~~~~~~~~~~~~~ 감사합니다.
즐거운 한주 되세요~ ㅎㅎ
properties (22)
authoranpigon
permlinkre-fur2002ks-pwgzjr
categoryzzan
json_metadata{"tags":["zzan"],"app":"steempeak/1.14.15"}
created2019-08-19 06:04:39
last_update2019-08-19 06:04:39
depth2
children0
last_payout2019-08-26 06:04:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length48
author_reputation17,258,940,000,931
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,690,529
net_rshares0
@steem-ua ·
#### Hi @anpigon!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your **UA** account score is currently 3.420 which ranks you at **#7424** across all Steem accounts.
Your rank has not changed in the last three days.

In our last Algorithmic Curation Round, consisting of 156 contributions, your post is ranked at **#91**.
##### Evaluation of your UA score:

* You're on the right track, try to gather more followers.
* The readers like your work!
* Good user engagement!


**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-react-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree-20190820t010524z
categoryzzan
json_metadata"{"app": "beem/0.20.23"}"
created2019-08-20 01:05:27
last_update2019-08-20 01:05:27
depth1
children0
last_payout2019-08-27 01:05:27
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length610
author_reputation23,214,230,978,060
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,724,006
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/kr-newbie/avatar) [kr-newbie](/@kr-newbie)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[kr-newbie](/@kr-newbie)님의 [[8/19 kr-newbie 큐레이팅 프로젝트]](/zzan/@kr-newbie/8-19-kr-newbie) <br /> 

 <blockquote>...b.io/#/wallet/kr-newbie
happigon에서 자세한 임대내역이 확인 가능합니다.
만들어주신 anpigon께 감사드립니다! 
<ul>
<li>anpigon님의 HAAPIGON 유저가이드를 참고해주시기 바랍니다!</...</blockquote>
👍  
properties (23)
authorsteem.apps
permlinkre---------react-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree-20190819t113730535z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-19 11:37:33
last_update2019-08-19 11:37:33
depth1
children0
last_payout2019-08-26 11:37:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length414
author_reputation7,218,006,883,278
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,699,947
net_rshares3,801,746,163
author_curate_reward""
vote details (1)
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/wonsama.zzan/avatar) [wonsama.zzan](/@wonsama.zzan)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[wonsama.zzan](/@wonsama.zzan)님의 [[ZZAN] DAILY REPORT 2019-08-19](/zzan/@wonsama.zzan/zzan-daily-report-2019-08-19) <br /> 

 <blockquote>...td>
<td>zzan의 가격은 얼마가 적당 한가?</td>
<td>33</td>
</tr>
<tr>
<td>anpigon/td>
<td>13:55:36</td>
<td>[React] Mobx-state-t</td>
<td>17</...</blockquote>
properties (22)
authorsteem.apps
permlinkre---------react-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree-20190819t153139188z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-19 15:31:39
last_update2019-08-19 15:31:39
depth1
children0
last_payout2019-08-26 15:31:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length450
author_reputation7,218,006,883,278
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,707,986
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/always1success/avatar) [always1success](/@always1success)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[always1success](/@always1success)님의 [Active Bloggers #34](/palnet/@always1success/33wuwe-active-bloggers-34) <br /> 

 <blockquote>...taneously posted articles on Liv.SteemPeople.</em>
<ol>
<li>anpigon/li>
<li>banguri</li>
</ol>
<em>From the list of active blogg...</blockquote>
properties (22)
authorsteem.apps
permlinkre---------react-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree-20190819t230615034z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-19 23:06:15
last_update2019-08-19 23:06:15
depth1
children0
last_payout2019-08-26 23:06:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length450
author_reputation7,218,006,883,278
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,721,292
net_rshares0
@steemitboard ·
Congratulations @anpigon! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td><img src="https://steemitimages.com/60x70/http://steemitboard.com/@anpigon/votes.png?201908190822"></td><td>You distributed more than 12000 upvotes. Your next target is to reach 13000 upvotes.</td></tr>
</table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@anpigon) and compare to others on the [Steem Ranking](https://steemitboard.com/ranking/index.php?name=anpigon)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-anpigon-20190819t115853000z
categoryzzan
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-08-19 11:58:51
last_update2019-08-19 11:58:51
depth1
children0
last_payout2019-08-26 11:58:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length895
author_reputation38,975,615,169,260
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,700,591
net_rshares0
@virus707 ·
Thank you for your continued support towards JJM. For each 1000 JJM you are holding, you can get an additional 1% of upvote. 10,000JJM would give you a 11% daily voting from the 700K SP virus707 account.
properties (22)
authorvirus707
permlinkre-react-mobx-state-tree-3-snapshots-patches-recording-mobx-state-tree-1566222791
categoryzzan
json_metadata{"tags":["jjm"]}
created2019-08-19 13:53:09
last_update2019-08-19 13:53:09
depth1
children0
last_payout2019-08-26 13:53:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length203
author_reputation557,563,606,581,756
root_title"[React] Mobx-state-tree 학습하기 #3 : Snapshots 또는 Patches를 Recording하여 mobx-state-tree 모델 테스트하기"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,704,658
net_rshares0