<?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 Gaston Nicolas on Medium]]></title>
        <description><![CDATA[Stories by Gaston Nicolas on Medium]]></description>
        <link>https://medium.com/@gastonnicolas?source=rss-4e448722348------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_KRt-Pk0DekTO42onRT6RA.jpeg</url>
            <title>Stories by Gaston Nicolas on Medium</title>
            <link>https://medium.com/@gastonnicolas?source=rss-4e448722348------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:49:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gastonnicolas/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[Taking a quick look at Testing ]]></title>
            <link>https://medium.com/@gastonnicolas/taking-a-quick-look-at-testing-5fd23300cdc2?source=rss-4e448722348------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd23300cdc2</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[enzyme]]></category>
            <dc:creator><![CDATA[Gaston Nicolas]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 10:38:00 GMT</pubDate>
            <atom:updated>2019-04-12T09:59:35.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>Taking a quick look at Testing 🧪</h3><p>This article aims to give you a whole introduction to the benefits of testing in general and some key points to keep in mind if you decide to involve testing in your development. <br>It is plenty of articles with consistent examples of testing code with Jest and Enzyme, so I won’t go in depth with code, instead I will present approches, tips and best practices related to it.<br>Due to the fact that I am a React.js developer, examples and notes will be written in javaScript. Before diving into it, I would like to make a brief introduction about some concepts that we need to know. <br>Let’s go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0KtlF9SMjC7lO5RV" /><figcaption>Photo by <a href="https://unsplash.com/@nicolasthomas?utm_source=medium&amp;utm_medium=referral">Nicolas Thomas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Concepts 📓</strong></h3><p><em>You can take a quick peek and keep going until it make sense to you. It is just to put on the table all the tools we have.</em></p><ul><li><strong>Testing</strong>: It is a procedure to verify and describe whether the actual results match the expected results. Also it helps to reduce the amount of bugs in the system (yeah, just reduce, not to kill them all 😅).</li><li><strong>Unit Testing</strong>: Tests the smallest unit of functionality (method, function, component). They shouldn’t call collaborators, access the network, hit a database or use the file system. Any outsider dependency should be mocked or stubed.</li><li><strong>Integration Testing</strong>: Combines the units of code to test that the resulting combination works properly.</li><li><strong>End to End (E2E)</strong>: Tests the whole application from beginning to end. With E2E, you prove that all pieces of your application works together as expected.</li><li><strong>Snapshot Testing: </strong>It is a rendered output of your component stored in a text file. You basically “take a photo” of your graphical UI and save it. Later, if anything change in the UI, the snapshot will fail. You could accept changes and overwrite the last one or correct the wrong behavior. It is very useful for screens that does not change a lot. If not, you will be constantly updating it. <br>A login form is an example of a screen that <em>probably </em>does not scale and its very suitable for snapshot testing.</li><li><strong>Mock</strong>: It is a fake implementation replacing a real one. We use mocks to replace something we don’t control with something we actually do. It allows us to capture calls, set return values and change implementation. <br>In a nutshell, with mocks we can isolate the component under test from the rest of the system.</li><li><strong>Stub</strong>: A stub is very similar to a mock. The main difference is that stubs use state verification instead of behaviour verification (doesn’t matter now, but it will be important to notice that there is a difference between mock and stub).</li><li><strong>Spy</strong>: It is a mixed between mocks and stubs. Spy is the real object with some methods shadowed by stub methods. This way you can have a real object with the minimun fake behavior.</li><li><strong>Coverage</strong>: It is an indicator of the amount of testing performed by a set of test cases.</li><li><strong>TDD</strong>: Technique that relies on the repetition of a cycle to perform testing. It is just a way to acquire a procedure in the way we test.<br>It could be summed up in what René Descartes said:</li></ul><blockquote>I test, therefore I code</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FpI2paNxecnUNW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FpI2paNxecnUNW%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FpI2paNxecnUNW%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="257" frameborder="0" scrolling="no"><a href="https://medium.com/media/325d9e5a6296b3a3dcc38a9af7cb5311/href">https://medium.com/media/325d9e5a6296b3a3dcc38a9af7cb5311/href</a></iframe><h3><strong>Jest &amp; Enzime</strong></h3><ul><li>Jest is the test runner 🏃.</li><li>Enzyme is a testing utility 🔨 for react that makes it easier to make assertions and provide additional testing utilities to manipulate elements.</li></ul><p>You can use Jest in other javaScript app, but enzyme <strong>only </strong>works with react.<br>You can use Jest without Enzyme or any other testing library. <br>However, you <strong>can not</strong> use just Enzyme because you need a test runner (Jest or any other like Mocha o Jasmine).</p><h3>The skeleton of a test</h3><p>First of all, we need to create the minimun valid squeleton to perform a test:</p><pre>import React from &#39;react&#39;;<br>import Counter from &#39;../Counter&#39;;<br>import {shallow} from &#39;enzyme&#39;;</pre><pre>describe(&#39;&lt;Counter /&gt;&#39;, () =&gt; {<br>  let wrapper;</pre><pre>  beforeEach(()=&gt;{<br>    wrapper = shallow(&lt;Counter /&gt;);<br>  })</pre><pre>  describe(&#39;render&#39;, () =&gt; {</pre><pre>    it(&#39;should have a button&#39;, () =&gt;  <br>        expect(wrapper.find(&#39;button)).toHaveLenght(1))         <br>    });<br>  });</pre><pre>  describe(&#39;interactions&#39;, () =&gt; {  //... })<br>  describe(&#39;inner methods&#39;, () =&gt; { //... })</pre><pre>})</pre><p>Each describe block will test one part of the component: render, interactions (events or state changes), inner methods and whatever you think it is important to reflect.</p><ul><li><strong>beforeEach</strong>: Runs a function before each of the tests in this file runs. (Important! Any promise or generator inside, Jest will wait for that to be resolved).We use it to setup some configuration or state before running each assertion.</li><li><strong>afterEach</strong>: Like the previous one, but used to clean o reset state.</li><li><strong>shallow</strong>: It is used to render the single component that we are testing isolated. The key to understand it is: <em>it does not render child components</em>.<br>When you perform a shallow, Enzyme calls constructor, render and componentDidMount (Enzyme &gt; 3).</li><li><strong>mount</strong>: Unlike the shallow method, mount renders the full DOM including the child components of the parent component that we are running the tests. This is costly in execution time.</li></ul><h4>¿Should I use mount or shallow?</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUPJPzcdlbvaFUrF7y%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUPJPzcdlbvaFUrF7y%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbWJmNXNiMnVlcm1jNm1qdmpkOWFuNjBzemMwb2E4OGQ0YTZxbmlrMSZlcD12MV9naWZzX2dpZklkJmN0PWc%2FxUPJPzcdlbvaFUrF7y%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/76e7d60efda5cfba5e0455f349bbbb06/href">https://medium.com/media/76e7d60efda5cfba5e0455f349bbbb06/href</a></iframe><p>Well, this is a whole issue that ended up in a new library named <strong>react-testing-library</strong> where his creator (Kent C Dodds) express that shallow is not real testing because we are not perfoming testing from the user’s point of view. Instead, you are testing implementation. So he decided to create his own library where you just use mount method.<br>On the other hand, Enzyme let you choose between both approaches.</p><p><a href="https://kentcdodds.com/blog/why-i-never-use-shallow-rendering"><em>(Link to the article on the footer or here)</em></a></p><h3><strong>Best Practices ✔️</strong></h3><p><em>Doing testing on my team let me some key points I would like to share. Some of them are more subjectives.</em></p><ul><li>Use one testing file por each component. No more than that. <br>Clear responsabilities.</li><li>Using declarative statements in “describe” and “it” methods let us understand the component. It is also important to maintain a convention in the way we express our tests.</li><li><strong>Do not test implementation</strong><br>We shouldn’t call explicitly lifecycle methods, React already does it. Remember that we are testing functionality from the User’s perspective. The user does not know if we call componentDidMount (I am sure he doesn’t).</li><li><strong>Decide Setup carefully</strong> <br>Using beforeEach instead of beforeAll may be significant. Evaluate each scenario. <br>Important: try to do the setup inside beforeEach or beforeAll handlers if possible, because jest executes all describe handlers in a test file before it executes any of the actual tests.<br>Try to encapsulate the whole setup for a test in the “it” method if possible.</li><li><strong>Do not relay on order execution</strong><br>Once the describe blocks are complete, Jest runs all the tests in the order they were found. In spite of that, each assertion should be<br>independent from the rest. So, in some scenarios I recommend you to switch “it” blocks to prove that they are still passing. If not, you have side effects.</li><li><strong>One expectation inside one “it” method</strong><br>Testing more than one thing at the same time make it difficult to detect the one that is not passing later.</li><li><strong>Do not code in testing (foreach, if etc) </strong><br>If you are introducing code in testing, then you should test your coding test. I know it looks weird that sometimes you are repeting lines of code that could automate but that’s the only way to reduce side effects. Our main goal in testing is to prove that functionality is working from the user’s perspective.</li><li><strong>Avoid using useless tests</strong> like: <br> <em>expect(component.render).toBe(true)</em><br>It does not add any value. If component does not render, you will figure it out in the following cases.</li><li>Get together with your team and define the way you are going to test. It is no enough to know the Enzyme and Jest API if each developer test a component in a different way. <br>For example, you could agree with your team that you are going to test a component in this way: <br><strong>1)</strong> Props sent to the component.<br><strong>2)</strong> Render. Check that everything you try to render is actually being rendered.<br><strong>3)</strong> Events. change, click or any other event that performs interactions with the state should be tested to prove that it is working as desired.<br><strong>4)</strong> Inner methods. As pure functions, you expect that a function receive an input and return an output.<br><strong>5)</strong> Special cases you consider important. More tests cases does not implies better chance that your app works properly. <br>In science we know a phenomenon called <strong>Confirmation bias</strong> that happens when we strongly support an hypothese and we try to confirm it searching for favor information or interpreting it in a way that give us the truth. <br>Do not test the easiest way just to feel like you are a good tester. Test the border cases, challenge your app and try to make it explode. If you can do it, then testing is being useful. If not, you are just generating useless code that you will have to maintain.</li><li><strong>Converage indicator</strong><br>Decide the coverage indicator with your team. In the beginning, we are gonna be tempted to strive for 100% coverage. But are we really convinced on testing? Do we have the expertise? Do we have realistic deadlines? If not, you will have to be less demanding. It could be a motivation to enforce testing or you will finally end up reducing coverage indicator. Every team will decide after all.<br>Remember also that code coverage is not equal to quality of tests. You could easily fool coverage. If you put a high coverage indicator and then you need to push for deadline, then you are gonna be tempted to take a shortcut that you are totally going to undo when the dust has settle <br>(No chance! That is not going to happen).</li><li><strong>API calls</strong><br>DO NOT perform real API calls in testing. It could just lead you to pain. Testing api calls trying to really call them may be dangerous.<br>If the API goes down, the test will fail with no reason at all. <br>If the API cost money, worse. <br>If the API slow down your test will break. <br>That’s why we have mocks. Are you testing the API? Not a chance! I hope their developers have already done that. We are testing <strong>our </strong>component consuming that API. So, we are going to fake any desirable output and work with it.</li><li><strong>Dive method (Just for Enzymers) </strong><br>Do not abuse dive() method. Due to the fact that shallow rendering only render parent component, we could need access to his first child and then dive method from Enzyme API allow us to obtain a wrapped child. Maybe there are some scenarios where this is useful, but if it becomes an habit, then review the way you are testing, because the main idea of using shallow rendering is to <strong>isolate component under test of the rest.</strong></li><li><strong>Integration testing</strong><br>Unit testing are necessary to prove that a component works fine in its own but that does not garantee that its interactions with other components are OK too. <br>A meaningfull set of integration tests is very important. Imagine that you have a component A with a button inside it that allows you to<br>navigate to another screen, where it is rendered component B. Unit tests in component A pass. Unit tests in B pass too. Integration test navigation and it fails.<br>What happened? Well, remember that unit testing has a boundary: mocking external dependencies or interactions. Maybe both components are mocking what they expect to receive from each other, but in the reality, where dependencies are not under your control, this is wrong. Only with integration testing you could prove collaboration between your components.</li><li><strong>Testing asynchronously.</strong> <br>Jest needs to know when the code it is testing has completed before it can move on to another test. Jest proposes more than one approaches<br>in his documentation. Async/Await worked fine for me and it can be combined with resolves/rejects approach too.</li></ul><h3>Integration testing</h3><p>This deserve a whole different article but I would like to introduce the topic.</p><p>Once you start with integration testing you will discover that even if the functionality itself it’s pretty simple to prove, to cover all the combinations you would have to repeat code. <br>It could also happen that you have too many combinations. Mounting is not free.<br>What do we do then?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT1XGv5SmVjoFgMYda%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT1XGv5SmVjoFgMYda%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxT1XGv5SmVjoFgMYda%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c572b43635594febee8929c0e197dc3/href">https://medium.com/media/0c572b43635594febee8929c0e197dc3/href</a></iframe><p>From my point of view, integration testing require more decisions than unit testing. Regarding unit testing, we could say that we need one file per component and that’s all. <br>Integration involves more than one component, so I would say that integration relays <strong>more on use cases</strong>. Instead of testing the interaction bewteen two components, why don’t you test a real scenario that involves both of them? Is it significant to develop each scenario or I can test the most representative?<br>Even if leaving untested cases could not be the best choice, remember that we made good unit tests (I hope so). So it should be covered.</p><h3>Conclusion 🔚</h3><p>I hope you have now all all the options over the table.</p><p>For those who are already testing, I hope to contribute to you. <br>For those who are diving into testing, I hope that it encourages you too finally do it. I wasn’t a big fan of testing because I did not know how to do it. I had the chance to work in a project where testing were required and I realized that I could make the most of it. <br>As I said at the beginning, the way of testing is not coming to an agreement. Some of you are more into mounting because it is more real than just faking it with shallow.</p><p>Nowadays, some projects are still considering testing an unnecesary luxury. I can imagine that must be difficult to justify the investment of time on an activity that won’t produce any visual delivery. However, are you, as a developer, going to spend hours trying to solve nasty bugs just because someone decided that testing was off the table?</p><p>Anyway, the most important is to find, as a team, a provable way to demonstrate that your components works as you expect and even more, to protect yourselves from future bugs. <br>Testing is locking behavior.</p><h3>Related Links 🔗</h3><ul><li><a href="https://blog.pragmatists.com/test-doubles-fakes-mocks-and-stubs-1a7491dfa3da">Test doubles, mocks and stubs</a></li><li><a href="https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c">Understanding Jest mocks</a></li><li><a href="https://jeroenmols.com/blog/2017/11/28/coveragproblem/">The 100% coverage problem</a></li><li><a href="https://medium.com/codeclan/testing-react-with-jest-and-enzyme-20505fec4675">Testing react with Jest and Enzyme</a></li><li><a href="https://kentcdodds.com/blog/why-i-never-use-shallow-rendering">Why I never use Shallow rendering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd23300cdc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>