<?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 D. Luu on Medium]]></title>
        <description><![CDATA[Stories by D. Luu on Medium]]></description>
        <link>https://medium.com/@thunho?source=rss-f09fcd0abcd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pJfMPiX8g6CPFzYNQ-YCaw.jpeg</url>
            <title>Stories by D. Luu on Medium</title>
            <link>https://medium.com/@thunho?source=rss-f09fcd0abcd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:08:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thunho/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[Testing React components with Jest and Enzyme]]></title>
            <link>https://medium.com/@thunho/testing-react-components-with-jest-and-enzyme-324a8684aad4?source=rss-f09fcd0abcd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/324a8684aad4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[D. Luu]]></dc:creator>
            <pubDate>Fri, 22 Dec 2017 10:04:02 GMT</pubDate>
            <atom:updated>2017-12-24T08:33:23.087Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a newbie to the React, so I have tried research and write unit test for 2 weeks. The first thing I learned is that it’s bunch of concept these word were flying at me all over the place like Redux, Jest, Enzyme, Mocking, Snapshot, rendering comparison…blabla. Before we start testing, <a href="https://medium.com/powtoon-engineering/a-complete-guide-to-testing-javascript-in-2017-a217b4cd5a2a">here’s</a> awesome article help you get overview Javascript testing.</p><p>In our project, we used Redux. <a href="https://redux.js.org/docs/recipes/WritingTests.html">Here’s great article</a> to start writing test in Redux. In this post, they recommend testing some functions:</p><ul><li>Rendering Component</li><li>Connected Component</li><li>Action Creators</li><li>Async Action Creators</li><li>Reducers</li><li>Middleware</li></ul><p>In this first article, I will focus on testing <strong>React Native components </strong>by mix up Snapshot and shallow rendering.</p><h3>Tooling</h3><p>I’ve tried many tools and finally have found a combination that I like enough to suggest you:</p><ul><li><a href="https://facebook.github.io/jest/">Jest</a>, a testing framework by Facebook;</li><li><a href="http://airbnb.io/enzyme/">Enzyme</a>, a testing utility for React;</li><li><a href="https://github.com/adriantoine/enzyme-to-json">enzyme-to-json</a> to convert Enzyme wrappers for Jest snapshot matcher.</li></ul><h3><strong><em>Testing basic component rendering</em></strong></h3><h4>Rendering Comparison</h4><p>Introduce <a href="http://airbnb.io/enzyme/docs/api/">Enzyme API</a>:</p><ul><li><a href="http://airbnb.io/enzyme/docs/api/shallow.html">Shallow Rendering</a>:</li></ul><p>Shallow rendering renders only component itself without its children. So if you change something in a child component it won’t change shallow output of your component. Or a bug, introduced to a child component, won’t break your component’s test.</p><pre>import { shallow } from &#39;enzyme&#39;;<br><br>const wrapper = shallow(&lt;MyComponent /&gt;);<br>// ...</pre><ul><li><a href="http://airbnb.io/enzyme/docs/api/mount.html">Full Rendering</a>:</li></ul><p>The only way to test the full lifecycle, componentDidMount and componentDidUpdate. Full rendering including child components. Requires a DOM (jsdom, domino). More constly in execution time.</p><pre>import { mount } from &#39;enzyme&#39;;<br><br>const wrapper = mount(&lt;MyComponent /&gt;);<br>// ...</pre><ul><li><a href="http://airbnb.io/enzyme/docs/api/render.html">Static Rendering</a>:</li></ul><p>Only calls render but renders all children.</p><pre>import { render } from &#39;enzyme&#39;;<br><br>const wrapper = render(&lt;MyComponent /&gt;);<br>// ...</pre><p>So, I recommend you some rules:</p><ul><li>Always begin with shallow</li><li>If componentDidMount or componentDidUpdate should be tested, use mount</li><li>If you want to test component lifecycle and children behavior, use mount</li><li>If you want to test children rendering with less overhead than mount and you are not interested in lifecycle methods, use render.</li></ul><p>Example use shallow rendering to test render component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39d88e09f38bf4799b7fcfe2dcfae9a4/href">https://medium.com/media/39d88e09f38bf4799b7fcfe2dcfae9a4/href</a></iframe><p><strong>Rendering comparison sumary:</strong></p><p><strong><em>Pros</em></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><em>Cons</em></strong></p><ul><li>The bigger picture (full render) is complicated to create</li><li>Difficult to write and maintain.</li></ul><h4>Snapshot Testing.</h4><blockquote>Snapshot testing is a way to assert the result of a given test by generating a Json representation of its output.</blockquote><p><em>How does snapshot testing work? </em>The first time your test is run, a Json representation of your expected output is saved to a file. The next time you run the same test, a diff runs between a new and the previously stored snapshot. If there are no differences the test passes, otherwise the test fails and the resulting diff is returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKhCyNyiI9P_s3kD-wPrEg.png" /></figure><p><em>There are 2 ways to create snapshot:</em></p><ul><li>Use react-test-rendering</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ITiCL-98jLi5f1dHkvfLA.png" /></figure><ul><li>Use Enzyme (shallow method) + Enzyme-to-JSON. (Mix shallow Rendering and snapshot). You can check bellow in part <strong>Testing React component connected Redux store.</strong></li></ul><h4><strong><em>Testing render when change props or state.</em></strong></h4><p>We can also easily test the state or props of our component. Update the component by initiating the state and props in the constructor and expanding the click event with the <em>setState()</em> and <em>setProps()</em> function.</p><p>Set up props before testing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dDI_pL0PJ_MlImRgb285Q.png" /></figure><p>Then snapshot with initial props.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqF0lZd6k22Gg4a_Gshinw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RwhvcTVwi7xgmjYEDuHiw.png" /></figure><p>So, you can see, props initial title is ‘ABC’. I’m going to change this title to ‘Google’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zww0TUvJmdMiGAQyT3y4g.png" /></figure><p>And finally, snapshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjYTH7BaXUoZ28rvgM0XUQ.png" /></figure><p>Yeah, with snapshot we can check something change very easy.</p><p><strong>Snapshots summary</strong></p><p><strong><em>Pros</em></strong></p><ul><li>Easy to write</li><li>Easy to check a change and update snapshot.</li></ul><p><strong><em>Cons</em></strong></p><ul><li>Missing a selector API like Enzyme</li><li>Snapshots can be huge and sometimes it might be slow to find the part you are looking for.</li></ul><h4><strong><em>Testing handle input function in the component.</em></strong></h4><p>With testing handle input function, our goal is to determine that <em>when a user interacts with our app</em>, <em>the appropriate functions are called</em>.</p><p>We are going to create a test case to check whether the <em>onPress</em> event of <em>TouchableOpacity</em> is being called. Our click events triggers an props <em>onLeftButtonClicked</em> and we can easily mock this functionality in Jest by using <a href="http://facebook.github.io/jest/docs/jest-object.html#jestfnimplementation"><em>jest.fn()</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yILDp_Ay-zKhjev6JlGcfg.png" /></figure><p>After shallow rendering our component we’re simulating a <em>onPress()</em> event and check if the props <em>onLeftButtonClicked</em> is being called. With <em>onPress</em> event use call simulating directly by using <em>props().onPress() </em>but in others event, we have to use <em>simulate()</em> to simulate event.</p><h3>Testing React component connected Redux store.</h3><p>One of the painful parts of testing a Redux container is that we can’t just render a container. That’s because container will ask for the Redux store when you connect your component to Redux, and without it, test fails.</p><p>So, before we start to write testing code, we will need a “Redux wrapper” for all of our testing components to provide Redux store. Luckily, Enzyme provides a <a href="http://airbnb.io/enzyme/docs/api/shallow.html#arguments">shallow-render function</a> that can take a context as second parameter, where we can put a Redux store for our tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdtkm7UbeJUDXqYGQTLyhw.png" /></figure><p>In order to put those in a mock store our test can use, we first create our <em>testState</em> object. Then pass that object into the <em>mockStore()</em> function from <em>redux-mock-store. </em>Next, we pass the mocked store to our connected component adding a second argument to the shallow function in <em>shallowWithStore</em>.</p><p>Finally, to render the snapshot of our connected component we use connectComponent.dive() to access the actual render output of our component for the snapshot (otherwise wrapper will represent the connect function):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3Qr7MohWonHOB5P8QTytQ.png" /></figure><p>Final</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13e377d02ac6521339f01504a02a4f2a/href">https://medium.com/media/13e377d02ac6521339f01504a02a4f2a/href</a></iframe><h3>Summary</h3><p>I hope this post will help you write your own React component tests. To summarize:</p><ul><li>Can only use snapshot to test unconnected component. It’s very useful and quickly.</li><li>Should use both snapshot and shallow rendering to wrap connected component.</li></ul><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=324a8684aad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>