技术控

    今日:155| 主题:49136
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Unit testing React Native with Jest

[复制链接]
凉透还能再暖 发表于 2016-9-30 20:08:47
107 3

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

Unit testing React Native with Jest-1 (comparison,management,including,business,concepts)
       Unit testing React Native with the *new* Jest (II) — Redux: Snapshots for your actions and reducers
   It’s a well known paradigm in the React world for any big app you want to write to extract your business logic (aka manage the state of your app) out of your components. The majority of your components should be a small piece of reusable code that just renders UI based on the app state that is triggered mainly by: User input and API calls. The same paradigm is used in React Native .
   I will talk about Redux together with React Native since testing Redux is easy . However feel free to apply the same concepts to another state management you choose. That’s what we will do here:
  
       
  • Testing Reducers: Manual comparison vs. Snapshots   
  • Mock the built-in React Native fetch   
  • Re-mock the redux-mock-store   
  • Testing Actions (including async ones): Manual comparison vs. Snapshots  
   Please refer to Unit testing React Native with the *new* Jest (I) — Snapshots come into play! for setting up Jest with React Native.
  Reducers

   Testing a reducer might be one of the easiest parts to test from your app: Given the current state and an action, a reducer should return a new state after that action is applied. Let’s see how to test part of this example :
   We will focus on testing that LOAD_REPOS.success action. Let’s create version 1 of our test:
        Copy & paste again :(       Quite short, right? I just went and copied and pasted the initialState from my reducer and added the part that changes ( repos ). When you work in larger projects and your state starts to grow (0r you do some refactoring), you will find this process to be so repetitive that you will want to do something better, so, version 2:
        Reimplementing the reducer :(       This is better, right? I can add or delete anything to the state (except the isLoading & repos part) and I won’t break the test. I just need to go back here if that action.success does actually affect another part of the state in the future. But, don’t you feel that test it is actually very similar to:
   Again, what we are doing in the test is basically reimplementing the reducer. Anytime I change the logic in my reducer, I need to come back here and do the same. It get’s so repetitive… Can we do better? Let’s snapshot that output. Hello version 3:
        Given the state and an action, generate the output for me       I know, it’s just one line and I did not have to repeat myself at all ( DRY ?). Do you like it? I do! Let’s see how the snapshot looks like:
   Wow! I can actually see how my state will exactly look like after applying the action. So as you can see, we are forcing Jest to do the hard work while we are just watching. In this case, if you add or remove any part of your state, this test will break: Which is what you should expect, since the outputted state would be different. But as I explained in thefirst part of these series, the only thing we need to do here is:
  
       
  • Review the Jest error output   
  • If it’s expected, run the test again using -u to re-generate the snapshot:  
  [code]npm test -— -u YourTestName[/code]  
       
  • If it’s not expected, go and fix it (obviously)  
   This is a great example of how fast and easy is to write your tests first, aka TDD ( Test-driven development ):
  
       
  • Write your test first   
  • Start writing your reducer with the Jest — watch mode enabled   
  • Once the outputted snapshot is the one you are expecting, just tell Jest to save it   
  • Done!  
  Actions

  A simple action creator is just a function that returns an object:
        Simple action creator      Which can be tested like:
  For the second part, let’s check out the generated snapshot:
  Yea, the exact same thing as the reducer: I (and my team) can read the output instead of re-creating the action again (which includes the need to maintain that code in both places).
   By the way, if you are already bored of reading, you can watch the same concept in a nice and short explanation here thanks to Kent C. Dodds . If you are not, let’s continue. Since testing such simple actions is so meh , let’s go and test an async action that uses the built-in fetch of React Native and dispatches more than one action at once.
  Async actions

  This is the async action we will test:
  We need some mocking help here to be able to have a nice way to test that so… Let’s mock!
   Mocking the built-in fetch of React Native
   Similar way that you can use whatwg-fetch in your web apps which will include a fetch polyfill into window.fetch , React Native uses the same idea and includes fetch into the global object as global.fetch .
  We don’t want to make real api calls into our unit tests but we would like to mock the responses to write better assertions. There are some mock libraries out there but I just wrote a smaller version that fits my purposes:
        Mocking fetch       Then, we can tell Jest to load that config using the package.json field setupFiles :
  [code]"jest": {  ...  "setupFiles": [    "./config/jest/globalFetch.js"  ]}[/code]  You will see when we are testing our async action how I used this mock. For now, let’s continue mocking.
  Mocking a Redux store

   I am sure that a lot of Redux users are familiar with redux-mock-store . It’s a simple helper that provides a mocked version of the Redux store and makes it very easy to test what actions have been called. Once you have your mocked store, you can use store.dispatch and get the list of actions that has been dispatched using store.getActions .
   But you know what? I feel so lazy that I don’t want to do the same in all my tests where I need a store and a thunk, so I am going to re-mock the redux-mock-store module. See, in Jest you can create a __mocks__ folder in the same level as your node_modules to mock any npm module. So I can actually create a redux-mock-store.js file (name of the module) in the __mocks__ folder:
  And use it in my tests like:
        Lazy, eh?      Async test

  I feel that we are ready to test our async action now, don’t you? Basically what we want to test here is:
  
       
  • A successful request should trigger request & success actions   
  • A failure request should trigger request & failure actions  
  First case:
        Quit short, right?      And what output will be generated?
  Just as expected and in this case, I think this one is very useful and easy to read: Quick read by reading “type” and longer read by checking that actually the “data” matches what we told fetch to return.
  The second case is very similar:
  And its output:
  As you can see, when you have the mocks in place, writing this kind of tests become very straightforward, and most likely, you won’t need to mock anything since you can find them out there or write your own and reuse them for other projects.
友荐云推荐




上一篇:The Perfect Web Development Environment for Your New Mac
下一篇:Node.js Roku Remote
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

董闵 发表于 2016-10-1 16:59:39
人是铁,范是钢,一天不装憋得慌
回复 支持 反对

使用道具 举报

hevnx 发表于 2016-10-21 12:29:37
给凉透还能再暖一个赞
回复 支持 反对

使用道具 举报

李长建 发表于 2016-10-22 08:16:15
避孕的效果:不成功,便成“人”。  
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表