<?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 Romario on Medium]]></title>
        <description><![CDATA[Stories by Romario on Medium]]></description>
        <link>https://medium.com/@romarioraff?source=rss-805e668fccc4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z1mdtAQM__9CMgjyZxnLSg.jpeg</url>
            <title>Stories by Romario on Medium</title>
            <link>https://medium.com/@romarioraff?source=rss-805e668fccc4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:52:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@romarioraff/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[January 1st 2018.]]></title>
            <link>https://medium.com/@romarioraff/january-1st-2018-d068c4602fb5?source=rss-805e668fccc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d068c4602fb5</guid>
            <category><![CDATA[new-year-resolution]]></category>
            <category><![CDATA[2018]]></category>
            <category><![CDATA[new-year]]></category>
            <category><![CDATA[goals]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Romario]]></dc:creator>
            <pubDate>Tue, 02 Jan 2018 00:04:55 GMT</pubDate>
            <atom:updated>2018-01-02T00:09:12.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiGd2PcTj4cB5dD7IzXCuQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/BRBjShcA8D4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brooke Lark</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>It’s January 1st, the start to a new year. This month, your gym and favorite running spot will be packed with <em>new year resolutionist</em>. Don’t worry, in a month or two everything will go back to normal. This seems to be the trend each year.</p><p>This year I won’t be making any new year resolutions. Instead, I’ll be setting daily goals. You see, new year resolutions are quite often empty promises we make to ourselves and the truth is most of us won’t accomplish these goals. It just makes us feel good.</p><p>This year is going to be different. This year I’ll be taking a new direction. <em>After all, one of the meanings of the number </em><strong><em>8 </em></strong><em>is new direction.</em> This year, I’ll be setting daily goals. Here’s why:</p><h3>1. Small + Measurable =👏</h3><p>Daily goals are smaller and more easily measured. These smaller goals will allow you to focus on the task at hand and force you to concentrate your efforts on tasks that are important for that day.</p><p>Also tracking daily goals are often easier. You can measure at any point in time how far off you are from completing a goal. Then you can make the necessary adjustments each day to ensure your targets are met.</p><h3>2. Constant Feedback</h3><p>With daily goals, you constantly get feedback. At the end of each day you can see where you need to improve and make adjustments to ensure you are more efficient the next day. This constant feedback will allow you to continuously improve and draw you closer to the main goal.</p><h3>3. Short-term Motivation</h3><p>Daily goals tend to keep you motivated. Having daily goals gives you a sense of purpose. However, be sure not to make these goals too easy as you won’t be as motivated to complete them.</p><p>Also keep in mind, the more goals you achieve, the more confident you become. At times when I become demotivated, visualizing the end results helps!</p><h3>4. Consistency</h3><p>Setting daily goals helps with consistency as each day you’ll be working on minor goals that will allow you to accomplish the main goal. Being consistent is very hard and having a list of daily tasks will be of help for sure.</p><p><em>…And remember, even when you don’t feel like it, just accomplishing one of your daily goals will push you closer to your destination.</em></p><h3>5. Staying Organized</h3><p>Everyday we are bombarded with new challenges and often times it’s easy for us get disorganized. Writing down your daily goals helps with organizing your thoughts and clearing your mind. In return, this helps with staying focus on the most important tasks for the day that aligns with your “top tier” goals.</p><p><em>Conclusion</em></p><p>New years resolutions are cool and it definitely works for some but I strongly believe daily goals yields better results. I encourage you to set and work towards accomplishing daily goals. <strong>I promise you, your 2018 will be full of more success.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d068c4602fb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Apps with Jest and chai-enzyme for Beginners]]></title>
            <link>https://medium.com/@romarioraff/testing-react-apps-with-jest-and-chai-enzyme-for-beginners-baa5f57cec0b?source=rss-805e668fccc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/baa5f57cec0b</guid>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[chai]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[Romario]]></dc:creator>
            <pubDate>Wed, 22 Feb 2017 12:50:03 GMT</pubDate>
            <atom:updated>2017-08-25T17:37:09.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ogragj2w9CKcL00UUmP2Kg.png" /></figure><blockquote>“Testing is an infinite process of comparing the invisible to the ambiguous in order to avoid the unthinkable happening to the anonymous.” — James Bach</blockquote><h3><strong>Introduction</strong></h3><p>In July, I completed the first <a href="https://github.com/romarioraffington/react-mybooks">project</a> for the Udacity <a href="https://www.udacity.com/course/react-nanodegree--nd019">React Nanodegree </a>Program. Having a QA background, I decided to write unit tests to ensure functionality didn’t break as I added new features.</p><p>After completing the project I decided to share it with my classmates via slack. Many of my classmates were impressed and I started receiving questions like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*ZrkSCG7pZgIq71CRQBxYYg.png" /></figure><p>I recommend a few tutorials, books and blog posts (see the <em>Recommended Resources </em>section).</p><p>Most of the resources I recommended, however, showed examples instead of explaining the thought process behind writing certain tests. In my opinion, the “why” is more important because that knowledge can be transferred onto testing other React apps.</p><p>It’s like the old saying — you give a man a few examples and he can only test a few scenarios. Tell a man the “why” and he can apply it to many other scenarios… or something like that 😶.</p><p>In this article, I assume you have some experience with React, JavaScript (ES6) and NPM. We’ll talk about:</p><ol><li>Testing Tools 🔨</li><li>Folder Structure 🏗</li><li>Thought Process 🤔</li><li>Creating Tests 👨‍🔬</li><li>Running the Tests 🏃</li><li>Recommended Resources 📚</li></ol><h3>Testing Tools 🔨</h3><p>The tools I use in the unit testing process:</p><ul><li><a href="https://facebook.github.io/jest/"><strong>Jest</strong></a><strong> </strong>- A test runner (similar to <a href="https://mochajs.org/">mocha</a>) that was built by Facebook to test JavaScript applications. I like Jest because it’s easy to setup, fast, has cool features like snapshot testing and it comes built in with code coverage and mocking.</li><li><a href="https://github.com/producthunt/chai-enzyme"><strong>chai-enzyme</strong></a> - <a href="http://airbnb.io/enzyme/"><em>Enzyme</em></a> is a testing utility for React that allows developers to easily assert and manipulate components. <a href="http://chai/"><em>Chai</em></a> is an assertion library for node and the browser. <a href="https://github.com/producthunt/chai-enzyme"><em>chai-enzyme</em></a> uses chai-like assertions to test React applications with enzyme.</li></ul><p>I like to use <em>chai-enzyme</em> because it makes assertions more readable. For example:</p><pre>// Using chai-enzyme <br>expect(wrapper.find(&#39;#id&#39;)).to.be.present()</pre><pre>// Using enzyme<br>expect(wrapper.find(&#39;#id&#39;)).to.have.length(1)</pre><ul><li><strong>Faker </strong>- A library that generates fake data.</li></ul><pre>faker.name.findName() // Usain Bolt</pre><h3>Folder Structure 🏗</h3><p>Code is read more than it is written and so it is important to structure your project in such a way that allows files to be easily located.</p><p>I organize files based on <strong>feature</strong> instead of <strong>type</strong>. A feature-based folder structure allows for test files to be easily located.</p><p>Organization by Feature</p><pre>/components<br> /Book<br>   index.js // Component<br>   index.spec.js // Test</pre><p>Organization by Type</p><pre>/components<br> /Book<br>   index.js // Book Component</pre><pre> /Tests <br>   book.spec.js // Test</pre><p>Here’s a <a href="https://softwareengineering.stackexchange.com/questions/338597/folder-by-type-or-folder-by-feature">stackexchange answer</a> explaining more about the pros and cons of the two folder structures.</p><h3>Thought Process 🤔</h3><p>Here are a few things I keep in mind when unit testing React apps:</p><h4><em>Mocking Modules, Clearing Mocks and Fake Data</em></h4><p>I usually start off my tests by creating mocks. That is, I mock functions / files that the component I’m testing uses. I mock functions using jest.fn() in the first describe method then clear the mock in the afterEach hook in that same describe method. This ensures that each test receives a freshly mocked function as they may be cases where subsequent tests/beforeEach functions modify the mocked method. Similarly, I create the fake data in the first describe to allow that data to be utilized in subsequent tests.</p><h4><em>Initial State</em></h4><p>I test the initial state to ensure that the component initialized the state correctly. This step is not necessarily needed because we can assume that the initial state that was specified will be rendered correctly by React.</p><p>However, it is good to have a test to verify that the initial state was initialized correctly before manipulating the state for other test scenarios. Ultimately, the granularity of your tests is a decision that you and your team would have to make before writing tests.</p><h4><em>Events(e.g Button click)</em></h4><p>I simulate events then assert that the state, props and the component change as expected. This simulation is done in the beforeEach hook and the assertions are carried out in the tests. Essentially, the beforeEach hook is used to setup scenarios to be tested.</p><h4><em>One Assertion per Test</em></h4><p>I try to limit each test to one assertion. If a test should fail, I can easily pick out the failed assertion.</p><h4><em>Behavior Driven Testing (BDD)</em></h4><p>This is an approach that is geared towards testing the behavior of the application instead of the implementation. BDD is a great way of unit testing React applications, since state and props change based on behavior. An example of BDD testing:</p><pre>describe(&#39;Search&#39;, () =&gt; {<br>    <br>   ... // before hooks, setup mocks, generate fake data</pre><pre>  describe(&#39;when a user types in the search box&#39;, () =&gt; { <br>    ... // tests</pre><pre>     describe(&#39;when the user clicks the search button&#39;, () =&gt; {<br>       ... // tests</pre><pre>       describe(&#39;when the user clears the search field&#39;, () =&gt; {<br>         ... // tests<br>       })<br>    )}<br>  })<br>})</pre><h3>Creating Tests 👨‍🔬</h3><h4>The Application</h4><p>I created a simple <a href="https://react-filterable-product-table.herokuapp.com/">filterable product table</a> (inspiration taken from the <a href="https://facebook.github.io/react/docs/thinking-in-react.html#step-1-break-the-ui-into-a-component-hierarchy">React docs</a>) that filters a list of products as the user types in the search box. The application also has a “<em>Only show products in stock”</em> checkbox that filters the product list based on the products that are in stock.</p><p>The app is broken down into 5 components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*64vaJYBqievcg4gTvfo2AQ.png" /><figcaption>Image taken for the React docs</figcaption></figure><ul><li>FilterableProductTable (orange): contains the entirety of the example</li><li>SearchBar(blue): receives all user input</li><li>ProductTable(green): displays and filters the data collection based on user input</li><li>ProductCategoryRow (turquoise): displays a heading for each category</li><li>ProductRow(red): displays a row for each product</li></ul><h4>Getting Started</h4><p>To get started, clone or fork <a href="https://github.com/romarioraffington/react-filterable-product-table">this repository</a>, and checkout the start-template branch. This branch contains the React app without the tests.</p><h4>Creating Test Data</h4><p>The FilterableProductTable requires an array of products to be passed in as props. Let’s create some test data using faker that we can use in our tests.</p><p>Steps:</p><ol><li>npm install faker --save-dev</li><li>Create a testData.js file in src/utils</li><li>Create a generateProduct function to generate test data for a single product and a generateProductList function to generate a product list.</li></ol><pre>// testData.js</pre><pre>import faker from &#39;faker&#39;;</pre><pre>export const generateProduct = () =&gt; ({<br>  category: faker.lorem.word(),<br>  price: faker.commerce.price(),<br>  stocked: faker.random.boolean(),<br>  name: faker.commerce.productName(),<br>});</pre><pre>export const generateProductList = (count = 4) =&gt; {<br>  const products = [];<br>  for (let i = 0; i &lt; count; i++) {<br>    products.push(generateProduct());<br>  }<br>  return products;<br>}</pre><p><em>View the </em><a href="https://github.com/romarioraffington/react-filterable-product-table/commit/681f2b4251abe81236ba406eba2dbe018f768b75"><em>commit</em></a><em>.</em></p><h4>Configure chai to use chai-enzyme</h4><ol><li>npm install chai chai-enzyme --save-dev</li><li>Create a chai.js file in src/utils .</li></ol><pre>import chai from &#39;chai&#39;;<br>import chaiEnzyme from &#39;chai-enzyme&#39;;</pre><pre>chai.use(chaiEnzyme());<br>export const expect = chai.expect;</pre><p>We will import this file in our test to do assertions.</p><p><em>View the </em><a href="https://github.com/romarioraffington/react-filterable-product-table/commit/9a4a8179b36c7add6a773fea5da40b1470fb6b3a"><em>commit</em></a><em>.</em></p><h4>FilterableProductTable Tests</h4><ol><li>npm install react-test-renderer enzyme --save-dev</li></ol><p>2. Create a test file in the components folder called index.spec.js and import the dependencies.</p><pre>// External Depedencies<br>import React from &#39;react&#39;; <br>import faker from &#39;faker&#39;<br>import { shallow } from &#39;enzyme&#39;;</pre><pre>// Our Dependencies<br>import { expect } from &#39;../../utils/chai&#39;;<br>import { generateProductList } from &#39;../../utils/testData&#39;;</pre><pre>// Our Component<br>import FilterableProductTable from &#39;./index&#39;;</pre><p>3. In the beforeEach hook we are going to shallow render our component. We will also generate a list of products using our generateProductList util function since our component need a list of products as props.</p><pre>describe(&#39;FilterableProductTable&#39;, () =&gt; {<br>  let wrapper;<br>  const products = generateProductList();</pre><pre>  beforeEach(() =&gt; {<br>    wrapper = shallow(<br>      &lt;FilterableProductTable<br>         products={products}<br>      /&gt;<br>    )<br>});</pre><p>4. As mentioned in the Thought Process section above, my first tests usually verify that the state was correctly initialized.</p><pre>it(&#39;should initialize the filterText state to empty string&#39;, () =&gt; {<br>  expect(wrapper).to.have.state(&#39;filterText&#39;).to.equal(&#39;&#39;);<br>});</pre><pre>it(&#39;should initialize the inStockOnly state to false&#39;, () =&gt; {   <br>  expect(wrapper).to.have.state(&#39;inStockOnly&#39;).to.equal(false);<br>})</pre><p><em>View the </em><a href="https://github.com/romarioraffington/react-filterable-product-table/commit/de9aba8957c6088c10afb26fa36984265bb2760d"><em>commi</em></a><em>t.</em></p><p>5. The component has two functions, handleFilterTextInput and handleInStockInput that are responsible for updating the filterText and inStockOnly state respectively. To test these functions, I will use the wrapper.instance().${functionName} to invoke the functions then assert that the state changes accordingly.</p><pre>it(&#39;should update the state filter to the correct value&#39;, () =&gt; {<br>  const filterText = faker.lorem.word();<br>  wrapper.instance().handleFilterTextInput(filterText);<br>  expect(wrapper).to.have.state(&#39;filterText&#39;).to.equal(filterText);<br>});</pre><pre>it(&#39;should update the state inStockOnly to true&#39;, () =&gt; {<br>  wrapper.instance().handleInStockInput(true);<br>  expect(wrapper).to.have.state(&#39;inStockOnly&#39;).to.equal(true);<br>});</pre><p><em>View the </em><a href="https://github.com/romarioraffington/react-filterable-product-table/commit/7a189bdd8a212d56b69c147ef865f784592c0b67"><em>commi</em></a><em>t.</em></p><h4>SearchBar Tests</h4><p>Let’s move on to testing theSeachBarcomponent.</p><p>Importing dependencies:</p><pre>// External Depedencies<br>import React from &#39;react&#39;;<br>import faker from &#39;faker&#39;;<br>import { shallow } from &#39;enzyme&#39;;</pre><pre>// Our Dependencies<br>import { expect } from &#39;../../../utils/chai&#39;;<br>import { generateProductList } from &#39;../../../utils/testData&#39;;</pre><pre>// Our Component<br>import SearchBar from &#39;./index&#39;;</pre><p><em>Setting up our tests:</em> We will mock our functions, clear our mocks and create fake data here.</p><pre>describe(&#39;SearchBar&#39;, () =&gt; {  <br>  let wrapper;    <br> <br>  const onFilterTextInput = jest.fn(),    <br>    onInStockInput = jest.fn(),      <br>    filterText = faker.lorem.word();   </pre><pre>    beforeEach(() =&gt; {    <br>      wrapper = shallow(      <br>        &lt;SearchBar <br>          onFilterTextInput={onFilterTextInput}        <br>          onInStockInput={onInStockInput}        <br>          filterText={filterText}        <br>          inStockOnly={false}      <br>        /&gt;    <br>       )<br>    });   </pre><pre>  afterEach(() =&gt; {    <br>    onFilterTextInput.mockClear();    <br>    onInStockInput.mockClear();  <br>  });</pre><p>For our tests, we can verify that the:</p><ul><li>onChange functions are called the correct number of times.</li></ul><pre>describe(..., () =&gt; {</pre><pre>  beforeEach(() =&gt; {<br>    value = faker.lorem.word();<br>    const input = wrapper.find(&#39;input&#39;).first();<br>  <br>    input.simulate(&#39;change&#39;, {<br>      target: { value }<br>    });<br>  });</pre><pre>  it(&#39;should call onFilterTextInput once&#39;, () =&gt; {<br>    expect(onFilterTextInput.mock.calls.length).to.equal(1);<br>  });<br>})</pre><ul><li>onChange functions are called with the correct value</li></ul><pre>it(&#39;should call the onFilterTextInput with the right value&#39;, () =&gt; {<br>  expect(onFilterTextInput.mock.calls[0][0]).to.equal(value);<br>});</pre><ul><li>Search input has the value of the filterText</li></ul><pre>it(&#39;should initialize search input to the filterText value&#39;, () =&gt; {<br>  const input = wrapper.find(&#39;input&#39;).first();<br>  expect(input).to.have.value(filterText);<br>});</pre><ul><li>Checkbox is checked whenever the inStockOnly prop is true</li></ul><pre>describe(&#39;...&#39;, () =&gt; {</pre><pre>  beforeEach(() =&gt; {<br>    wrapper.setProps({<br>      inStockOnly: true, // Set inStockOnly prop to true<br>    });<br>  });</pre><pre>it(&#39;should check the &quot;Only show products in stock&quot; checkbox&#39;,() =&gt; {<br>    const checkbox = wrapper.find(&#39;p input&#39;).first();<br>    expect(checkbox).to.be.checked();<br>  });<br>});</pre><p>It’s pretty much the same for theonInStockInput tests but instead of changing the target.value we’re going to change the target.checked value.</p><p>Instead of:</p><pre>input.simulate(&#39;change&#39;, {<br>  target: { <strong>value</strong> }<br>});</pre><p>We’ll do:</p><pre>checkbox.simulate(&#39;change&#39;, {<br>  target: { <strong>checked: true</strong> }      <br>});</pre><p><em>View the </em><a href="https://github.com/romarioraffington/react-filterable-product-table/commit/5d928af2f05fed65a81b987186a12f6c2c639313"><em>commit</em></a><em> for all the tests.</em></p><p>The ProductRow , ProductCategoryRow and ProductTable components also need to be tested. Feel free to submit a PR, I think this would be a fun exercise.</p><h3>Running the Tests 🏃</h3><p>Running npm test should get the tests running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aSa4Q2Rsn6An3_l_zMPog.png" /><figcaption>The test results should look something like this</figcaption></figure><h3>Recommended Resources 📚</h3><ul><li>Lessons 22- 25 for 30 Days of React by FullStackReact <a href="https://www.fullstackreact.com/30-days-of-react/">#</a></li><li>FullStackReact book has an amazing testing chapter. I highly recommend this book! <a href="https://www.fullstackreact.com/">#</a></li><li>Good Practices for Testing React Apps by <a href="https://medium.com/@TuckerConnelly?source=post_header_lockup">Tucker Connelly</a> <a href="https://medium.com/@TuckerConnelly/good-practices-for-testing-react-apps-3a64154fa3b1">#</a></li><li>Unit Testing React Components: Jest or Enzyme? <a href="https://www.codementor.io/vijayst/unit-testing-react-components-jest-or-enzyme-du1087lh8">#</a></li><li>Testing React Applications with Jest <a href="https://auth0.com/blog/testing-react-applications-with-jest/">#</a></li><li>Testing React Components with Enzyme and Jest video tutorial <a href="https://www.youtube.com/watch?v=u5XTnNBotqs">#</a></li></ul><h3>Conclusion</h3><p>I hope you’re not afraid anymore when it comes to unit testing your React apps. Testing can be fun 🌝 and it can end up saving you lots of time as your app scales. I hope that you find this article useful or at least learnt something new.</p><p>I published on my Github account a more complex React project that contains more complex testing scenarios. You can find it here: <a href="https://github.com/romarioraffington/react-mybooks">https://github.com/romarioraffington/react-mybooks</a>.</p><p>Feel free to add a response below or contact me directly if you have any questions or any suggestions on how to make this article better.</p><p>Hi, I’m Romario! I’m a Javascript application developer who has been programming for over 6 years. I ❤️ creating scalable, quality applications and writing articles about interesting technologies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baa5f57cec0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>