技术控

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

[其他] Unit testing React Native with Jest

[复制链接]
凉透还能再暖 投递于 2016-9-30 20:08:47
188 3

Unit testing React Native with Jest

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:  
  1. npm test -— -u YourTestName
复制代码

       
  • 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 :
  1. "jest": {  ...  "setupFiles": [    "./config/jest/globalFetch.js"  ]}
复制代码
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
避孕的效果:不成功,便成“人”。  
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表