<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ferran Negre on Medium]]></title>
        <description><![CDATA[Stories by Ferran Negre on Medium]]></description>
        <link>https://medium.com/@ferrannp?source=rss-1c26b66f5300------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5bw39UWjM9jVdc5T687ARA.jpeg</url>
            <title>Stories by Ferran Negre on Medium</title>
            <link>https://medium.com/@ferrannp?source=rss-1c26b66f5300------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 23:25:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ferrannp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[React Native Splash Screen on Android]]></title>
            <link>https://medium.com/@ferrannp/react-native-splash-screen-on-android-5e46e96006f1?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e46e96006f1</guid>
            <category><![CDATA[splash-screen]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native-development]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Wed, 22 Jan 2020 17:43:10 GMT</pubDate>
            <atom:updated>2020-01-22T17:43:10.233Z</atom:updated>
            <content:encoded><![CDATA[<h4>Spoiler: Native internals</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Yj0W6oGkoKtX-WUxJajCtw.png" /><figcaption>Image from <a href="https://facebook.github.io/react-native/">https://facebook.github.io/react-native/</a> (except the Android figure)</figcaption></figure><p>I could have used the following title for this article: “React Native Splash Screen done right on Android”. And you could have asked me, why done right? Who are you to say how to do it right? Well, it’s not you it’s me (or something like that!). It is actually Google and they know some things about Android. First of all, I’d like to suggest you to watch the following 3 minutes video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FE5Xu2iNHRkk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DE5Xu2iNHRkk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FE5Xu2iNHRkk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9320a459a7590681a96c79ed66b89dbd/href">https://medium.com/media/9320a459a7590681a96c79ed66b89dbd/href</a></iframe><p>Now, in order to add a splash screen into a React Native app (on the Android side), let’s follow their suggestions.</p><h4>First attempt</h4><p>The example app of this article does not have a white background by default, so having the transition from white to blueish is probably not really what we want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*x0oSmNULjzYIwHaKTpJ1UA.gif" /></figure><p>Let’s apply some concepts from the video including handling the status bar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c5862f3e80d4e5e2860a99fd100b6bb/href">https://medium.com/media/4c5862f3e80d4e5e2860a99fd100b6bb/href</a></iframe><p><strong>Note</strong>: With colorPrimaryDark you can change the status bar color on Android without waiting for the JS to load. You won’t even need to use the <a href="https://facebook.github.io/react-native/docs/statusbar">StatusBar</a> component for it.</p><p>With that we got the following effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*nXcJWZgG0gZBpS1GQhOjxg.gif" /><figcaption>First attempt</figcaption></figure><p>Much better with a couple of lines, but let’s proceed.</p><h4>Second attempt</h4><p>Ok, now we want to add an image to the splash screen. We can use windowBackgroundas it was explained in the video we watched (right?) just a few moments ago. First, we need to create a drawable file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c808c33b938d066ac853addae7c1e558/href">https://medium.com/media/c808c33b938d066ac853addae7c1e558/href</a></iframe><p>Then let’s update our styles to add the SplashTheme:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44089676e2bcf59ff34aa0dbf539d9d8/href">https://medium.com/media/44089676e2bcf59ff34aa0dbf539d9d8/href</a></iframe><p>We modify our AndroidManifest.xml to change the default theme of our MainActivity:</p><pre>// AndroidManifest.xml</pre><pre>&lt;activity<br>    android:name=&quot;.MainActivity&quot;<br>    ...<br>    <strong>android:theme=&quot;@style/SplashTheme&quot;</strong>&gt;</pre><p>And finally we change our MainActivity to switch to the default theme when the app starts:</p><pre>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>  <strong>setTheme(R.style.<em>AppTheme</em>);</strong><br>  super.onCreate(savedInstanceState);<br>}</pre><p><strong>Everything we did here so far is from the Google’s video</strong>. All of it. This is the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*6FGOGgPVmbtvHvwk1ACuqQ.gif" /><figcaption>Second attempt</figcaption></figure><p><strong>I was not fully satisfied with it</strong>. There is still an empty blue screen in the middle (because the JS and everything else needed by React Native is still loading). So the following is the extra React Native mile I came up with.</p><h4><strong>Final attempt</strong></h4><p>The idea is:</p><ol><li>Show the splash screen while loading JS without mounting the React default view</li><li>When the JS is ready, mount the React view using a native fade-in animation</li></ol><p><strong>Note</strong>: The following code is not documented so it might change in future versions of React Native.</p><p>We are gonna override the <a href="https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java#L37-L40">createReactActivityDelegate</a> method from the<a href="https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java">ReactActivity</a>. This is to defer adding the <a href="https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java">ReactRootView</a> so then we can have a nice fade-in effect (we will call <a href="https://developer.android.com/reference/android/app/Activity.html#setContentView(android.view.View)">setContentView</a> later). Thus, inside of our MainActivity let’s place this piece of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c0715fd88e5e284f5d3dcf8f80aa0f4/href">https://medium.com/media/5c0715fd88e5e284f5d3dcf8f80aa0f4/href</a></iframe><p>After that, we are going to add the following method (where the <em>magic</em> happens):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69086eb7cb4d2de9f33c9695a786d017/href">https://medium.com/media/69086eb7cb4d2de9f33c9695a786d017/href</a></iframe><p>And we are also going to create a small native module that we will use from the JS side:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47290a8ce326c470f4e431be479ff928/href">https://medium.com/media/47290a8ce326c470f4e431be479ff928/href</a></iframe><p>Anywhere in our JS side, depending on ours app needs we can call that method:</p><pre>// JS side</pre><pre><strong>import </strong>{ <strong>NativeModules </strong>} <strong>from </strong>&#39;react-native&#39;;<br><strong>const </strong>RNSplashScreen = <strong>NativeModules</strong>.RNSplashScreen;<br><br>RNSplashScreen.hide();</pre><p>And with that, we got the one I was looking for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*DuG2p-oUugDk7R4HjHGYRg.gif" /><figcaption>Release app mode</figcaption></figure><p><strong>Note</strong>: Another benefit from this approach is that we do not have to use any extra <a href="https://developer.android.com/reference/android/app/Activity">Activity</a> or <a href="https://developer.android.com/guide/topics/ui/dialogs">Dialog</a>.</p><p>It took me quite some time but I am really happy with the final result and if you would like the same, feel free to use that in your React Native apps for a <em>delightful</em> Android splash screen experience.</p><p>Thanks for reading and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e46e96006f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your next React Native app will still be done with Paper (2.0)]]></title>
            <link>https://medium.com/call-stack/your-next-react-native-app-will-still-be-done-with-paper-2-0-672bb4fdb5b7?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/672bb4fdb5b7</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Fri, 28 Sep 2018 10:10:27 GMT</pubDate>
            <atom:updated>2021-08-16T15:31:26.238Z</atom:updated>
            <content:encoded><![CDATA[<h4>react-native-paper</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ucm2eGmeDRIRDY4cez-4w.jpeg" /></figure><p>Hooray! While react-native-paper has just reached 2000 ⭐️ on Github, we were announcing it at <a href="https://react-native.eu/">React Native EU 2018</a> as a major update for Paper that is aligned with the <a href="https://material.io/design/">new Material Design guide</a>. This is <strong>react-native-paper 2.0</strong>. Don’t want to read? No problem, I got a lighting talk that gets you covered:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0CxUzjWkRms%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0CxUzjWkRms&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0CxUzjWkRms%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e42be51b53fb974bc7ea41bc2a9d560/href">https://medium.com/media/6e42be51b53fb974bc7ea41bc2a9d560/href</a></iframe><h3>Key concepts of Paper 2.0</h3><h4>Material design guidelines</h4><p>New style and new components are awaiting for you, ready to be used on Android and iOS.</p><h4>Platform adaptation</h4><p>As you saw in <a href="https://blog.callstack.io/your-next-react-native-app-will-be-done-with-paper-40eebd88be98">version 1</a>, we continue to provide platform adaption so your iOS users keep feeling comfortable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6fNZ3g4sRzw7vMOOhtQzw.png" /></figure><h4>Full theming support</h4><p>We extracted the theming logic into <a href="https://github.com/callstack/react-theme-provider">https://github.com/callstack/react-theme-provider</a>. You can easily switch from light to dark theme or give to your users any choice they want!</p><h4>Portal</h4><p>Render dialogs, floating action buttons, snackbars… One thing above the other. Thanks to <a href="https://callstack.github.io/react-native-paper/portal.html">Portal</a> you can easily manage it.</p><h4>Accessibility and RTL</h4><p>We’ve been working very hard for this version to be much better regarding accessibility. We want each and every of our components to be fully accessible and RTL compatible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mbjbzmts3RKLYLfOwheQ8w.png" /></figure><h4>Developer experience</h4><p>Not only our example is <a href="https://expo.io/">Expo</a> compatible but now you can also check any component in our docs and look for this link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*P0aUDo6omkqMKuM6x-hALw.png" /><figcaption>You can find a link like this in every page in our docs</figcaption></figure><p>And you can just try it! Oh and we are also working in <a href="https://github.com/callstackincubator/bs-react-native-paper">bindings for ReasonML</a>!</p><h3>1.0 vs 2.0</h3><p>Some component differences between versions.</p><h4>Button</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MxPiDTn3Yscj2Ij4YoiSw.png" /><figcaption>1.0 vs 2.0</figcaption></figure><h4>TextInput</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fl2ZB8xC_u0ayUrHruXQxw.png" /><figcaption>1.0 vs 2.0</figcaption></figure><h4>Appbar</h4><p>Yes, not a <a href="https://material.io/design/components/app-bars-top.html">Toolbar</a> anymore!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCO_FeOWaUqadsoypq1IWg.png" /><figcaption>1.0 vs 2.0</figcaption></figure><p>Want to see more? Check the <a href="https://callstack.github.io/react-native-paper">t</a>he docs at <a href="https://callstack.github.io/react-native-paper">https://callstack.github.io/react-native-paper</a>!</p><p>Wanna help? Be a contributor? There a are lot of components to be made so just join us in this beautiful journey and do not hesitate to send a PR! We also have a channel in <a href="https://discord.gg/zwR2Cdh">Discord</a>.</p><p>Don’t forget to check our repo: <a href="https://github.com/callstack/react-native-paper">https://github.com/callstack/react-native-paper</a></p><p>Happy Paper day 2!</p><p><em>This article was originally published at </em><a href="https://callstack.com/blog/your-next-react-native-app-will-still-be-done-with-paper-2-0/"><em>callstack.com</em></a><em> on September 28, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=672bb4fdb5b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/call-stack/your-next-react-native-app-will-still-be-done-with-paper-2-0-672bb4fdb5b7">Your next React Native app will still be done with Paper (2.0)</a> was originally published in <a href="https://medium.com/call-stack">Callstack Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your next React Native app will be done with Paper]]></title>
            <link>https://medium.com/call-stack/your-next-react-native-app-will-be-done-with-paper-40eebd88be98?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/40eebd88be98</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[material-design]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Thu, 22 Feb 2018 15:42:47 GMT</pubDate>
            <atom:updated>2018-02-22T15:42:47.386Z</atom:updated>
            <content:encoded><![CDATA[<h4>Meet react-native-paper</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gVfEuQ_cDslEcAZUwtSpAQ.jpeg" /><figcaption>Credits to <a href="http://manualcreative.com/project/google-design/">http://manualcreative.com/project/google-design/</a></figcaption></figure><p>Today I am proud to announce the release of <a href="https://callstack.github.io/react-native-paper/"><strong>react-native-paper</strong></a><strong> 1.0.0</strong> 🎉 🎉 🎉 .</p><p>React Native Paper or just <em>Paper</em> was started a long ago, around October 2016. It was an idea from <a href="https://github.com/ahmedlhanafy">ahmedlhanafy</a> and <a href="https://github.com/satya164">satya164</a>. Some time ago, we decided that <a href="http://github.com/callstack">Callstack</a> could take care of it as part of our open source mission and here we are today — Paper is now ready for you to use it in production. Yey!</p><h4>Why?</h4><p>We love <a href="https://material.io/guidelines/">Material Design</a> because it provides a consistent and smooth user experience. We wanted to have the same look and feel in our React Native apps. We wanted to support both Android and iOS platforms, closely following the Material Design guidelines, all with a nice and easy to use API.</p><p>That’s why we created Paper. We are very picky and detail oriented and that is why we made sure to make every pixel count.</p><p>Paper gives you all the beautiful of well crafted <strong>material design</strong> components that work and look (almost) exactly the same for both <strong>Android and iOS</strong>. Why almost? Well, we are following the <a href="https://material.io/guidelines/platforms/platform-adaptation.html">Platform Adaptation</a> guide:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ty_tKz3rBR2Drtb2SJPIRg.png" /><figcaption>Platform adaptation</figcaption></figure><h4>Tell me more!</h4><p>We are releasing a bunch of components like Buttons, Toolbar, Papers!, Cards, Typography, etc. But we plan to add much more so we expect 1.0.0 to be just the beginning of our big plans (CollapsibleToolbar? 😄). And of course, we will be very thrilled to get more contributors on board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Y69g1QIkTCUNVwXXK8nhQ.png" /><figcaption>Some the components from react-native-paper</figcaption></figure><p>Let’s play a game, I’ll show you some real apps. You tell me if they are written in pure native code or using Paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFXI2dmYxNgspheT5FvaHQ.jpeg" /></figure><p>Did you guess it? You are right, they are all built with Paper!</p><p>To conclude, just to make it easier for playing with our internal example, scan this QR code with Expo and you are good to go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*21hQWoDFNnxFxPX7CIa_Kw.png" /><figcaption>Scan with Expo to try the <a href="https://github.com/callstack/react-native-paper/tree/master/example">example</a> app</figcaption></figure><p>Checkout the <a href="https://callstack.github.io/react-native-paper/">docs</a> to get started with Paper. If you have any issues or ideas for improvements, open an issue on <a href="https://github.com/callstack/react-native-paper">our repo</a>, and don’t forget to star it!</p><p>Happy Paper day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40eebd88be98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/call-stack/your-next-react-native-app-will-be-done-with-paper-40eebd88be98">Your next React Native app will be done with Paper</a> was originally published in <a href="https://medium.com/call-stack">Callstack Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native: Handling language changes on Android the right way]]></title>
            <link>https://medium.com/call-stack/react-native-handling-language-changes-on-android-the-right-way-c883056a8f5c?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/c883056a8f5c</guid>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Tue, 12 Sep 2017 14:01:00 GMT</pubDate>
            <atom:updated>2017-09-12T14:01:00.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKsZPBfgWRmXZCabe0KOfQ.jpeg" /></figure><p>One of the core features of your app is internationalization (aka <strong>I18n</strong>), right? Internationalization is all about offering your products in such a way that they can be localized for languages and cultures easily.</p><p>In react native there is a very nice library to handle it: <a href="https://github.com/AlexanderZaytsev/react-native-i18n">https://github.com/AlexanderZaytsev/react-native-i18n</a>. With this library, you can define a list of locales your mobile app supports:</p><pre>I18n.<strong>fallbacks </strong>= <strong>true</strong>;<br>I18n.<strong>translations </strong>= {<br>  en,<br>  es,<br>  pl,<br>  fr,<br>  it,<br>};</pre><p><em>Note</em>: Fallback is important for unfinished translations. So if your fallback language is en and you have a key that is not translated (so not defined in another language) it will use the key from the fallback language instead.</p><p>Using the module is also pretty familiar if you come from the web:</p><pre>I18n.t(&#39;some_key&#39;)</pre><p>One of the lovely things to handle this on the JavaScript side (I developed pure Android apps) is that you can update your .js language files and upload them on the fly using <a href="https://github.com/Microsoft/react-native-code-push">CodePush</a>. That way, for any new language, any new key, any typo being fixed, you do not need to do a full app release (YEAH!).</p><p>There was some trickery involved though and that is why I am writing this article. I found out that when using this library on Android, if we change the system language, <strong>the app will not update to the new locale till I reload the JS bundle</strong>. That is not the Android default behavior so… Let’s fix it!</p><h3>Solving the reload Android problem</h3><p>Let’s see first what happens on iOS when changing the system language and going back to our app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*PzBQ3zrOBHpYsNzX0kwZzw.gif" /><figcaption>I speeded up the video a bit…</figcaption></figure><p>As you can see, everything works as expected, our app and bundle gets restarted when coming back to it and we see the new language in place. Let’s see how it behaves on Android:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*W1lATFIAbKzLrojoadyejw.gif" /><figcaption>The bundle does not reload when changing the language</figcaption></figure><p>I googled for an existing solution, I followed this post <a href="https://medium.com/@maximtoyberman/changing-locale-in-react-native-android-86fe25cde318">https://medium.com/@maximtoyberman/changing-locale-in-react-native-android-86fe25cde318</a> but it did not work for me (the part of restarting). Plus you need a couple of more dependencies: react-native-locale-listener and react-native-restart. In fact, we can solve this on the native side with a few lines of code and we won’t need any more dependencies. Actually, we won’t even need to go through the bridge (all will happen in the native side).</p><p>We need to add a couple of cases in our AndroidManifest.xml, look for this line and add the two bold cases:</p><pre>android:configChanges=&quot;keyboard|keyboardHidden|orientation|screenSize|<strong>layoutDirection</strong>|<strong>locale</strong>&quot;&gt;</pre><p>In theory we just need locale but there is a bug in the Android platform where the locale change won’t trigger if we do not add layoutDirection too.</p><p>After that, we can go to our MainActivity.java, it should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b892b9e47fab943ce8fae9d4b9afac8a/href">https://medium.com/media/b892b9e47fab943ce8fae9d4b9afac8a/href</a></iframe><p>Unfortunately, inside onConfigurationChanged we cannot access the old locale and that is why I am using the currentLocale variable. But basically, if we change the locale (change the phone language) we will recreate the react context. This is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*iOOwVTqvHjQpzRHMWX4r9A.gif" /><figcaption>The bundle reloads when changing the language</figcaption></figure><p>Just as we wanted! Not sure about you but I am going to use this technique in any app I need to write, I18n is a must!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c883056a8f5c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/call-stack/react-native-handling-language-changes-on-android-the-right-way-c883056a8f5c">React Native: Handling language changes on Android the right way</a> was originally published in <a href="https://medium.com/call-stack">Callstack Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Drawer & StatusBar done right for React Native]]></title>
            <link>https://medium.com/call-stack/android-drawer-statusbar-done-right-for-react-native-7e85f01fc099?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e85f01fc099</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[material-design]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Fri, 24 Mar 2017 16:07:13 GMT</pubDate>
            <atom:updated>2017-03-24T16:07:13.478Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of React Native applications out there don’t really care about this matter but as an Android perfectionist I do, so let me show you how to make your drawers more beautiful following some simple steps (It took me a while to figure out them though!).</p><p>You can check all the <a href="https://material.io/guidelines/patterns/navigation-drawer.html#">official Material spec for the drawer</a>, but what we are going to focus here is in the following part:</p><blockquote>The nav drawer spans the full height of the screen, including behind the status bar.</blockquote><p>Thus, a drawer following this spec would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*dEw5lf7wEcWZvucYRmsgXw.png" /><figcaption>Beautiful, isn’t it?</figcaption></figure><p>If you go deep down into the material intro guide, you’ll find the <a href="https://material.io/guidelines/layout/structure.html#structure-system-bars">opacity value</a> for the StatusBar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*gY5sHAbwuKUGDSU2xoWTxg.png" /><figcaption>Translucent status bar, 20% Black #000000</figcaption></figure><p>Let’s try that 20% of black. To do so, we can define the StatusBar as follows:</p><pre>import { StatusBar } from &#39;react-native&#39;;</pre><pre>&lt;StatusBar<br>  translucent<br>  backgroundColor=&quot;rgba(0, 0, 0, <strong>0.20</strong>)&quot;<br>  animated<br>/&gt;</pre><p>You will get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJEsd3oc41Mq1aXAA2S0jA.png" /><figcaption>Using the <a href="https://facebook.github.io/react-native/docs/drawerlayoutandroid.html">DrawerLayoutAndroid</a> from React Native</figcaption></figure><p>Now, we have the drawer above the status bar giving us a nice visual effect (you can use an image as a header too). However, we need to adjust our screens as you can see at the screenshot on the right. For that, we can just make a View with the desired color to be our <a href="https://developer.android.com/training/material/theme.html#StatusBar">colorPrimaryDark</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e84b092dea09cd71d207890bf1a962f/href">https://medium.com/media/4e84b092dea09cd71d207890bf1a962f/href</a></iframe><p>Now it will look like as we wanted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wK-07nFXTpPYLGXKnc0OQ.png" /></figure><h4>Pitfalls of using &lt;StatusBar /&gt; and how to avoid them</h4><p>The main problem of using &lt;StatusBar translucent /&gt;is that it will load after the React JS context loads. So if you pay attention when opening the app, there is going to be a glitch after that loading because the status bar will become translucent and we will be moving the screen down to adjust it.</p><p>Check it out (check the button in the center):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*-_hLymZOAn1l8cuyy_qNVw.gif" /><figcaption>50% of original speed</figcaption></figure><p>To fix the glitch, we can write the translucent logic natively. We can check howreact-native does <a href="https://github.com/facebook/react-native/blob/a99f6f51a959717a124d7fe61beab43b146518bb/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/StatusBarModule.java#L106-L143">this</a> and just base our solution on it (in our MainActivity.java):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6258f9747de193f5e79b6824bfaa629/href">https://medium.com/media/a6258f9747de193f5e79b6824bfaa629/href</a></iframe><p>The important part here is just to call our function before super.onCreate(savedInstanceState) where the actual JS context initialization will happen.</p><p>With this, the glitch will be gone when you first open the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*C2mhkFI5A128k3Te7qFfkA.gif" /></figure><p>And that’s it! I hope to start seeing more beautiful drawers above the status bar from now on!</p><p>Give this some ❤️ if you like me to continue with a series of articles based on making your React Native base app look and feel like an Android/Material application.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e85f01fc099" width="1" height="1" alt=""><hr><p><a href="https://medium.com/call-stack/android-drawer-statusbar-done-right-for-react-native-7e85f01fc099">Android Drawer &amp; StatusBar done right for React Native</a> was originally published in <a href="https://medium.com/call-stack">Callstack Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native and Native Modules: The Android SyncAdapter]]></title>
            <link>https://medium.com/call-stack/react-native-and-native-modules-the-android-syncadapter-517ddf851bf4?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/517ddf851bf4</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Mon, 13 Feb 2017 15:02:00 GMT</pubDate>
            <atom:updated>2017-04-24T23:45:09.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzw_9zxwsRgIOIRg-N-A0g.jpeg" /><figcaption>React Native and Android have been friends for a while</figcaption></figure><p>I came into the need of using a SyncAdapter for an Android app I want to fully convert into React Native. In this app, I already have the native piece of code working and I could not find a library out there that actually exposes such functionality. This is how I ended up writing it by myself.</p><h4>What is the SyncAdapter ?</h4><p>Basically it is a framework that Android provides to synchronize the data between an Android device and web servers. You could design your own, but they always recommended to use their solution since it provides you with several nice features that you cannot implement by yourself. Basically:</p><ul><li>Schedule syncs: If at scheduled time is not possible to sync, the system will run when possible</li><li>The system only runs your data transfer when the device has network connectivity (so no need to check/worry about it)</li><li>Improved battery performance: Your data transfer is scheduled in conjunction with data transfers from other apps. These factors reduce the number of times the system has to switch on the network, which reduces battery usage</li><li>No need to worry about device being restarted so you do not need to listen for <a href="https://developer.android.com/reference/android/content/Intent.html#ACTION_BOOT_COMPLETED">ACTION_BOOT_COMPLETED</a></li></ul><p>You can read more advantages <a href="https://developer.android.com/training/sync-adapters/index.html">here</a>.</p><h4>What is the HeadlessJS ?</h4><p>It is just another Native Module that wraps an <a href="https://developer.android.com/guide/components/services.html">Android Service</a> which starts the JavaScript engine where you can run background tasks written in JavaScript. <a href="https://facebook.github.io/react-native/docs/headless-js-android.html">Headless JS</a> is part of React Native since version <a href="https://github.com/facebook/react-native/releases/tag/v0.36.0">0.36.0</a>.</p><p>For this native module that I named as react-native-sync-adapter, we are gonna combine the Android SyncAdapter with the HeadlessJS. Let’s start!</p><h4>Writing native code</h4><p>I will not go into details in this part but it is a must to use <a href="https://developer.android.com/studio/index.html">Android Studio</a>. It will provide you with auto-imports and tones of other features. For writing native code, I have basically followed <a href="https://developer.android.com/training/sync-adapters/creating-sync-adapter.html">Creating a Sync Adapter</a> training. If you want to read through the code you can do it <a href="https://github.com/ferrannp/react-native-sync-background/tree/master/android/src/main">here</a>. For this section, I am actually going to focus on parts of the code that would actually be new for an Android developer (including React Native code interaction).</p><p><strong>Using HeadlessJS</strong></p><p>When our SyncAdapter is ready to sync, it basically calls the Java method onPerformSync (see this <a href="https://github.com/ferrannp/react-native-sync-background/blob/master/android/src/main/java/com/fnp/reactnativesyncbackground/SyncAdapter.java#L21-L25">file</a>). In there, we want to start our HeadlessJS so we can write all the actual sync code in JavaScript (like fetching from an API):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad8102653c98276da764388667a042f4/href">https://medium.com/media/ad8102653c98276da764388667a042f4/href</a></iframe><p>Our HeadlessService.class is almost the same as the one explained on the <a href="https://facebook.github.io/react-native/docs/headless-js-android.html">docs</a> but with some extra checks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/313efa8c88212bbdb015358baa510ee1/href">https://medium.com/media/313efa8c88212bbdb015358baa510ee1/href</a></iframe><p>There are several things worth mentioning here:</p><pre>new HeadlessJsTaskConfig(<br>        <em>TASK_ID</em>,<br>        null,<br>        300000);</pre><ul><li>We hardcoded our TASK_ID to be TASK_SYNC_BACKGROUND so you will need to register a task with this exact same name and that is the task our SyncAdapter will run</li><li>We pass null as parameter so the actual JS task will receive null as extra (since we do not need any param)</li><li>Default timeout is set to 5 minutes which should be enough for any task of this kind. It could have been also possible to pass a parameter for the timeout the same as we do with syncInterval and syncFlexTime (see <a href="https://github.com/ferrannp/react-native-sync-background#api">API</a>)</li></ul><p>What about the isAppInForeground check? From the <a href="https://facebook.github.io/react-native/docs/headless-js-android.html#caveats">docs</a>:</p><blockquote>By default, your app will crash if you try to run a task while the app is in the foreground. This is to prevent developers from shooting themselves in the foot by doing a lot of work in a task and slowing the UI. There is a way around this.</blockquote><p>Indeed <em>there is a way around this </em>which is taking a look at the source code and passing a specific parameter. But, I prefer to stick into only launching the service when the app is in the background. My workaround would be:</p><ol><li>In your HeadlessJS task, save (for example in the <a href="https://facebook.github.io/react-native/docs/asyncstorage.html">AsyncStorage</a>) the last timestamp where a sync was completed</li><li>When opening the app, check that timestamp, if a sync is required, just make the app to do the job</li><li>Done</li></ol><p>Another thing worth mentioning, have you spot the stopSelf() ? If we actually return just null, it will start a <a href="https://developer.android.com/reference/android/app/Service.html#START_NOT_STICKY">non-sticky Service</a> that will not be stopped (which is bad for memory/battery) so we make sure that we handle this edge case.</p><p><strong>Creating the module</strong></p><p>Let’s go ahead and create a native module, named SyncBackground that will be responsible for interacting with our SyncAdapter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ad056583ef99d5c6c912b070ed4b066/href">https://medium.com/media/5ad056583ef99d5c6c912b070ed4b066/href</a></iframe><p>Basically we do two things here:</p><ul><li>Override getName so from now on, our Native Module will be called SyncBackground</li><li>Expose (using @ReactMethod), in this case, just the method init that will set up all the sync hassle for us</li></ul><p>Now, loading that module is just a matter of adding a new instance of it to the native modules list, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be9ee4f32213c1c4b59d037323df7cd2/href">https://medium.com/media/be9ee4f32213c1c4b59d037323df7cd2/href</a></iframe><p>So the apps that want to actually use this module will be able to add new SyncBackgroundPackage() just as we do in the <a href="https://github.com/ferrannp/react-native-sync-background/blob/master/example/android/app/src/main/java/com/syncbackgroundexample/MainApplication.java#L27">example</a> app.</p><p>More on the native side, we want our module to act as an Android library so we can use it in other projects, to do so, take a look at the <a href="https://github.com/ferrannp/react-native-sync-background/blob/master/android/build.gradle">build.gradle</a> file. The only required thing to convert our module into an Android library (so Android won’t generate an apk for it) is to add the following line:</p><pre>apply plugin: ‘com.android.library’</pre><p>To learn more check <a href="https://developer.android.com/studio/projects/android-library.html">Create an Android library</a>.</p><p>And voilà! Our library is ready to be consumed.</p><h4>Android library perks</h4><p>One requirement to set up a SyncAdapter is to provide unique resources (strings in this case) plus our app launcher icon. If you check the Android library <a href="https://developer.android.com/studio/projects/android-library.html#Considerations">considerations</a>:</p><blockquote>Resource merge conflicts: The build tools merge resources from a library module with those of a dependent app module. If a given resource ID is defined in both modules, the resource from the app is used.</blockquote><p>Which basically means that if you define a resource in your library named my-library-string-name and define the same resource name in your app, the one from your app will take precedence. We can take advantage of this since our SyncAdapter needs unique values for each app, so in the app that we will be using this library, we should override these values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46a5aae984b0eef6f24865e3370fc1fc/href">https://medium.com/media/46a5aae984b0eef6f24865e3370fc1fc/href</a></iframe><p>As you can see, I prefixed the specific strings from the library with rnsb so they are safer to override (app_name is a common pattern so I left it like that). The launcher icon that is used in the library should be named ic_launcher.png which is also a default pattern.</p><p>If you run the example app and in your phone, go to Settings -&gt; Account you will see how the strings and the launcher icon are correctly being overridden:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bAo1PrwJ49AY4S3r9GIFuw.png" /></figure><p>As you can see, the values that are used are from our app and not from the library. To your question: Yes, I AM A WIZARD.</p><p>By the way, notice at the second screenshot, you can select the option <strong>Sync Now</strong> which will trigger onPerformSync which will trigger your HeadlessJS task so you can try it out without waiting at all.</p><h4>Exposing a typed API</h4><p>I find it nice not to expose the Native Module as it is, but wrap it into your own API where you can actually use some typing (Hello Flow!).</p><p>Indeed, I could expose this library as:</p><pre><strong>import </strong>{ NativeModules } <strong>from </strong>&#39;react-native&#39;;<br><strong>export default </strong>NativeModules.SyncBackground;</pre><p>But as I said, I would like to provide a more JS-like API and provide Flow types so we make sure we use the library correctly. Here is this tiny API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e720b29938029a0c5965d8d073b87ecb/href">https://medium.com/media/e720b29938029a0c5965d8d073b87ecb/href</a></iframe><p>I use an Object as parameter so it is easy to extend it in the future without breaking changes. Flow will make sure you call the function with correct parameters plus I do some error checking. Therefore, the internal implementation is totally transparent to the user and they do not need to know/care how do I use/call functions in the native (Java) code.</p><h4>Binding it all together</h4><p>Our native module is ready to use. You can actually follow the setup instructions in the repository: <a href="https://github.com/ferrannp/react-native-sync-adapter">https://github.com/ferrannp/react-native-sync-adapter</a>.</p><p>Thanks to React Native modular approach, when one solves a problem on Android (that we do not really want to solve ourselves), then you do not need to do it by yourself never again. Which is nice, isn’t it?</p><p>Let me know what you think in the comments below and if you would like me to continue writing about Native Modules even if they are simple examples.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517ddf851bf4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/call-stack/react-native-and-native-modules-the-android-syncadapter-517ddf851bf4">React Native and Native Modules: The Android SyncAdapter</a> was originally published in <a href="https://medium.com/call-stack">Callstack Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Native with the *new* Jest — Part II]]></title>
            <link>https://medium.com/call-stack/unit-testing-react-native-with-the-new-jest-ii-redux-snapshots-for-your-actions-and-reducers-8559f6f8050b?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/8559f6f8050b</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Thu, 29 Sep 2016 15:00:11 GMT</pubDate>
            <atom:updated>2017-02-27T14:49:08.080Z</atom:updated>
            <content:encoded><![CDATA[<h4>Redux: Snapshots for your actions and reducers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izboexI8_vOPxIVYLQSVVw.jpeg" /></figure><p>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 <strong>React Native</strong>.</p><p>I will talk about Redux together with React Native since <strong>testing Redux is easy</strong>. However feel free to apply the same concepts to another state management you choose. That’s what we will do here:</p><ul><li>Testing Reducers: Manual comparison vs. Snapshots</li><li>Mock the built-in React Native fetch</li><li><em>Re-mock</em> the redux-mock-store</li><li>Testing Actions (including async ones): Manual comparison vs. Snapshots</li></ul><p>Please refer to <a href="https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.kz404carv">Unit testing React Native with the *new* Jest (I) — Snapshots come into play!</a> for setting up Jest with React Native.</p><h3>Reducers</h3><p>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 <a href="https://github.com/ferrannp/react-native-testing-example/blob/master/app/reducers/__tests__/repos-test.js">example</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c765ae1a54a0f717254158a929d4377e/href">https://medium.com/media/c765ae1a54a0f717254158a929d4377e/href</a></iframe><p>We will focus on testing that <em>LOAD_REPOS.success</em> action. Let’s create version 1 of our test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb16ff5365004bd5d9e55ee9151ba580/href">https://medium.com/media/fb16ff5365004bd5d9e55ee9151ba580/href</a></iframe><p>Quite short, right? I just went and copied and pasted the <em>initialState</em> from my reducer and added the part that changes (<em>repos</em>). 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:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78d4a2e3ee48c98e5fd820b4152494b8/href">https://medium.com/media/78d4a2e3ee48c98e5fd820b4152494b8/href</a></iframe><p>This is better, right? I can add or delete anything to the state (except the <em>isLoading</em> &amp; <em>repos</em> part) and I won’t break the test. I just need to go back here if that <em>action.success</em> does actually affect another part of the state in the future. But, don’t you feel that test it is actually very similar to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc109a52ada361eb551122ab2e075a0/href">https://medium.com/media/2dc109a52ada361eb551122ab2e075a0/href</a></iframe><p>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 <em>snapshot</em> that output. Hello version 3:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8256fd662cea717eb6536868309fb4be/href">https://medium.com/media/8256fd662cea717eb6536868309fb4be/href</a></iframe><p>I know, it’s just one line and I did not have to repeat myself at all (<a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>?). Do you like it? I do! Let’s see how the snapshot looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/556c1fe61ac7f9fe3e4ad9f3edd781cb/href">https://medium.com/media/556c1fe61ac7f9fe3e4ad9f3edd781cb/href</a></iframe><p>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 the <a href="https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.kz404carv">first part</a> of these series, the only thing we need to do here is:</p><ul><li>Review the Jest error output</li><li>If it’s expected, run the test again using -u to re-generate the snapshot:</li></ul><pre>npm test -— -u YourTestName</pre><ul><li>If it’s not expected, go and fix it (obviously)</li></ul><p>This is a great example of how fast and easy is to write your tests first, aka TDD (<a href="https://en.wikipedia.org/wiki/Test-driven_development">Test-driven development</a>):</p><ol><li>Write your test first</li><li>Start writing your reducer with the Jest <em>— watch</em> mode enabled</li><li>Once the outputted snapshot is the one you are expecting, just tell Jest to save it</li><li>Done!</li></ol><h3>Actions</h3><p>A simple action creator is just a function that returns an object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e14782a6bb4d08ea32c07b2e42405e2e/href">https://medium.com/media/e14782a6bb4d08ea32c07b2e42405e2e/href</a></iframe><p>Which can be tested like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7042a17bcb52c48532f0dea747a4893e/href">https://medium.com/media/7042a17bcb52c48532f0dea747a4893e/href</a></iframe><p>For the second part, let’s check out the generated snapshot:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28f4c41170c59583647f87bdf9242e35/href">https://medium.com/media/28f4c41170c59583647f87bdf9242e35/href</a></iframe><p>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).</p><p>By the way, if you are already bored of reading, you can watch the same concept in a nice and short explanation <a href="https://egghead.io/lessons/javascript-use-jest-s-snapshot-testing-feature?utm_content=bufferf0127&amp;utm_medium=social&amp;utm_source=twitter.com&amp;utm_campaign=buffer">here</a> thanks to <a href="https://medium.com/u/db72389e89d8">Kent C. Dodds</a>. If you are not, let’s continue. Since testing such simple actions is so <em>meh</em>, 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.</p><h3>Async actions</h3><p>This is the async action we will test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf5fc34488730423dfcd1b9e051a84b5/href">https://medium.com/media/bf5fc34488730423dfcd1b9e051a84b5/href</a></iframe><p>We need some mocking help here to be able to have a nice way to test that so… Let’s mock!</p><h4><strong>Mocking the built-in fetch of React Native</strong></h4><p>Similar way that you can use <a href="https://github.com/github/fetch">whatwg-fetch</a> in your web apps which will include a fetch polyfill into <em>window.fetch</em>, React Native uses the same idea and includes fetch into the global object as <em>global.fetch</em>.</p><p>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:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c0a411c5a9d9f54956f137fc006b83f/href">https://medium.com/media/5c0a411c5a9d9f54956f137fc006b83f/href</a></iframe><p>Then, we can tell Jest to load that config using the package.json field <em>setupFiles</em>:</p><pre>&quot;jest&quot;: {<br>  ...<br><strong>  &quot;setupFiles&quot;: [<br>    &quot;./config/jest/globalFetch.js&quot;<br>  ]</strong><br>}</pre><p>You will see when we are testing our async action how I used this mock. For now, let’s continue mocking.</p><h4>Mocking a Redux store</h4><p>I am sure that a lot of Redux users are familiar with <a href="https://github.com/arnaudbenard/redux-mock-store">redux-mock-store</a>. 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 <em>store.dispatch</em> and get the list of actions that has been dispatched using <em>store.getActions</em>.</p><p>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 <em>re-mock</em> the <em>redux-mock-store </em>module. See, in Jest you can create a <a href="https://facebook.github.io/jest/docs/manual-mocks.html">__mocks__</a> folder in the same level as your <em>node_modules</em> to mock any npm module. So I can actually create a <em>redux-mock-store.js</em> file (name of the module) in the <em>__mocks__ </em>folder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c12baf4ebcdddec0699cca330b477945/href">https://medium.com/media/c12baf4ebcdddec0699cca330b477945/href</a></iframe><p>And use it in my tests like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/576e40641c2466ed0db4cf3016fa1f3a/href">https://medium.com/media/576e40641c2466ed0db4cf3016fa1f3a/href</a></iframe><h4>Async test</h4><p>I feel that we are ready to test our async action now, don’t you? Basically what we want to test here is:</p><ol><li>A successful request should trigger <em>request</em> &amp; <em>success</em> actions</li><li>A failure request should trigger <em>request</em> &amp; <em>failure</em> actions</li></ol><p>First case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ee6bb75f39c177269bcd96b8a70ef95/href">https://medium.com/media/0ee6bb75f39c177269bcd96b8a70ef95/href</a></iframe><p>And what output will be generated?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/870fd63a6b1769553577b64b39e8fdb9/href">https://medium.com/media/870fd63a6b1769553577b64b39e8fdb9/href</a></iframe><p>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.</p><p>The second case is very similar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81f9308b305cf4ca507c4e8f2970482c/href">https://medium.com/media/81f9308b305cf4ca507c4e8f2970482c/href</a></iframe><p>And its output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9292233e234cfcb604d54226d199a42/href">https://medium.com/media/a9292233e234cfcb604d54226d199a42/href</a></iframe><p>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.</p><h3>Wrap up</h3><p>This is it, with this part and the <a href="https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.tw96bxp3h">first one</a>, we pretty much covered (I hope) unit testing of your React Native components + your state management logic. We also re-discovered Jest and its new superpower: Snapshots. On contrary, I am sure the way to test React Native apps will continue to improve as much as Jest keeps growing. So this article might get out of date quite soon!</p><p>Let me finish with some personal thoughts:</p><h4>Why would I use Jest?</h4><ul><li>You can easily test your React &amp; React Native components</li><li>Snapshots are a plus, but they are totally optional</li><li>You can easily test Redux or other state management libraries with Jest: Shared logic between web and mobile <em>could</em> share tests too!</li><li>The same community have created React Native &amp; Jest. What does that mean? They will be the ones who care the most about making React Native and Jest to play nicely together in the future</li></ul><p>To sum up: If you test your web &amp; mobile app with Jest, you can use the same core principle of React Native:</p><blockquote><em>Learn once, write anywhere — React Native</em></blockquote><p>Of course, that is only my opinion. I just hope you enjoyed this short journey about testing a React Native app with the <em>new</em> Jest and remember…</p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8559f6f8050b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/call-stack/unit-testing-react-native-with-the-new-jest-ii-redux-snapshots-for-your-actions-and-reducers-8559f6f8050b">Testing React Native with the *new* Jest — Part II</a> was originally published in <a href="https://medium.com/call-stack">Callstack Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Native with the *new* Jest — Part I]]></title>
            <link>https://medium.com/call-stack/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/68ba19b1b9fe</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Fri, 09 Sep 2016 13:26:54 GMT</pubDate>
            <atom:updated>2018-02-01T14:33:38.256Z</atom:updated>
            <content:encoded><![CDATA[<h4>Snapshots come into play!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*prMD_4FNJ_l1rxhmNEJh5Q.jpeg" /></figure><p>In my journey with <a href="https://facebook.github.io/react/">React</a>, I have been always testing and encouraging people who surround me to test their apps. I have always used <a href="https://facebook.github.io/jest/">Jest</a> for it. But let’s not talk about it <a href="https://medium.com/@ferrannp/unit-testing-with-jest-redux-async-actions-fetch-9054ca28cdcd#.687medygy">again</a> and let’s focus on <a href="https://facebook.github.io/react-native/">React Native</a>. Wouldn’t it be nice to use the same framework to test our amazing mobile apps? Furthermore… Wouldn’t it be nice to reuse some tests if we are reusing logic between our web app and our mobile app?</p><p>I will try to answer those questions in the following series. In this first article, I will focus on testing <strong>React Native components</strong> and the pros and cons of using the new Snapshot system provided by Jest vs. shallow rendering comparison (test utils and Enzyme).</p><h3>The new Jest ?</h3><p>Before you ask me why I am calling it the <em>new</em> Jest, please check out the updates notes from <a href="https://facebook.github.io/jest/blog/2016/07/27/jest-14.html">Jest 14</a> and <a href="https://facebook.github.io/jest/blog/2016/09/01/jest-15.html">Jest 15</a>. It is not only me who says that Jest has a total new face compared to 1 year ago… It is also his number one core contributor:</p><h3>Christoph Pojer on Twitter</h3><p>@pedrasmachado @dan_abramov @matzatorski yeah, it has nothing to do with what Jest was then. Just the same name and logo.</p><p>In this series we will focus on one of the new Jest features: <strong>Snapshot testing</strong>.</p><blockquote>Jest can <a href="https://facebook.github.io/jest/docs/tutorial-react.html#snapshot-testing">capture snapshots</a> of React trees or other serializable values to write tests quickly and it provides a seamless update experience.</blockquote><p>Let’s begin to prove the above quote!</p><h3>Set up Jest in a React Native project</h3><p>Trivial, seriously. Just follow the <a href="https://facebook.github.io/jest/docs/tutorial-react-native.html#setup">docs</a>:</p><pre>// <strong>Install dependencies</strong><br>npm install --save-dev jest babel-jest jest-react-native babel-preset-react-native react-test-renderer</pre><pre>// <strong>package.json</strong><br>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;jest&quot;<br>},<br>&quot;jest&quot;: {<br>  &quot;preset&quot;: &quot;jest-react-native&quot;<br>}</pre><pre>// <strong>.babelrc</strong><br>{<br>  &quot;presets&quot;: [&quot;react-native&quot;]<br>}</pre><p>DONE. Try it out with:</p><pre>npm test</pre><h3>Time to test components</h3><p>The <a href="https://github.com/ferrannp/react-native-testing-example">example repo</a> for this article renders a list of Github repositories. You can read several test examples in there but for the purpose this article, let’s focus on testing a simple component called RepoItem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a181c869be0eb45c2cb54f8c7ba9a86/href">https://medium.com/media/9a181c869be0eb45c2cb54f8c7ba9a86/href</a></iframe><p>As you can see, this component has an interesting prop called <em>isSelected</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*qKM5_0LPe79DV6pY-V6Wag.jpeg" /><figcaption>When isSelected = true, then the item renders with a green background</figcaption></figure><h3>The problems of Shallow Rendering comparison</h3><p>Have you ever used <a href="https://facebook.github.io/react/docs/test-utils.html#shallow-rendering">Shallow rendering</a> from <a href="https://facebook.github.io/react/docs/test-utils.html#shallow-rendering">react-addons-test-utils</a><em> </em>or <a href="https://github.com/airbnb/enzyme">Enzyme</a>? They are pretty similar, Enzyme got popular cause it has a nicer API which also allows you to find elements in your React trees. Let’s choose this one and try to test a React Native component using it.</p><h4><strong>Enzyme</strong></h4><p>First problems when trying to use the <a href="https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md">shallow</a> function from Enzyme (forget about <a href="http://airbnb.io/enzyme/docs/guides/jsdom.html#using-enzyme-with-jsdom">mount</a> in react-native):</p><pre><strong>react-addons-test-utils</strong> is an implicit dependency in order to support react@0.13–14. Please add the appropriate version to your devDependencies. See <a href="https://github.com/airbnb/enzyme#installation">https://github.com/airbnb/enzyme#installation</a></pre><pre><strong>react-dom</strong> is an implicit dependency in order to support react@0.13–14. Please add the appropriate version to your devDependencies. See <a href="https://github.com/airbnb/enzyme#installation">https://github.com/airbnb/enzyme#installation</a></pre><p>So we actually need to install <em>react-dom</em> and <em>react-addons-test-util</em> to our <em>devDependencies</em> for Enzyme to work… Ouch!:</p><pre>npm install react-dom react-addons-test-util --save-dev</pre><p>Ok, let’s go and try to do the first full shallow comparison:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71624eaee65fe5cf58944f839186c64c/href">https://medium.com/media/71624eaee65fe5cf58944f839186c64c/href</a></iframe><p>Ok, actually, this first example won’t work. See the <em>onPress</em> property? The first problem that we have here is the way it’s defined in the component:</p><pre>onPress={() =&gt; {props.selectRepo(id)}}</pre><p>Both functions won’t be the same (we are creating a new function instance) thus the comparison will fail. We could make some workarounds here but… Let’s be lazy and skip the <em>TouchableHighlight</em> part and assume that nobody will break it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e3c50f009295475d7d73d3ea2d890d0/href">https://medium.com/media/2e3c50f009295475d7d73d3ea2d890d0/href</a></iframe><p>Don’t you feel we are reimplementing the <em>render()</em> again? Any prop you add/remove or any change you make… You need to come back here and do the same.</p><p>All right, now we want to test the component when the prop <em>isSelected</em> is set to true:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d73e5d2f2cd06fefeb93d9255f79e64/href">https://medium.com/media/4d73e5d2f2cd06fefeb93d9255f79e64/href</a></iframe><p>Since recreating the bigger picture gets so repetitive, developers tend to test only the <em>dynamic parts</em>, see:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/233626a73c3e819af79a90da1a9b14de/href">https://medium.com/media/233626a73c3e819af79a90da1a9b14de/href</a></iframe><p>This seems better, right? Let’s continue…</p><p>Assume that at some point on this project, our client decides that when you click a list item, a part from the selected background color, we also want to show more information, specifically, the repo description. It would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*3w4LPNHhQ48VPzPRLvipBw.jpeg" /><figcaption>When isSelected = true, the item renders with a green background and shows the repo description</figcaption></figure><p>With this change, two things will happen:</p><ol><li>The test that checks all the render output will fail: We will need to go back and reimplement it</li><li>The test that checks only the dynamic part will pass anyway (Oops! is that good?)</li></ol><p>In the first case, we need to go back and copy-paste this line into it’s corresponded place:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b605213c4d24b412c480814a49366b70/href">https://medium.com/media/b605213c4d24b412c480814a49366b70/href</a></iframe><p>In the second case, we need to remember to go back to the test and add the new cases:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/783cb11a418e0d9eb126ad00dd43336e/href">https://medium.com/media/783cb11a418e0d9eb126ad00dd43336e/href</a></iframe><p>Do you see the problems? The way I see it… The bigger picture (full render) is complicated to create, tedious to maintain and very repetitive (copy-paste). The second approach (using find, contains…) is unstable: We need to remember to implement all the cases since the new ones won’t break those tests.</p><p>Check the full <a href="https://github.com/ferrannp/react-native-testing-example/blob/master/app/components/__tests__/RepoItem-Shallow-test.js">RepoItem-Shallow-test.js</a> file for a bigger picture.</p><h4>Shallow rendering summary</h4><p><strong>Pros</strong></p><ul><li>Powerful selector api (find, contains, etc)</li><li>It is actually working in React Native (shallow part)</li></ul><p><strong>Cons</strong></p><ul><li>It feels you are repeating yourself all the time, thus, people will usually tend to test only specific parts of the output (render) instead of the big picture</li><li>Copy-paste from the component to the test</li><li>Difficult to maintain</li><li>Go try convincing people to write them</li></ul><h3>Snapshots to the rescue</h3><p>Jest 14 introduced Snapshots testing: Check out <a href="https://facebook.github.io/jest/blog/2016/07/27/jest-14.html#why-snapshot-testing">why are they so great</a>:</p><blockquote><strong>No flakiness:</strong> Because tests are run in a command line runner instead of a real browser or on a real phone, the test runner doesn’t have to wait for builds, spawn browsers, load a page and drive the UI to get a component into the expected state which tends to be flaky and the test results become noisy.</blockquote><blockquote><strong>Fast iteration speed:</strong> Engineers want to get results in less than a second rather than waiting for minutes or even hours. If tests don’t run quickly like in most end-to-end frameworks, engineers don’t run them at all or don’t bother writing them in the first place.</blockquote><blockquote><strong>Debugging:</strong> It’s easy to step into the code of an integration test in JS instead of trying to recreate the screenshot test scenario and debugging what happened in the visual diff.</blockquote><p>After the read, let’s try it out and convince ourselves.</p><p>We can write a Snapshot test for our first RepoItem (when isSelected is set to false):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db5e358f2e5b44759e15248b38667866/href">https://medium.com/media/db5e358f2e5b44759e15248b38667866/href</a></iframe><p>Check the result at: <a href="https://github.com/ferrannp/react-native-testing-example/blob/master/app/components/__tests__/__snapshots__/RepoItem-Snapshot-test.js.snap">RepoItem-Snapshot-test.snap</a>. You will find that it does not use the background color property (as expected) because isSelected is false:</p><pre><strong>// RepoItem-Snapshot-test.snap</strong></pre><pre>...<br>style={<br>  Array [<br>    Object {<br>      &quot;backgroundColor&quot;: &quot;transparent&quot;<br>    },<br>    <strong>undefined</strong><br>  ]<br>}<br>...</pre><p>Now, let’s test the output when isSelected is set to true (it needs to render a green background). Since our component is actually a pure function, this becomes trivial:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc38012eee91f927dcd5d4e9cd3da76f/href">https://medium.com/media/dc38012eee91f927dcd5d4e9cd3da76f/href</a></iframe><p>And we can find the expected part inside the resulted snapshot <a href="https://github.com/ferrannp/react-native-testing-example/blob/master/app/components/__tests__/__snapshots__/RepoItem-Snapshot-test.js.snap">RepoItem-Snapshot-test.snap</a>:</p><pre><strong>// RepoItem-Snapshot-test.snap</strong></pre><pre>style={<br>  Array [<br>    Object {<br>      &quot;paddingHorizontal&quot;: 24,<br>      &quot;paddingVertical&quot;: 8<br>    },<br>    <strong>Object {<br>      &quot;backgroundColor&quot;: &quot;#B2DFDB&quot;<br>    }</strong><br>  ]<br>}&gt;</pre><p>Great! Now, remember that our client came and asked us to implement the expanded part to show the repo description (a part from the background color). Let’s run the tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*TC5he0oV3gCoCCwENhEZeA.png" /><figcaption>Oops! A test has failed</figcaption></figure><p>Let’s check why:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*FO1j84U-kBJ1MFbPoB1MHg.png" /><figcaption>Nice output!</figcaption></figure><p>At developing time, Jest will show us very useful error outputs (you can use the <a href="https://facebook.github.io/jest/#use-the-interactive-mode-mode-to-automatically-re-run-tests">watch</a> argument to see them live). Since this change is expected, we can run:</p><pre>npm test -- -u RepoItem-Snapshot</pre><p>And that will update our snapshot for free. Check it out:</p><pre>...<br>    50000 stars<br>  &lt;/Text&gt;<br><strong>  &lt;Text<br>    accessible={true}<br>    allowFontScaling={true}<br>    ellipsizeMode=&quot;tail&quot;&gt;<br>    Useful description goes here.<br>  &lt;/Text&gt;</strong><br> &lt;/View&gt;<br>&lt;/View&gt;<br>...</pre><p>Boom! Our test failed, we inspected it, the failure was expected and we re-generated the snapshot. We did not have to modify our test. Moreover, this snapshot difference will be shown in our next Pull Request.</p><p>And that is all, seriously. Our render output is fully tested for both cases and it is capable to <em>react</em> to changes giving us nice error outputs and an easy way to fix them. Quiet neat, right?</p><h4><strong>Can I test components with internal state?</strong></h4><p>Before you ask, yes, you can. Check this example in the Jest repo: <a href="https://github.com/facebook/jest/blob/master/examples/snapshot/__tests__/Link.react-test.js">Link.react-test.js</a>. Of course, if your component has internal state (side effects), it will get much more complicated to test. See:</p><p><strong>I am missing a selector api like Enzyme</strong></p><p>Specially if your component has state and you need to trigger some event, it can be very tedious to find the node inside the tree. However, this question has been already asked <a href="https://github.com/facebook/jest/issues/1411">https://github.com/facebook/jest/issues/1411</a> and it has an official answer:</p><blockquote>We are working on a selector API for the test renderer which will make this possible through an official API — <a href="https://medium.com/u/9ea60eb6fc7c">Christoph Pojer</a></blockquote><h4>Snapshots summary</h4><p><strong>Pros</strong></p><ul><li>Easy to write</li><li>Don’t repeat yourself (<a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>)</li><li>Compatible with React Native: Check <a href="https://github.com/ferrannp/react-native-testing-example/blob/master/app/components/__tests__/RepoList-Snapshot-test.js">RepoList-Snapshot-test.js</a> and its <a href="https://github.com/ferrannp/react-native-testing-example/blob/master/app/components/__tests__/__snapshots__/RepoList-Snapshot-test.js.snap">snapshot</a> which renders a ListView with its items (try to do that without snapshots if you can)</li><li>Error messages on develop time (you can use —watch t00)</li><li>More goodies to come!</li></ul><p><strong>Cons</strong></p><ul><li>Missing a selector API like Enzyme (but you read above that Jest community is working on it)</li><li>S̶n̶a̶p̶s̶h̶o̶t̶s̶ ̶c̶a̶n̶ ̶b̶e̶ ̶h̶u̶g̶e̶ ̶a̶n̶d̶ ̶s̶o̶m̶e̶t̶i̶m̶e̶s̶ ̶i̶t̶ ̶m̶i̶g̶h̶t̶ ̶b̶e̶ ̶t̶e̶d̶i̶o̶u̶s̶ ̶t̶o̶ ̶f̶i̶n̶d̶ ̶t̶h̶e̶ ̶p̶a̶r̶t̶ ̶y̶o̶u̶ ̶a̶r̶e̶ ̶l̶o̶o̶k̶i̶n̶g̶ ̶f̶o̶r̶ ̶(̶l̶o̶t̶ ̶o̶f̶ ̶n̶o̶i̶s̶e̶)̶.̶ ̶I̶n̶ ̶c̶o̶n̶t̶r̶a̶s̶t̶,̶ ̶p̶u̶l̶l̶ ̶r̶e̶q̶u̶e̶s̶t̶s̶ ̶w̶i̶l̶l̶ ̶h̶i̶g̶h̶l̶i̶g̶h̶t̶ ̶a̶n̶y̶ ̶c̶h̶a̶n̶g̶e̶s̶ ̶f̶o̶r̶ y̶o̶u̶ . <strong>Update 27 Jul 2017</strong>: We created <a href="https://github.com/jest-community/snapshot-diff">snapshot-diff</a> to overcome this issue. Third part of this article is coming soon.</li><li>I am missing a comparison-tool-like between Snapshots. In my example, I manually need to look the differences between the Snapshot with <em>isSelected</em> set to false vs. <em>isSelected</em> set to true</li></ul><h3>What is the true value of Snapshots?</h3><p>I want to wrap up <strong>stressing the pull request part</strong> again. From <a href="https://medium.com/u/db72389e89d8">Kent C. Dodds</a>:</p><h3>Kent C. Dodds on Twitter</h3><p>@spencercarnage that&#39;s not where the value is... The value is in this [1] at develop time and this [2] at PR time</p><p>I could not agree more: Code reviews shine using snapshots. But, <strong>be aware</strong> then that for the Snapshot concept to work you need to<strong>:</strong></p><h3>Christoph Pojer on Twitter</h3><p>@VilleImmonen @Vjeux but I need to stress that when using snapshots it&#39;s integral that the resulting file is being reviewed properly.</p><p>Which means:</p><blockquote>You need to <strong>make sure</strong> that the __snapshots__ folders are reviewed in your PRs</blockquote><p>Let me add yet another value: Don’t repeat yourself. This has been demonstrated (I hope!) here when we do not have to re-rewrite our component output. But if you want to go further on that, check out the next article of this series:</p><p><a href="https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-ii-redux-snapshots-for-your-actions-and-reducers-8559f6f8050b#.vvzqnehue">Unit testing React Native with the *new* Jest (II) — Redux: Snapshots for your reducers and actions</a></p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68ba19b1b9fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/call-stack/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe">Testing React Native with the *new* Jest — Part I</a> was originally published in <a href="https://medium.com/call-stack">Callstack Engineers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React HOC: ‘Enhancing’ a Dropdown]]></title>
            <link>https://medium.com/@ferrannp/react-hoc-enhancing-a-dropdown-8784b2909104?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/8784b2909104</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Fri, 01 Jul 2016 16:32:38 GMT</pubDate>
            <atom:updated>2016-07-01T17:03:42.189Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started with React there was no Redux, there was no idea of centralized state or store. There was just React state and props + Flux and its <a href="https://raw.githubusercontent.com/facebook/flux/master/docs/img/flux-diagram-white-background.png">diagram</a> if you wanted to go further. At that time, there was still discussion and confusion whether to use state or props.</p><p>I feel there is still a lot of discussion around this topic today. Some people will tell you that state is evil and you should never use it, some people will tell you to use Redux even if you don’t know React and some others will tell you just to do whatever you like. This is still happening today! Check this recent discussion from one of the co-creators of <a href="https://github.com/reactjs/react-router">react-router</a>:</p><h3>Ryan Florence on Twitter</h3><p>When in React, and you think, &quot;I heard state is bad&quot;. Open http://facebook.com , go to the React Inspector, look at their components.</p><h3>The dropdown example</h3><p>What I am going to do here is present a real example I encountered several times when writing React applications that have suffered from this topic: A component as simple as a Dropdown. Here is the main idea:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*bLtmB_cHIGJdeJuCWF7CVg.png" /><figcaption>The dropdown</figcaption></figure><p>For a particular app, this is what I needed:</p><p><strong>State that I needed to access outside of this component</strong></p><ul><li>data (coming from an external API)</li><li>optionSelected (which would affect other parts of the app)</li></ul><p><strong>State that I did not need to access outside of this component</strong></p><ul><li>isOpen</li></ul><p>So here is where the debate started. What do I do with the <em>isOpen</em> state? I can think of 3 different approaches to tackle it:</p><ol><li>Write your state as up as you can on your hierarchy and pass a callback as a prop (scales pretty badly)</li><li>Add the state in your Redux store:<br>- Create a reducer or reuse another one if it makes some sense<br>- Create an action for it<br>- Do the same if you want to reuse this dropdown into another application</li><li>Use a High Order Component (HOC) that ‘enhances’ your component injecting state and/or functionality</li></ol><p>In this post I am not going to discuss the pros and cons of number 1 and 2 (because that would probably be too subjective) but rather I am going to show an example of the option we will be using here: Number 3 that is based on this <a href="https://gist.github.com/sebmarkbage/ef0bf1f338a7182b6775">gist</a> from <a href="https://twitter.com/sebmarkbage">sebmarkbage</a>.</p><p>Here is our shinny <a href="https://facebook.github.io/react/docs/reusable-components.html#stateless-functions">stateless</a> dropdown:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52b451f1fa46045a79b27657f898d26f/href">https://medium.com/media/52b451f1fa46045a79b27657f898d26f/href</a></iframe><p>This guy has been also named as <a href="http://dump or presentational componen">dump/presentational component</a>. The thing is that it can not do anything by its own (a part from render a view), it actually needs an app that controls it or a HOC that enhances it.</p><p>So I did actually want an enhancer that was capable to:</p><ul><li>Open and close the dropdown (state)</li><li>Close the dropdown when clicking outside of it (functionality)</li><li>Close the dropdown when clicking on one of its options (functionality)</li><li>Be reusable</li></ul><p>Proposed solution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3ea24681eb882f39aabe988e1393dcc/href">https://medium.com/media/f3ea24681eb882f39aabe988e1393dcc/href</a></iframe><p>This enhancer is teaching our stateless Dropdown when to be opened or closed using <em>isOpen</em> and what to do <em>onToggle</em> and <em>onSelect</em>. Another cool thing is that it is handling the <em>click oustide</em> functionality using a wrapper<em>.</em></p><p>This approach has few advantages:</p><ul><li>It is reusable: You can write another kind of dropdown (different markup) and it will work if you respect the prop names</li><li>You can use it or not, if your <em>isOpen</em> state affects other parts of the app, you can go with other options of using the stateless dropdown (like together with Redux) without enhancing it</li><li>A state (<em>isOpen</em>) that only affects that component has been encapsulated into it, thus, when changing it, the <a href="https://facebook.github.io/react/docs/reconciliation.html">React DOM reconciliation algorithm</a> will only look at this portion of code to decide whether we need a re-render or not</li></ul><h3>Wrap Up: To state or not to state</h3><p>So, what now? Do I use state or not? Well… I want to think there is not a clear and 100% proven answer for this. React is so close to pure JS that gives you almost all the freedom in the world. I would say that sometimes it might be beneficial and sometimes it might be not, the key here is that you need to find what is suitable for your app and <strong>go for it without being afraid of sentences like</strong>:</p><ul><li>Always use props</li><li>Never use state</li><li>State is evil</li><li><em>You are doing it wrong</em></li></ul><p>And… That’s it! Hope this was helpful and happy coding!</p><p><strong>Final note</strong>: You can try the example code <a href="https://github.com/ferrannp/react-high-order-dropdown">here</a> or visit the <a href="https://ferrannp.github.io/react-high-order-dropdown/">demo</a> page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8784b2909104" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing with Jest: Redux + async actions + fetch]]></title>
            <link>https://medium.com/@ferrannp/unit-testing-with-jest-redux-async-actions-fetch-9054ca28cdcd?source=rss-1c26b66f5300------2</link>
            <guid isPermaLink="false">https://medium.com/p/9054ca28cdcd</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Ferran Negre]]></dc:creator>
            <pubDate>Thu, 19 May 2016 01:43:53 GMT</pubDate>
            <atom:updated>2017-06-24T18:23:20.591Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Jest v20</h4><p><strong>LAST UPDATE: June 24, 2017. Original writing: May 19, 2016.</strong></p><p>I have been using <a href="https://facebook.github.io/jest/">Jest</a> since its beginnings. I won’t lie, the path has been painful: Things like updating from version 0.x.0 to version 0.y.0 (specially to version 0.4.0) was particularly terrible for my tests. Furthermore, I struggled myself more than once with the way Jest works and I even bothered the community with questions like <a href="http://stackoverflow.com/questions/25533036/test-a-react-component-function-with-jest">1</a>, <a href="http://stackoverflow.com/questions/26470679/test-a-form-with-jest-and-react-js-testutils">2</a>, and <a href="http://stackoverflow.com/questions/35610252/how-to-test-a-react-component-that-uses-context-like-in-react-router-2-0-with-je">3</a>.</p><p>But stay with me, Jest has also good things that I am going to show you in a moment. I hope somebody will find this particularly useful because, in my humble opinion, the biggest drawback of Jest is its lack of real examples.</p><p>Recently (May 19, 2016), I’ve been writing an app with the React/Redux combo. It uses an external API and I decided to use a fetch <em>polyfill</em> in order to make my network requests. Following the <em>Redux-way</em>,<em> </em>I’ve used <a href="http://redux.js.org/docs/advanced/AsyncActions.html">Async Action Creator</a>s in combination with <a href="https://github.com/gaearon/redux-thunk">redux-thunk</a>. Here is how my action looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb0231e404533214a38028b472e944ec/href">https://medium.com/media/bb0231e404533214a38028b472e944ec/href</a></iframe><p>(Notice that nowadays you can use async/await too).</p><p>Ok, now, let’s test it step by step based on the <a href="http://redux.js.org/docs/recipes/WritingTests.html">WritingTests</a> from the Redux docs.</p><blockquote>A big change here since I first wrote this article in 2016 is that Jest now does <strong>not mock your dependencies automatically</strong> like it used to. You can read more about it on its blog: <a href="http://facebook.github.io/jest/blog/2016/09/01/jest-15.html#disabled-automocking">Jest 15 — Disabled automocking</a></blockquote><p>Therefore, we do not need to manually <a href="https://facebook.github.io/jest/docs/jest-object.html#jestunmockmodulename">unmock</a> modules we want to test.</p><p>On the contrary, we are going to use <a href="https://github.com/arnaudbenard/redux-mock-store"><em>redux-mock-store</em></a> which is a small package that will help us mocking a redux store as it’s name suggests. Basically, it emulates the redux store (same API) but just for test purposes. You can check the <a href="https://github.com/arnaudbenard/redux-mock-store/blob/master/src/index.js">code</a> which is very simple.</p><p>Let’s get started! We import everything we need:</p><pre><strong>import </strong>{ fetchData } <strong>from </strong>&#39;../api&#39;;<br><strong>import </strong>configureMockStore <strong>from </strong>&#39;redux-mock-store&#39;<br><strong>import </strong>thunk <strong>from </strong>&#39;redux-thunk&#39;<br><br><strong>const </strong>middlewares = [ thunk ];<br><strong>const </strong>mockStore = configureMockStore(middlewares);</pre><p>And I am also going to write a helper method to mock the <a href="https://github.com/github/fetch/blob/master/fetch.js#L327-L339">fetch response</a> (we don’t need <a href="https://github.com/node-nock/nock">nock</a> as suggested in the <a href="http://redux.js.org/docs/recipes/WritingTests.html#async-action-creators">Redux Writing Test example</a>):</p><pre><strong>const </strong>mockResponse = (status, statusText, response) =&gt; {<br>  <strong>return new </strong>window.Response(response, {<br>    status: status,<br>    statusText: statusText,<br>    headers: {<br>      &#39;Content-type&#39;: &#39;application/json&#39;<br>    }<br>  });<br>};</pre><p>After that, let’s actually write our first <strong>it</strong> (previously we needed to use <a href="https://github.com/facebook/jest/issues/928">pit</a> for async test: Not anymore)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba98e22ffc017bfea7a909c60837c511/href">https://medium.com/media/ba98e22ffc017bfea7a909c60837c511/href</a></iframe><p>Do you see what I am doing? I don’t care what the real fetch does, I will reinvent it with <em>jest.fn().mockImplementation</em> and force it to return the response I want to test with (in this case a successful one). And with that, I assert that two and only two actions have been called and that they are <em>FETCH_DATA_REQUEST</em> and <em>FETCH_DATA_SUCCESS</em>.</p><p>Very similar with the error test case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f82f32e45820096aec0cd85d057b1f43/href">https://medium.com/media/f82f32e45820096aec0cd85d057b1f43/href</a></iframe><p>Well done! Let’s go one step further, remember this?</p><pre><strong>if</strong>(getState().id === id)) {<br>      <strong>return</strong>; // No need to fetch<br>}</pre><p>Well, that might be the most basic caching system in the world. Let’s see how can we easily test that too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49ca9a9bd71506d999ee501ed8354511/href">https://medium.com/media/49ca9a9bd71506d999ee501ed8354511/href</a></iframe><p>See, I am mocking a new store that already has the id 1234 ‘fetched’, so if we dispatch our action, <em>window.fetch</em> should not be called because it is the same id we already “fetched”. Instead, it should be called if it is a different one. As you can see, I don’t even care what fetch returns here so I just make it to return a Promise.</p><p>With that, we got our async action fully covered. But wait! It’s not over, there is a bonus and this is <strong>very</strong> important. Do you remember the import at the beginning of our example action code?</p><pre><strong>import </strong>‘whatwg-fetch’</pre><p>If you or your team forget to use the <em>polyfill</em> version of fetch, Chrome or FF will still work and you won’t notice it! But poor the user who tries to use your website on older versions or other browsers if you know what I mean. For that reason, we will write a unit test to avoid such case too. Look at the <a href="https://github.com/github/fetch/blob/master/fetch.js#L432"><em>polyfill</em> code</a>, it has:</p><pre>self.fetch.polyfill = true</pre><p>Awesome, we can write a test like:</p><pre>it(&#39;makes sure window.fetch is the one from the polyfill&#39;, () =&gt; {<br>  expect(window.fetch.polyfill).toBe(<strong>true</strong>);<br>});</pre><p>Splendid Jest!</p><p>And that’s it my friends, this is actually everything I wanted to show you. If you find a similar example with Jest, please share it because it does get really hard to find them. Thanks to the <a href="http://redux.js.org/docs/recipes/WritingTests.html">Redux docs</a> for the great explanation of how we can test those async actions and for the mocha example (2017 note: They changed the example to use Jest!).</p><p>By the way, this is my first article in Medium, I hope you enjoyed, thanks for reading and hopefully, <em>write</em> you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9054ca28cdcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>