<?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 Ramon Prata on Medium]]></title>
        <description><![CDATA[Stories by Ramon Prata on Medium]]></description>
        <link>https://medium.com/@ramonprata?source=rss-a303fddd144a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-pEe1AeIkZt4RQOdh8r9vA.jpeg</url>
            <title>Stories by Ramon Prata on Medium</title>
            <link>https://medium.com/@ramonprata?source=rss-a303fddd144a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:28:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramonprata/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[How to structure a React App in 2025 (SPA, SSR or Native)]]></title>
            <link>https://ramonprata.medium.com/how-to-structure-a-react-app-in-2025-spa-ssr-or-native-10d8de7a245a?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/10d8de7a245a</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-vite]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 12:07:17 GMT</pubDate>
            <atom:updated>2025-09-03T18:21:32.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cD6wIFgqQ9k4LXHu-b7yiA.png" /></figure><p>Five years ago, I wrote an article about how to structure a React application: <a href="https://ramonprata.medium.com/react-controle-de-estado-vamos-organizar-a065e0f5e82c">(PT-BR <em>React + Controle de estado. Vamos organizar?</em>)</a>. At that time, React was primarily used for building SPAs and React Native (RN) apps, with strong recommendations on libraries such as Redux. Since then, React and its ecosystem have evolved significantly, so it’s time to share the updated structure I’ve been working on — one that better fits modern React applications, <strong>including SPAs, SSR and Native.</strong></p><p>Over the past four years, this structure has been adopted in multiple real world React projects, not only by myself but also by several development teams. The feedback from those teams has consistently been very positive, which makes me confident sharing more about this approach</p><p>Before we get started, I’d like to make it clear what to expect — and what not to expect — from this post. It is meant as suggestions, not as a set of rules you must follow. I won’t be recommending which approach to use (SSR, SPA, etc.), nor which libraries or technologies to adopt, since those choices depend heavily on the specific needs of your application. Instead, I’ll provide an agnostic folder structure for React applications that you, as a developer, can take inspiration from and adapt as needed. <br>With that said, let’s dive in.</p><p>Let’s say we want to build an e-commerce application. As modern React frameworks suggest, we could structure the application’s folders based on pages or routes…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*3nlI5qIfQ9gk04NM0vEiGw.png" /></figure><p>There’s nothing inherently wrong with this approach, but I’d argue that as an application grows and new features are added, a page-based folder structure can become increasingly complex and harder to maintain. This isn’t just because of the growing number of files or the amount of code within certain folders (pages), but also because a single page can sometimes end up putting together implementation details from parts of the application that aren’t closely related</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*xg5sHYMIJD-Kxwa-VLp00A.png" /></figure><p>Take the <strong>Home </strong>page as an example: Products, Offers, Banners, and Brands are not closely related. To list Products, we may need API calls, components, hooks, logic, and more. The same applies to Banners, Brands, and so on. Instead of lumping everything together into a single <strong>Home </strong>folder, we should start thinking about the application in a more modular way — as a composition of cohesive parts that are closely related. You can call them resources, modules, or features (whatever works best for you). Personally, I prefer <strong>features</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*14Cn42uHu_4YfNWeXfFTsA.png" /></figure><p>Now we have a clear separation of the application’s functionalities — or, as we’ll call them, <strong>features</strong>. As you can see, the <strong>Home </strong>box is still there. Yes, a page is considered a feature folder in our structure; you can think of it as <strong><em>‘a page is a feature, but not every feature is a page.’</em> </strong>Now, the <strong>Home </strong>folder is simply a feature composed of other features, without needing to know their implementation details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*9O5w7EK8vJgOFJL4cnOjIg.png" /></figure><p>The feature-based folder structure offers several advantages, especially in growing applications. By grouping components, logic, hooks, and other related elements within specific feature folders, it establishes a clear separation of concerns, making the codebase easier to maintain, scale, and collaborate on. This approach promotes higher code cohesion, as related items are kept together, preventing fragmentation across multiple folders. Additionally, it simplifies the process of adding or modifying a feature without having to touch various parts of the application. Given the evolution of the React ecosystem (SPAs, SSR, React Native), this structure also provides a solid and adaptable foundation for different types of projects.</p><p>Now, let’s see the big picture..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*HETsutr0AVNdQUuamraYmg.png" /></figure><p>As you can see, inside <strong>src folder</strong>, we have 3 main folders</p><ul><li><strong>src/features</strong></li><li><strong>src/shared</strong></li><li><strong>src/app</strong></li></ul><p>First, let’s zoom in a feature folder to see what we can have here.</p><p><strong>Example: Products feature</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*aTGNq_Isa23m7FGk1re0Kw.png" /></figure><p>Now, let’s go through each sub-folder inside the <strong>Products feature</strong></p><h4><strong>feature/views</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*ApjpVacgJh9Fz-EUuupZYQ.png" /></figure><p><strong>The views folder is part of the View Layer</strong>.<strong> </strong>A folder that holds all the feature components and its styles. Every feature <strong>Component </strong>goes here. <strong>Example: ProductList.tsx</strong></p><ul><li><strong>feature/views/styles: (optional) </strong>a folder that holds all the components <strong>styles</strong>. Each component can have its corresponding <strong>styles -file (e.g. ProductList.styled.tsx)</strong>. It could be using <strong>CSSModule</strong>, <strong>CSSInJs </strong>or even <strong>TailwindCSS (</strong>if you want to avoid a lot of css classes polluting the components)</li></ul><h4><strong>feature/hooks</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*lTMnWjJY-V0q_zJqULY-vQ.png" /></figure><p>Since <strong>hooks </strong>are used within components, they’re also part of the <strong>View Layer</strong>. <strong>The hooks </strong>folder contains all hooks that are intrinsic to the feature itself. For example, if you need to manage the state of a “fetch products” API call (using React Query, for instance), a hook like useProductsData would belong here.</p><h4><strong>feature/services</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*ArPl3BookQhC4QaFYbpE0Q.png" /></figure><p><strong>The services folder is part of the Data Layer </strong>and it contains two files:</p><ul><li><strong>feature/services/ProductsManager: </strong>Responsible for mediating between the <strong>View Layer</strong> and the <strong>data source</strong>. The <strong>View Layer</strong> (components or hooks ) don’t need to know how data is fetched or sent.<strong> The Manager handles business rules, input/output data transformations, and error handling.</strong></li><li><strong>feature/services/ProductsRepository: </strong>Responsible for interacting with the data source. This file marks the <strong>boundary </strong>of our application. It could be used for API calls, access a local data base, etc.<strong> No error handling, no business rules</strong></li></ul><h4><strong>feature/store</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*2wU6kPdmspUGwWNyiNtqng.png" /></figure><p><strong>The feture store folder composes the Application State Layer. </strong>Almost every React application will eventually need to share states across components. In cases like this, we usually use some <strong>Global State Management lib (e.g. Zustand, Redux Toolkit, etc) or at least React Context API.</strong> I named this folder <strong>store </strong>because for this example, I am using <a href="https://zustand.docs.pmnd.rs/guides/slices-pattern">Zustand Slice Store Pattern</a>. But feel free to rename it as <strong>redux</strong>, <strong>context </strong>or whatever fits better in your case</p><h4><strong>feature/utils</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*VtNmIelfEy0fB8lZYhnUIA.png" /></figure><p><strong>The utils </strong>folder holds utility functions related to the feature scope. They should be used to offload low-level implementation details from components, managers, hooks, and other parts — keeping those files more declarative and less verbose. By encapsulating imperative logic into utilities, the other files can operate at a higher level of abstraction, focusing on <em>what</em> should happen rather than <em>how</em> it happens.</p><p><strong>Example:</strong> dataMappers.ts can be used by the <strong>Manager file </strong>to transform response data into a format suitable for rendering by the feature components.</p><h4><strong>feature/types</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*AJil7WZxaQwr8PNFY3v6yw.png" /></figure><p><strong>The types </strong>folder holds the feature types, interfaces, enums. <br><strong>Note</strong>: for component props (types/interfaces) I recommend keeping them in the component file itself</p><h3>How feature layers interact with each other</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*R0LprFu2u_jpTp66Z5YPTg.png" /></figure><h4><strong>View layer &lt;=&gt; Application State Layer</strong></h4><ul><li>consumes states from <strong>Application State Layer</strong></li><li>trigger actions that change states in the<strong> Application State Layer</strong></li></ul><h4>⁠<strong>View layer &lt;=&gt; Data Layer</strong></h4><ul><li>fetch data from <strong>Data layer </strong>(<strong>Manager </strong>=&gt; <strong>Repository</strong>)</li><li>send data to the <strong>Data layer</strong> (<strong>Manager </strong>=&gt; <strong>Repository</strong>)</li></ul><h4>Now, let’s take a look at the <strong>shared</strong> folder.</h4><p>The <strong>shared folder</strong> is meant to hold everything that is <strong>feature-agnostic</strong> — think of it as a library folder (generic components, generic hooks, etc.). <strong>Important</strong>: features can use what comes from the shared folder, but not the other way around. Since this is fairly self-explanatory, I won’t go into details; instead, I’ll just show you what a shared folder could look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*-a5gc5b1R-mne7f5KKQVbA.png" /></figure><h4>Feature &amp; Shared — usage flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*m82n-xl3Pt0zvzFlsVhyvg.png" /></figure><h4>Finally, the app folder</h4><p>Every React application has an entry file, typically App.tsx or main.tsx. In some frameworks, such as Next.js, the <strong>app</strong> folder is especially important because the framework relies on files with reserved naming conventions to bootstrap the application. Here, you can define the root layout, configure routing, initialize providers and put anything that needs to run at the very start of the app. You can also organize its sub-folders (as needed) adopting the same conventions we&#39;ve established for <strong>feature </strong>(e.g., views, hooks, etc.). Since the specifics may vary slightly from one framework to another, <strong>I highly recommend checking out the 3 demo repositories I created (linked below).</strong></p><p><strong>Exemple app folder</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*bxolVyi-zscwBQtE1xB9_Q.png" /></figure><p>That’s it! This is how I’d structure <strong>React applications (SPA, SSR, and Native)</strong>. If you want to dive deeper, check out my <a href="https://github.com/ramonprata">github</a>. I created 3 demos that show how to use this structure in practice:</p><ul><li><strong>React SSR with NextJs:</strong> <a href="https://github.com/ramonprata/react-next-js-boilerplate">ramonprata/react-next-js-boilerplate</a></li><li><strong>React SPA with Vite:</strong> <a href="https://github.com/ramonprata/react-vite-boilerplate">ramonprata/react-vite-boilerplate</a></li><li><strong>React Native with Expo:</strong> <a href="https://github.com/ramonprata/react-native-expo-boilerplate">ramonprata/react-native-expo-boilerplate</a></li></ul><p>Thank you for reading this far. <br>I hope these ideas help you in your next React Project.</p><p>See you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10d8de7a245a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intermittent Unit Tests: Understanding and Solving the Problem]]></title>
            <link>https://ramonprata.medium.com/intermittent-unit-tests-understanding-and-solving-the-problem-46d057d82289?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/46d057d82289</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 13:17:43 GMT</pubDate>
            <atom:updated>2025-03-17T13:17:43.569Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, while troubleshooting a unit testing issue in React, I noticed a curious and potentially problematic behavior that can also occur in other projects: unit tests intermittently passing and failing due to timeout errors.</p><h3>The Problem: Asynchronous Tests and Timeouts</h3><p>Tests, especially those involving component rendering and asynchronous executions, have a time limit to complete. In Jest, this default timeout is 5 seconds. If a test doesn’t finish within this time, it fails due to a timeout error.</p><p>In React components, we know that changes in props and local states can trigger re-renders. To handle this, the Testing Library documentation suggests using waitFor, which allows the test to &quot;wait&quot; until a certain condition is met or the timeout limit is reached.</p><p>The issue arises because Jest runs tests concurrently, causing multiple tests to share and compete for the same “DOM”. This can result in situations where, depending on the execution order, the DOM state is not as expected for a given test.</p><h3>Example: Modal with a Close Button</h3><p>I encountered this issue while testing a modal that received a prop to determine whether it was open or closed. The modal contained a close button, and the test checked if clicking the button triggered the correct function. The unexpected behavior was:</p><p>✅ Sometimes, the test passed, indicating that the button was rendered and the click event worked correctly.<br> ❌ Other times, the test failed because the button was not present in the DOM.</p><p>I noticed the same strange behavior when running the button click test in isolation (the test always passed), but when running all the tests together, sometimes it passed, sometimes it didn’t. So, I realized that the tests were in fact interfering with each other</p><p>Upon investigation, I realized that previous tests were verifying other modal’s behaviors, like when it was closed and nothing inside the modal was rendering (including the close button). Since the Testing Library does not automatically clear the DOM between tests and Jest was executing tests concurrently, conflicting render states could occur.</p><p>By reordering the tests — placing the close button test before the modal-closed test — the issue disappeared. However, this violates one of the fundamental principles of unit testing: <strong>independence</strong>. To ensure <strong>idempotency</strong>, each test must be isolated and produce the same result regardless of execution order.</p><h3>Possible Solutions</h3><p>After researching the issue further, I discovered three key points:</p><ul><li><strong>The Testing Library does not automatically clean up the DOM</strong> between tests.</li><li><strong>Jest runs tests concurrently</strong>, which can lead to unexpected conflicts due to DOM sharing between different tests.</li><li>Some approaches can help prevent this issue:</li></ul><p>✅ <strong>Force DOM cleanup using </strong><strong>cleanup() after each test</strong>, ensuring no persistent DOM states between tests.<br> ✅ <strong>Run tests sequentially using </strong><strong>--runInBand in Jest</strong>, ensuring each test runs in isolation.</p><p>While the first option seems preferable because it preserves “parallelization”, the second approach proved more effective. Since asynchronous tests relying on waitFor can take up to 5 seconds, concurrent execution (sharing tbe DOM) can make tests slower and more unstable. By forcing sequential execution, the intermittent failures disappeared, and surprisingly, the overall test runtime was shorter.</p><h3>Conclusion</h3><p>Unit tests should be reliable and predictable. Concurrent execution combined with persistent DOM states between tests can introduce flakiness, compromising test independence. Two possible solutions to avoid this issue are:</p><p>✔ <strong>Force DOM cleanup with </strong><strong>cleanup() after each test.</strong><br> ✔ <strong>Run tests sequentially using </strong><strong>--runInBand in Jest.</strong></p><p>In my case, sequential execution resolved the intermittent failures and even reduced the total test runtime. When dealing with such issues, it’s crucial to understand how the testing framework manages states and concurrency to avoid unnecessary headaches.</p><p>Well, I hope this short post can help you dealing with issues similar to these. <br>Thank you for readind this far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46d057d82289" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactSmallTips: neat components]]></title>
            <link>https://ramonprata.medium.com/reactsmalltips-neat-components-a0b8492e1fab?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0b8492e1fab</guid>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 13:11:50 GMT</pubDate>
            <atom:updated>2024-04-24T13:13:26.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*jIIxvZ_A9YfIVB3E7GK5lQ.png" /></figure><p>I have been working with React for 6 years now and I have to say, at the beginning, my components were really scary to look at. Not to mention how hard it was to maintain the code, fix bugs and add new features. After some time feeling bothered by this, I started to think about how to improve it, how I could turn my “monster” components into clean, small, concise, and flexible components. <br>As I was improving my coding skills, I noticed that most of the time we, developers, weren’t applying good coding practices in the components as we usually do in some backend code, for instance. I’ve learned some principles and good practices from books, online courses and also from my colleagues, but my components weren’t reflecting any of this knowledge. But, as the application starts to grow and acquire more features, more components, more complexity, not caring about the components code can lead to real pain in the near future.<br><br>That said, I’m going to show an example of some things I try to avoid and some practices I use to keep my components as neat as possible.</p><p>The following component is a <strong>HomePage </strong>that fetches a list of users from an API and renders it. The HomePage component also includes a select field, which can be used to sort the list of users by name or age and also to set the <strong>document.title</strong> (the page title) according to the selected value (e.g.: “Users by age | name”).</p><p>Along with the code, I added some comments to highlight some changes we can make to improve the component.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import { Iuser } from &#39;./types/IUser&#39;;<br><br>const HomePage = () =&gt; {<br>  const [sortBy, setSortBy] = useState(&#39;name&#39;);<br>  const [users, setUsers] = useState&lt;Iuser[] | null&gt;(null);<br>  const [error, setError] = useState(false);<br><br>  // extract complex hooks logic to a custom hook<br>  useEffect(() =&gt; {<br>    const fetchUsers = async () =&gt; {<br>      try {<br>        // extract input/output of data (e.g: API calls) to a separate file<br>        const response = await fetch(&#39;https://api.example.com/users&#39;);<br>        if (!response.ok) {<br>          throw new Error(&#39;Failed to fetch users&#39;);<br>        }<br>        const data = await response.json();<br>        setUsers(data);<br>      } catch (error) {<br>        console.error(&#39;Error fetching users:&#39;, error);<br>      }<br>    };<br>    fetchUsers();<br>  }, []);<br><br>  const handleSortChange = (event: {<br>    target: { value: React.SetStateAction&lt;string&gt; };<br>  }) =&gt; {<br>    setSortBy(event.target.value);<br>    // extract browser API interaction<br>    document.title = `Users by ${event.target.value}`;<br>  };<br><br>  // extract data processing for rendering.<br>  const sortedUsers =<br>    users &amp;&amp;<br>    [...users].sort((a, b) =&gt; {<br>      if (sortBy === &#39;name&#39;) {<br>        return a.name.localeCompare(b.name);<br>      } else if (sortBy === &#39;age&#39;) {<br>        return a.age - b.age;<br>      }<br>      return 0;<br>    });<br><br>  // split the component into smaller and concise parts<br>  // avoid in-jsx conditional rendering<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;User List&lt;/h2&gt;<br>      &lt;label htmlFor=&quot;sort&quot;&gt;Sort by:&lt;/label&gt;<br>      &lt;select id=&quot;sort&quot; value={sortBy} onChange={handleSortChange}&gt;<br>        &lt;option value=&quot;name&quot;&gt;Name&lt;/option&gt;<br>        &lt;option value=&quot;age&quot;&gt;Age&lt;/option&gt;<br>      &lt;/select&gt;<br><br>      {!error &amp;&amp; users &amp;&amp; (<br>        &lt;ul&gt;<br>          {sortedUsers?.map((user) =&gt; (<br>            &lt;li key={user.id}&gt;<br>              &lt;img src={user.avatar} alt={`Avatar of ${user.name}`} /&gt;<br>              &lt;div&gt;<br>                &lt;h3&gt;{user.name}&lt;/h3&gt;<br>                &lt;p&gt;{user.age} years old&lt;/p&gt;<br>              &lt;/div&gt;<br>            &lt;/li&gt;<br>          ))}<br>        &lt;/ul&gt;<br>      )}<br>     <br>      {error &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;p&gt;Something went wrong&lt;/p&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default HomePage;</pre><p>In this post I’m not going to delve into the use of third-party libraries to simplify things like API calls. Of course there are many libraries that we could use it, and if it makes sense in the context of your application, use them. The example here was done purely with React (with no libs) for the purpose of understanding how a component can go from something cumbersome and sometimes complex to something simpler, organized, and clean. But I would like to emphasize that sometimes the use of third-party libraries can bring even more complexity to your code, so be careful when adopting a library. If you choose to use a library, a good idea is to encapsulate it in a layer so that your components do not interact directly with it. Encapsulation can bring a lot of advantages such as abstraction, ease of replacement, testability, code organization and risk reduction.</p><p>Now let’s try to apply some of the tips left in the comments above.</p><h4>Extract complex hooks logic to a custom hook</h4><p>When React hooks were first introduced their main purpose was to reuse logic across components. Nowadays many React libraries provide their own hooks that we can simply import and use. If we take a look at those libraries’ hooks, we may notice that some of them contain a considerable amount of code, sometimes a bit complex. However, when we use them in components, it is quite straightforward: you just call the hook and receive its return value (if there is one). So, I would argue that to simplify components code, we can create our own custom hooks to handle the logic. Then, we can simply use them in the components, similar to how we use third-party hooks. Even if the logic isn’t reusable, extracting it from the component can simplify unit tests (you can test the logic and the component separately) and make your component less imperative. Plus, who knows, maybe later in another component you’ll notice the same pattern, so you can turn the created custom hook into a more generic one that’s reusable across components.</p><p>Taking the <strong>HomePage </strong>component as an example, let’s first create a UserService file that will be responsable for API calling and error handling</p><pre>import { IUser, API_PATHS } from &#39;../../shared&#39;;<br>import { USER_API_EXCEPTIONS } from &#39;./homeUtils&#39;;<br><br>class UserService{<br>  async getUsers() {<br>    try {<br>      const response = await fetch(API_PATHS.GET_USERS);<br>      if (response.ok) {<br>        const users = (await response.json()) as IUser[];<br>        if (!users.length) {<br>          USER_API_EXCEPTIONS.throwEmptyException();<br>        }<br>        return users;<br>      }<br>      USER_API_EXCEPTIONS.throwFailedException();<br>    } catch (error) {<br>      USER_API_EXCEPTIONS.throwFailedException();<br>    }<br>  }<br>}<br><br>export default new UserService();</pre><p>Now let’s create a custom hook that will be responsible for firing that API call and returning its result to the component as needed.</p><pre>import { useEffect, useState } from &#39;react&#39;;<br>import UserService from &#39;../UserService&#39;;<br>import { IUser } from &#39;../../../shared&#39;;<br><br>export const useLoadUsers = () =&gt; {<br>  const [users, setUsers] = useState&lt;IUser[] | null&gt;(null);<br>  const [error, setError] = useState(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    const fetchUsers = async () =&gt; {<br>      try {<br>        const users = await UserService.getUsers();<br>        if (users) {<br>          setUsers(users);<br>        }<br>      } catch (error) {<br>        setError((error as Error).message);<br>      }<br>    };<br>    fetchUsers();<br>  }, []);<br><br>  return {<br>    users,<br>    error,<br>  };<br>};</pre><p>The above hook extracts the data-fetching logic from the component. Now, the component doesn’t need to know how it’s done, it just needs to use it. The implementation above could be easily replaced to use a third-party library like <strong>React Query</strong> to achieve the same result, and your component wouldn’t know, since it will only interact with the custom hook <strong>useLoadUsers</strong>. The power of encapsulation!</p><p>Now let’s refactor our component to see where we got so far..</p><pre>import React, { useState } from &#39;react&#39;;<br>import { useLoadUsers } from &#39;../hooks/useLoadUsers&#39;;<br><br>const HomePage = () =&gt; {<br>  const [sortBy, setSortBy] = useState(&#39;name&#39;);<br><br>  // NO FETCH IMPLEMENTARION HERE<br>  // JUST CALL THE CUSTOM HOOK<br>  const { users, error } = useLoadUsers();<br><br> // CODE..<br>};<br><br>export default HomePage;</pre><h4>Extract data processing into a utility function outside of the component.</h4><p>The list of users can be ordered by name or age, so in that case, we can move the sorting list logic from the component to a pure JS function. Let’s create that function outside of the component</p><pre>import { IUser, TSortBy } from &#39;../../shared&#39;;<br><br>export const sortUsers = (users: IUser[] | null, sortBy: TSortBy) =&gt; {<br>  if (users?.length) {<br>    return users.sort((a, b) =&gt; {<br>      if (sortBy === &#39;name&#39;) {<br>        return a.name.localeCompare(b.name);<br>      } else if (sortBy === &#39;age&#39;) {<br>        return a.age - b.age;<br>      }<br>      return 0;<br>    });<br>  }<br>  return [];<br>};</pre><p>Now let’s use the function in the component</p><pre>import React, { useState } from &#39;react&#39;;<br>import { useLoadUsers } from &#39;../hooks/useLoadUsers&#39;;<br>import { sortUsers } from &#39;../homeUtils&#39;;<br>import { TSortBy } from &#39;../../../types/TSortBy&#39;;<br><br>const HomePage = () =&gt; {<br>  const [sortBy, setSortBy] = useState&lt;TSortBy&gt;(&#39;name&#39;);<br>  // ...CODE<br><br>  // NO DATA PROCESSING IMPLEMENTATION HERE<br>  // JUST CALL THE FUNCTION AND GET ITS RETURN<br>  const sortedUsers = sortUsers(users, sortBy);<br><br> // ...CODE<br>};<br><br>export default HomePage;</pre><h4>Extract browser API interactions from the component</h4><p>Sometimes, components need to interact with browser APIs and its resources (such as the global window, local storage, cookies, etc.). In cases like these, it’s a good idea to also extract that code from the component, at least to make it easier to unit testing the components. So let’s do that</p><pre>export const changePageTitle = (title: string) =&gt; {<br>  document.title = `Users by ${title}`;<br>};</pre><p>Now let’s use that function in the component</p><pre>import React, { useState } from &#39;react&#39;;<br>import { useLoadUsers } from &#39;../hooks/useLoadUsers&#39;;<br>import { sortUsers } from &#39;../homeUtils&#39;;<br>import { TSortBy } from &#39;../../../types/TSortBy&#39;;<br>import { changePageTitle } from &#39;../../../utils&#39;;<br><br>const HomePage = () =&gt; {<br>  const [sortBy, setSortBy] = useState&lt;TSortBy&gt;(&#39;name&#39;);<br><br>  const { users, error } = useLoadUsers();<br><br>  const handleSortChange = (event: {<br>    target: { value: React.SetStateAction&lt;string&gt; };<br>  }) =&gt; {<br>    setSortBy(event.target.value as TSortBy);<br>    // NO DIRECT INTERACTION WITH BROWSER API HERE<br>    // JUST CALL THE FUNCTION<br>    changePageTitle(`Users by ${sortBy}`);<br>  };<br><br>  const sortedUsers = sortUsers(users, sortBy);<br><br>  // ...CODE<br>};<br><br>export default HomePage;</pre><h4>Split the main component into smaller and more concise components</h4><p>As we saw, the <strong>HomePage </strong>component implemented everything it needs to render. Wouldn’t it be nice if we split it into pieces and then just put these pieces all together like a puzzle? So, let’s create the following components: <strong>HomeHeader</strong>, <strong>UserList </strong>and <strong>ErrorMessage</strong></p><pre>import { TSortBy } from &#39;../../../shared&#39;;<br><br>type HomeHeaderProps = {<br>  handleSortChange: (event: React.ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; void;<br>  sortBy: TSortBy;<br>};<br>const HomeHeader = (props: HomeHeaderProps) =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;h2&gt;User List&lt;/h2&gt;<br>      &lt;label htmlFor=&quot;sort&quot;&gt;Sort by:&lt;/label&gt;<br>      &lt;select id=&quot;sort&quot; value={props.sortBy} onChange={props.handleSortChange}&gt;<br>        &lt;option value=&quot;name&quot;&gt;Name&lt;/option&gt;<br>        &lt;option value=&quot;age&quot;&gt;Age&lt;/option&gt;<br>      &lt;/select&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default HomeHeader;</pre><pre>import { IUser } from &#39;../../../shared&#39;;<br><br>const UserList = (props: { users: IUser[] }) =&gt; {<br>  if (!props.users?.length) {<br>    return null;<br>  }<br><br>  return (<br>    &lt;ul&gt;<br>      {props.users?.map((user) =&gt; (<br>        &lt;li key={user.id}&gt;<br>          &lt;img src={user.avatar} alt={`Avatar of ${user.name}`} /&gt;<br>          &lt;div&gt;<br>            &lt;h3&gt;{user.name}&lt;/h3&gt;<br>            &lt;p&gt;{user.age} years old&lt;/p&gt;<br>          &lt;/div&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};<br><br>export default UserList;</pre><pre>const ErrorMessage = (props: { errorMessage: string }) =&gt; {<br>  if (!props.errorMessage) {<br>    return null;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{props.errorMessage}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ErrorMessage;</pre><p>As we can see the components will take care of their own rendering internally. There is no need for conditional rendering in the main component (<strong>HomePage</strong>).</p><p>Now, let’s refactor the HomePage component to use these pieces and see the final result</p><pre>// ..imports<br><br>const HomePage = () =&gt; {<br>  const [sortBy, setSortBy] = useState&lt;TSortBy&gt;(&#39;name&#39;);<br>  const { users, error } = useLoadUsers();<br><br>  const handleSortChange = (event: React.ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; {<br>    setSortBy(event.target.value as TSortBy);<br>    changePageTitle(`Users by ${sortBy}`);<br>  };<br><br>  const sortedUsers = sortUsers(users, sortBy);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;HomeHeader handleSortChange={handleSortChange} sortBy={sortBy} /&gt;<br><br>      &lt;UserList users={sortedUsers} /&gt;<br><br>      &lt;ErrorMessage errorMessage={error} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default HomePage;</pre><p>As we can see, the HomePage component now has a higher-level, cleaner and less imperative code, without implementation details of things that are not relevant to it. It simply calls the functions and components it needs, allowing them to internally resolve their implementations, exposing to the main component only what is necessary. Also the children components are really simple and concise.</p><p>Some of the proposed changes may seem unnecessary, but believe me, in the long run, these practices can contribute a lot for the application’s scalability, maintenance, add new features and testing.</p><p>Last but not least, I would like to suggest an <strong>anatomy </strong>for the components. A way to organize things within the components to make sure all the components have the same “look”. This can improve the understanding and the development experience</p><pre>const HomePage = () =&gt; {<br>  // 1. HOOKS (FROM REACT, LIBS AND YOUR OWN CUSTOM HOOKS)<br>  const [sortBy, setSortBy] = useState&lt;TSortBy&gt;(&#39;name&#39;);<br>  const { users, error } = useLoadUsers();<br><br>  // 2. HANDLE FUNCTIONS <br>  // FOR EVENTS AND FUNCTIONS THAT WILL BE PASSED <br>  // AS PROPS TO CHILDREN COMPONENTS<br>  const handleSortChange = (event: React.ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; {<br>    setSortBy(event.target.value as TSortBy);<br>    changePageTitle(`Users by ${sortBy}`);<br>  };<br><br>  // 3. PROCESSING DATA<br>  // STATE, PROPS, ANYTHING THAT NEED A POLISHING BEFORE RENDER<br>  const sortedUsers = sortUsers(users, sortBy);<br><br>  // 4. RENDER<br>  return (<br>    &lt;div&gt;<br>      &lt;HomeHeader handleSortChange={handleSortChange} sortBy={sortBy} /&gt;<br><br>      &lt;UserList users={sortedUsers} /&gt;<br><br>      &lt;ErrorMessage errorMessage={error} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default HomePage;</pre><p>The above anatomy is just a suggestion, but I strongly recommend that you follow it or come up with your own way to organize things within the component. Just make sure your components always follow the same pattern</p><p>Well, that’s all. I hope this post can be useful when you are creating your components. If you want to see the finished code in details, check out the <a href="https://github.com/ramonprata/neat-react-components">repo</a>.<br>Thank you for reading this far.<br>Regards!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0b8492e1fab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactSmallTips: unit-testing-components]]></title>
            <link>https://ramonprata.medium.com/reactsmalltips-unit-testing-components-190dfda44ac3?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/190dfda44ac3</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 13:23:56 GMT</pubDate>
            <atom:updated>2023-10-25T13:47:52.196Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is PART II of another article that I wrote, recently, about good practices with unit tests. If you don’t know what I am talking about, I highly recommend that you take a look at the <strong>PART I: </strong><a href="https://medium.com/@ramonprata/js-smalltips-unit-tests-good-practices-2b89b03c39fc"><strong>JS SmallTips — unit tests: good practices</strong></a><strong>.</strong> While in the first post I discussed about unit tests in general<strong> (</strong>regardless of whether it is tests on react-components or not), having a good understanding of these concepts is crucial to fully understanding what we will see in this one.</p><h3>First things first</h3><p>As we know, unit-tests are tests performed on units. If we think about a react-component, they are just functions (it can be classes too, but not recommended). So it is perfectly acceptable that we deal with unit tests in components folowing the same principles and concepts we use to test a normal function or class. Therefore, applying those concepts while testing a component, will give us the same benefits we know.</p><h3>What to test</h3><p>When dealing with unit tests on components, some developers can feel a little intimidated and most of the time they may wonder:<strong> “There is so much going on in my component, what should I test?”</strong>. And thats true, sometimes your component can have multiple props, local states, global states, using <em>third-party-libs</em>, fetching data from an API, hooks, nested components, conditional rendering, etc. If that’s the case, you should first consider breaking down your component into smaller and simpler components. This will make your life a lot easier! After that, we can answer that question for each component we created: <strong>It depends.</strong></p><p>I know that answer isn’t helpful. So, I’ll give you my tips on this one. Whenever I am testing a component, I consider 3 things that tests must cover:</p><ul><li>conditional rendering</li><li>user events</li><li>(re-)rendering (based on state changes and/or props)</li></ul><p>With these 3 pillars, we can implement really effective unit tests on any component. To test components, besides <strong>Jest</strong>, we need more tools. Here I’m going to use <a href="https://testing-library.com/"><strong>testing-library</strong></a><strong> lib</strong>, which is just a utility lib that provide us the necessary tools to unit-testing components.</p><p>Consider this simple <strong>Counter</strong> component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*rIWFonpZgDDqEeGKn1iOEA.png" /></figure><p>It will increment and decrement the count value as the user click on the buttons</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*OEGdbC_mgbubDzk6q-Lm1w.png" /></figure><h4>Testing first rendering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*Nm7xvTYWApej2HvNafjyxg.png" /></figure><h4>Testing events and re-rendering</h4><p>Now, let’s test some user events (clicks) and re-rendering. For this, we will use <strong>userEvent </strong>and <strong>async methods </strong>provided by <em>testing-library</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*V9CKfhZ3Ns1_UWC6cDKTjQ.png" /></figure><p>Some notes here. Whenever you test something in a component that causes a re-rendering, we should assert using <strong>async/await</strong> since the async methods return a Promise. See the <em>testing-library</em> documentation on <a href="https://testing-library.com/docs/guide-disappearance/"><strong>Appearance and Disappearance</strong></a> and <a href="https://testing-library.com/docs/user-event/intro/#writing-tests-with-userevent"><strong>userEvent</strong></a><strong>.</strong></p><h4>Testing props</h4><p>Let’s make the <strong>Counter </strong>component receive a initial value as <strong>props</strong>, and test whether the props is being rendered as expected or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*sZhHLOlwAiMWa3VzemQ6tw.png" /></figure><p>props being rendered..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*FAsnqpO-zsCTJgFu-unUiw.png" /></figure><p>What if the <strong>Counter </strong>component receive a function as a prop? How do we test it? Well, the same way we have passed a value to <strong>initialValue </strong>prop, we can also pass a <strong>mocked function</strong> as a prop. During testing, at the component level, it doesn’t matter if the function is actually executing anything, we just need to make sure the function is being called as intended.</p><p>Let’s add another prop to the <strong>Counter </strong>component. This time a function prop that will be attached to a button</p><p>Adding a function as a prop</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*3POEzOGA4rrShQ4_1-mIuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*5CuO27HFhJvc1h3GSWPOFw.png" /></figure><p>prop (function) being called..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*tCNfGx9q98YRbEBlgoR2Ww.png" /></figure><h4>Testing condtional rendering</h4><p>To exemplify how to test a conditional rendering, let’s make the component tree a bit more interesting.</p><p>First, let’s create a <strong>Page </strong>component that will get an initial count value from an async method and pass it to the <strong>Counter</strong> component as props</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*hTvD1qj3hNeLUck5qgx2fQ.png" /></figure><p>Although this is still a simple component, it covers several real-world scenarios when you have components that use hooks, async methods, conditional rendering, dependencies, etc. By the way, when dealing with a complex component, the first thing we must identify are its dependencies.</p><p>Here we have 2 dependencies. The service we are using to get the initial data (<strong>myService.getInitialValue</strong>) and the <strong>Counter </strong>component.</p><p>Maybe you are asking yourself: <strong>“What? Why is the <em>Counter component </em>a dependency in the <em>Page component</em>?” </strong>Well, we saw that a component is nothing more than a function, and a function is an unit, therefore a component inside a component is just a dependency, just like the <strong>myService.getInitialValue </strong>function. When the <strong>Page </strong>renders the <strong>Counter </strong>component, it is just calling a function. We know that, while testing, is a good practice to mock dependencies instead of calling the actual implementation.</p><p>This makes the unit tests simpler, easier to maintain and faster to run. Furthermore, we have already tested the <strong>Counter</strong> component separately, so there is no need to render <strong>Counter’s</strong> actual implementation during <strong>Page’s</strong> tests. So let’s mock the <strong>Page’s </strong>depenencies and test it..</p><p>mocking the <strong>Counter </strong>component..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*TjFejadKzEjEel75o9JaQA.png" /></figure><p>testing the <strong>Page </strong>component..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*j_Nhx1f4xzQMo5scXACgfg.png" /></figure><p>The main reason why the test was so easy to implement, is that we mocked its dependencies, including nested components (<strong>Counter</strong>). There is nothing wrong with that. In fact, this is desirable. If you don’t want to mock nested components, you’ll still be able to unit-test your application, but your tests will become more complex and slow to run.</p><p>That’s why I recommend: in cases where you have a <strong>component</strong> that renders other <strong>nested-components</strong>. Start testing the <strong>nested </strong>ones separately and then, test the outer component that is wrapping those.</p><p>So, that’s it. These were my final basic tips (I think) to assist you in writing better unit tests regarding testing components in React. I hope you found them helpful. Thank you for reading this far.</p><p>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=190dfda44ac3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS SmallTips — unit tests: good practices]]></title>
            <link>https://ramonprata.medium.com/js-smalltips-unit-tests-good-practices-2b89b03c39fc?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b89b03c39fc</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 13:08:05 GMT</pubDate>
            <atom:updated>2023-10-18T13:08:05.404Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS SmallTips — unit tests: good practices</h3><p>As a software developer, you probably know what unit tests are and why they are beneficial. However, sometimes, you might (just like me) struggle to fully grasp how to create effective and simple unit tests. Perhaps you find yourself reproducing someone else’s test code without a clear understanding of its purpose. So, instead of jumping right into the code, let’s take a step back and explore some tips that I hope will help us writing better unit tests.</p><h3>First things first</h3><p>When we say <strong>unit tests,</strong> we are referring to testing a unit-level piece of code (but still testable). A unit can be a function, a method, a class or even a React component. Since this type of testing focuses on the smallest parts of the application and serves as a base for other types of tests, unit tests are placed at the bottom of the testing pyramid (unit-tests; integration-tests; e2e-tests).</p><h3>Why</h3><p>While it’s quite obvious that testing your code helps ensure that the units work as intended and prevents bugs, there are additional advantages to unit testing. We will explore some of these benefits as we apply the following tips to our testing process</p><h4>I. Be clear when structuring your tests</h4><p>The suite of tests and each test case should be organized in a way that clearly defines what you are testing and what the expected results are. Testing frameworks like <strong>Jest </strong>provide us a way to structure tests into blocks, describe test suites, and specify test cases. When used effectively, this approach can enhance our understanding of both the tests and the code itself</p><figure><img alt="describing suit tests" src="https://cdn-images-1.medium.com/max/599/1*Rh7fPML96tl2JKd_dzvpvw.png" /></figure><p>As we can see, there’s no need to dig into the code ( the <strong>moduleA.isEvenNumber</strong> function) to understand what it does. The main advantage here is that unit tests can also work as code documentation, helping other developers better grasp the code implementation and even the business rules.</p><h4>II. Mocking dependencies</h4><p>What makes unit tests different from other types of tests (integration, e2e) is that it should only run against the unit you are testing, that means we must (while testing) isolate the code we are testing from its dependencies. <strong>For instance:</strong> Let’s say we want to test the <strong>moduleA.functionA </strong>and at some point in the<strong> </strong>code, this function calls another module’s function (<strong>moduleB.functionB). </strong>During testing, <strong>module.functionA</strong> should not rely on the actual implementation of its dependencies. That’s where <strong>mocks</strong> come in handy. Let’s see an example</p><figure><img alt="moduleA" src="https://cdn-images-1.medium.com/max/414/1*sTuvqQtZASWYslQ-GP2PoQ.png" /></figure><p>Mock <strong>moduleA’s </strong>dependencies and force <strong>moduleB </strong>to respond as necessary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*mJtKOhESlrKPt7inTiwvKA.png" /></figure><p>The benefits of mocking include the ability to control <strong>moduleB’s </strong>responses for each test case and to assert <strong>moduleA’s </strong>results to ensure it meets our expectations. Additionally, we isolated <strong>moduleA</strong>, so any changes in <strong>moduleB </strong>will not affect <strong>moduleA’s </strong>tests. Isolating the unit we are testing is quite important because if we don’t do this, we will end up with an <strong>integration-like-test</strong>. In the example above, <strong>moduleA </strong>depends on <strong>moduleB </strong>and <strong>moduleB </strong>can also have its own dependencies, so if we don’t mock it, we will have a dependency chaining effect, which can lead to really complex and slow unit tests.</p><h4>II. Make it simple</h4><p>Not only should the structure of your test be clear, but the implementation should also be simple. In fact, the test implementation should be simpler than the code we are testing. I have a “rule of thumb” that I use when writing unit tests: “if my unit test is becoming too complex, it might be time for some code refactoring.”</p><p>I mentioned earlier that unit testing has some not-so-obvious benefits, one of them being that unit tests can actually improve your code. If you’ve read books like “Clean Code”, you probably already know some tips for making your code cleaner, easier to understand, and more maintainable. Well, unit testing can help with this and can also encourage us to adopt good development practices like <strong>Test-Driven Development (TDD).</strong> One approach I find useful to simplify my tests is to follow a basic test case structure. You see, a test case has a kind of “basic anatomy”.</p><p>1º. <strong>given</strong> — prepare the test-case scenario<br>2º.<strong> when — </strong>execute the unit<br>3º. <strong>then </strong>— check the expected behavior or outcome of the test</p><p>Let’s see the previous example with some comments to help us to get the idea.</p><figure><img alt="module A unit tests" src="https://cdn-images-1.medium.com/max/635/1*9KJmUqbHGVdXEJPGy1pkbA.png" /></figure><p>To close this section, here are some “red-flags”, you should consider, that indicates that your unit test is becoming too complex and/or your code need some refactoring.<br>- the unit you are testing is doing more than it should?<br>- can the unit be broken down into smaller parts, so you can test them separately?<br>- the 1º step (<strong>given</strong>) is getting too cumbersome? If so, this could mean that the unit you are testing rely on too many dependencies. Breaking down the unit into small pieces will help.</p><h4>III. Test the behavior not only the results</h4><p>When unit-testing, we tend to focus on the results. We wanna write a test where the unit’s results match our expectations. But, as we saw in the previous examples, sometimes the unit we are testing rely on other units, modules or a third-party code. We also saw that in cases like that a good practice to apply is to mock its dependencies. So, let’s say we are testing a <strong>moduleA.functionA </strong>and that function calls, conditionally, the <strong>moduleC.functionC</strong>, since the <strong>moduleA </strong>may or may not call<strong> moduleC</strong>, we might want to test the <strong>moduleA.functionA’s </strong>behavior and assert<strong> </strong>whether it is calling <strong>moduleC only when &amp; how </strong>it should. Let’s see an example</p><p>Given some conditions, the <strong>moduleA.getNumberDescription may or may not </strong>call <strong>moduleC.describeNumberType</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*wRoERPAb7a3nRGkRERWtqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*7wV5dwMJ3n6DsJf6oN5qfQ.png" /></figure><p>So let’s see how to test the <strong>moduleA.getNumberDescription </strong>function’s<strong> </strong>behavior</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*869OYh6SCfvhrLrpiWzKFg.png" /></figure><p>As we can see, asserting the behavior is as relevant as asserting the results. Sometimes more.</p><h4>IV. Force failures</h4><p>Sometimes our test code isn’t that simple, and its logic can be misleading. So here’s an extra tip: every time you run your tests and they pass..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*7U5U_GEuADoao-focZ7P-Q.png" /></figure><p><strong>..intentionally introduce some failures</strong> to ensure that your test doesn’t provide a <strong>false positive result </strong>and it’s passing and failing only when it should</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*z5Ds4AgZtNh-JC5gC2UPLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*pev5Eb5rHzWT1SnwcmtAzw.png" /></figure><p>So, that’s it. These were some of my basic tips to assist you in writing better unit tests. I hope you found them helpful, and stay tuned for a potential PART II with some more tips. Thank you for reading this far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b89b03c39fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactSmallTips: Liskov Substitution in React components]]></title>
            <link>https://ramonprata.medium.com/reactsmalltips-liskov-substitution-in-react-components-b823163bca75?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b823163bca75</guid>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 14:39:04 GMT</pubDate>
            <atom:updated>2022-12-21T15:57:17.841Z</atom:updated>
            <content:encoded><![CDATA[<p>At some point in your career as a software developer you might start worrying about not just writing code that works, but code that is readable, easy to understand, easy to maintain and scalable. In other words, a good quality code.</p><p>In order to achieve that, there are some guidelines like: <em>patterns</em>, <em>paradigms and principles</em>. Those guidelines were designed by real developers to solve well known real problems in programming. Among them, we have <strong>SOLID Principles</strong>.</p><blockquote><strong><em>SOLID </em></strong><em>is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin (aka </em><a href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin"><em>Uncle Bob</em></a><em>).</em></blockquote><p>I’ve already written 2 articles covering the<strong> </strong><a href="https://ramonprata.medium.com/reactsmalltips-open-closed-react-components-248226863276"><strong>Open-closed Principle</strong></a><strong> </strong>and the<strong> </strong><a href="https://medium.com/@ramonprata/reactsmalltips-interface-segregation-in-react-components-b1a63d5a0e9f"><strong>Interface Segregation Principle</strong></a><strong> in React</strong>. In this one we’re going to see the <strong>Liskov Substitution Principle </strong>applied in React Components.</p><p>So, what <strong>Liskov Substitution Principle (LSP from now on) </strong>is all about? The oficial definition goes like..</p><blockquote>If for each object <strong>o1 </strong>of type S there is an object <strong>o2 </strong>of type T such that for all prgrams <strong>P </strong>defined in terms of <strong>T</strong>, the behavior of <strong>P </strong>is unchanged when <strong>o1 </strong>is substituted for <strong>o2 </strong>then <strong>S </strong>is a subtype of <strong>T </strong><br><em>Clean Architecture — Robert C. Martin</em></blockquote><p>I don’t know about you, but, for me that definition wasn’t easy to get at first glance. So, after reading some other paraphrased definitions, I got the idea. Bring that concept to the <strong>React </strong>world, we could say that: <br>A <strong>subComponent </strong>based on a <strong>baseComponent </strong>could substitute the <strong>baseComponent </strong>without changing the application’s behavior.</p><p>I know it is still not very clear, so let’s jump into an example that I hope will make the concept of <strong>LSP </strong>cristal clear for you.</p><p>Let’s say in your application a lot of componentes are styled using <strong>flex box</strong> and <strong>its properties</strong>. In order to avoid repetition— <em>defing display: flex, flex-direction, justify-content, etc..</em>— and to make it easier to use flex box styles in our components, let’s create a component called, unsurprisingly, <strong>FlexBox</strong>.</p><p>To create such styled component, I’m going to use a <em>lib </em>called <a href="https://emotion.sh/docs/@emotion/react"><strong>@emotion/react</strong></a><strong> </strong>to helps us styling components with CSS in JS</p><p>So, first we create our <strong>FlexStyled</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*LMBqcSIac1RGl74dk4mtxw.png" /></figure><p><em>Note: a </em><strong><em>flex box </em></strong><em>can have more than those properties. But, to keep the example as simple as possible, I’m going to use just some of them</em></p><p>Now we can use that <strong>FlexStyled </strong>to create our <strong>FlexBox </strong>component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*dNmV3y5FFb7i7M9eupySuA.png" /></figure><p>And then, we can use our <strong>Flexbox</strong> in our application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*9Ff5uZdWyts5bLWBvrRWFw.png" /></figure><p>As a result, we got the default behavior of flex box <br><strong><em>flexDirection: ‘row’, justifyContent: ‘flex-start’ and alignItems: ‘stretch”<br></em></strong>The <strong>purple border shows the limits of the FlexBox</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*zvRKoX8ap7MjrWJzRZulcQ.png" /></figure><p>A common use of flex box is to <strong>perfectly center</strong> children both horizontally and vertically, and the following code snippet can be repeated a lot in your application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*XjMS0iVpvS1ie6snFJUrAA.png" /></figure><p>Result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*LGOLQHXTQy8tsxU2bVmFcA.png" /><figcaption>Result with Flexbox: pasing align and justify as ’center’</figcaption></figure><p>To avoid that annoying repetition everytime we want to center things with flex box, <strong>let’s create a sub-type of our FlexBox, the FlexCenter</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*U2ziCzryZwOQZq0SP5jHww.png" /></figure><p>As you can see, the <strong>sub-type</strong> component — <strong>FlexCenter — </strong>can be created just by <strong>extending props</strong> from <strong>FlexBox </strong>and returning the <strong>FlexBox </strong>component itself, <strong>passing </strong>the value “<strong>center</strong>” <strong>for both align and justify props</strong></p><p>Now we can go to our App, and <strong>substitute the FlexBox for FlexCenter</strong>. Wait a minute,<strong> can we substitute a baseComponent for a sub-type of that component and still get the same result (behavior)?</strong></p><p>If we can, i<strong>sn’t that the LSP after all? </strong>Let’s see..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*RYGdfw-cYggcm71l9DOBFQ.png" /></figure><p>And we still got the expected behavior</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*LGOLQHXTQy8tsxU2bVmFcA.png" /><figcaption>Result with FlexCenter: no need to pass align and justify props</figcaption></figure><p>To summarize, in order to make it easier to style components with flex box and avoid annoying repetition, we created a <strong>FlexBox </strong>component with handy props. Then we created a <strong>sub-type </strong>of that component, the <strong>FlexCenter</strong>. As we saw in the <strong>LSP </strong>concept, we should be able to <strong>substitute the a baseComponent </strong>for a <strong>subComponent of that one, </strong>and still get the expected behavior. <br>Since the relationship between <strong>sub-types</strong> and <strong>base-types</strong> is basically an extension, <strong>the Liskov Substitution Principle is very close to the Open Closed Principle</strong>. You should check that out!</p><p>So that was the <strong>LSP </strong>(<strong>Liskov Substitution Principle</strong>) in action with React components. Hope this post was helpful.</p><p>You can find the code on my <a href="https://github.com/ramonprata/liskov-substitution-principle-in-react"><strong>Github</strong></a><strong>.<br></strong>Thanks a lot for reading this far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b823163bca75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactSmallTips: Interface Segregation in React components]]></title>
            <link>https://ramonprata.medium.com/reactsmalltips-interface-segregation-in-react-components-b1a63d5a0e9f?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1a63d5a0e9f</guid>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 30 Nov 2022 12:30:04 GMT</pubDate>
            <atom:updated>2022-11-30T12:30:04.034Z</atom:updated>
            <content:encoded><![CDATA[<p>At some point in your career as a software developer you might start worrying about not just write a code that works, but a code that is readable, easy to understand, easy to maintain and scalable. In other words, a good quality code.</p><p>In order to achieve that, there are some guides like: <em>patterns</em>, <em>paradigms and principles</em>. Those guides were designed by real developers to solve well known real problems in programming. Among them, we have <strong>SOLID Principles</strong>.</p><blockquote><strong>SOLID<em> </em></strong>is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin (aka <a href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin">Uncle Bob</a>).</blockquote><p>The SOLID acronym stands for: <strong><em>S</em></strong><em>ingle-responsiblity Principle; </em><strong><em>O</em></strong><em>pen-closed Principle;</em><strong><em> L</em></strong><em>iskov Substitution Principle; </em><strong><em>I</em></strong><em>nterface Segregation Principle; </em><strong><em>D</em></strong><em>ependency Inversion Principle.</em></p><p>I’ve already written an article covering the<strong> </strong><a href="https://ramonprata.medium.com/reactsmalltips-open-closed-react-components-248226863276"><strong>Open-closed Principle</strong></a><strong> in React</strong>. In this one we’re gonna cover the <strong>Interface Segregation Principle</strong>.</p><p>So, what <strong>Interface Segregation Principle (ISP from now on) </strong>is all about? The idea here is that..</p><blockquote>Clients should not be forced to depend upon interfaces that they do not use.<br>Robert C. Martin (aka <a href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin">Uncle Bob</a>).</blockquote><p>Bringing that concept to the React world, we could say that.. <br><strong>components shouldn’t depend on props that they don’t use. </strong>And there are at least two scenarios which that could happen.</p><ol><li>We have a component <strong>Page</strong> that renders a <strong>ProductList </strong>component<strong> </strong>which renders a <strong>ProductItem</strong> component for each product mapped in <strong>ProductList</strong>.</li></ol><p><strong>Page component</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*iYjZV9pf3g62U-kyqKpBCw.png" /></figure><p><strong>ProductList component</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*QjCsUMADKEJDD90TrmWgMA.png" /></figure><p>Let’s say in our <strong>Page </strong>component we have a <strong>toggle </strong>to <strong>highlight </strong>products that are rated with <strong>5 stars</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*USt2-Ic_aJ1qxQDKAwJ-aQ.png" /></figure><p>So in that case, each <strong>ProductItem</strong> needs to know if the <strong>Page </strong>wants to <strong>highlight </strong>the product. But, between our <strong>Page </strong>component and our <strong>ProductItem </strong>component we have our <strong>ProductList c</strong>omponent. We could pass a prop (<strong>shouldHighLight</strong>) like <strong>Page =&gt; ProductList =&gt; ProductItem.</strong> But that means <strong>ProductList would depend upon a prop that it doesn’ t use. </strong>This well known bad practice in React is commonly called <strong>props drilling.</strong></p><p>So, how can we apply the <strong>ISP </strong>to solve this issue? Well, there are some options for that. We could use React Context API or even a State Management to share states across<strong> components, </strong>but <strong>there is a simpler way to fix this, which is the renderProps approach</strong>. In this approach we create sort of a shortcut between <strong>Page </strong>and <strong>ProductItem </strong>and pass the <strong>shouldHighLight</strong> prop directly from <strong>Page =&gt; ProductItem</strong>. The <strong>ProductList </strong>doesn’t need to know about the <strong>shouldHighLight </strong>prop, hense <strong>it will no longer depend upon a prop that it doesn’t use</strong>.</p><p>Refactored <strong>Page component</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*XgUfIdL_w53nLmdwnAi95w.png" /></figure><p>Refactored <strong>ProductList component</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*YuBbkYBuY4dHOzo7UEoZ1g.png" /></figure><p>2. Now that we applied the <strong>ISP </strong>to solve that <strong>drilling props issue</strong>, there is another scenario, much simpler, that we can also <strong>apply ISP in React components</strong>. Let’s say our <strong>ProductItem </strong>wants to render a <strong>ProductImage. </strong>This one<strong> </strong>only need the <strong>image path</strong> from <strong>product</strong>, it doesn’t care about other properties the product might have, so <strong>it shouldn’t have to depend upon things that it doesn’t use</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*JK-3HnGlCC5Id2KC4NtmDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*FYJ7LBnliy6RAgbrOAdBRQ.png" /></figure><p>You probably have already done this instinctively in your code, and yet you didn’t know you were applying the <strong>Interface Segregation Principle.</strong></p><p>So that was the ISP (<strong>Interface Segregation Principle</strong>) in action with React components. Hope this post was helpful.</p><p>You can find the code on my <a href="https://github.com/ramonprata/react-interface-segregation-in-components"><strong>Github</strong></a><strong>. <br></strong>Thanks a lot for reading this far.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1a63d5a0e9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactSmallTips: Open-closed React components]]></title>
            <link>https://ramonprata.medium.com/reactsmalltips-open-closed-react-components-248226863276?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/248226863276</guid>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[component-composition]]></category>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 12:15:02 GMT</pubDate>
            <atom:updated>2022-08-10T12:15:02.016Z</atom:updated>
            <content:encoded><![CDATA[<p>At some point in your career as a software developer you might start worrying about not just write a code that works, but a code that is readable, easy to understand, easy to maintain and scalable. In other words, a good quality code.</p><p>In order to achieve that, there are some guides like: <em>patterns</em>, <em>paradigms and principles</em>. Those guides were designed by real developers to solve well known real problems in programming. Among them, we have <strong>SOLID Principles</strong>.</p><blockquote><strong><em>SOLID</em> </strong>is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin (also known as <a href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin">Uncle Bob</a>).</blockquote><p>The SOLID acronym stands for: <strong><em>S</em></strong><em>ingle-responsiblity Principle; </em><strong><em>O</em></strong><em>pen-closed Principle;</em><strong><em> L</em></strong><em>iskov Substitution Principle; </em><strong><em>I</em></strong><em>nterface Segregation Principle; </em><strong><em>D</em></strong><em>ependency Inversion Principle.</em></p><p>If you search for SOLID principles, you’ll probably find a lot of examples usually using <em>classes </em>(<strong>OOP</strong>). But the concept, the ideas behind the principles are not restricted only to <em>classes</em>. In this post we will focus on the letter <strong>O </strong>(<strong>O</strong>pen-closed Principle) applied to a React Component.</p><p>So, what <strong>Open-closed Principle</strong> is all about? The idea here is that..</p><blockquote>The objects or entities should be open for extension but closed for modification.</blockquote><p>So, if we bring this concept to the React world, we can think of components as objects or entities. That means it would be a good practice to create components <strong>open to extension</strong>, but <strong>closed to modification</strong>. At least the reusable ones</p><p>So let’s see a scenario where we can apply this principle in a reusable React Component. In most applications, specially mobile ones, we see a “thing” that is present in almost every screen: the <strong>Header.</strong></p><p>At the beginning of the project, that <strong>Header </strong>might be a simple “box” with some style and a logo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*JBjlUM1ttVwsRAlXs0eknA.png" /></figure><p>And your code will be as simple as the Header needs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*lRpT2VqyXc-pHm6rzQc25w.png" /></figure><p>But as the application grows, that Header will need some changes: a button/icon to open a menu, to navigate; an input text where the user can search for something and more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*v2kEu5OldNvbs5ik8GvXRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*ODEZPLU82OycPNlzNcFaKw.png" /></figure><p>If we don’t think about the <strong>Open-closed principle</strong> here, we’ll end up making changes to the <strong>Header </strong>component every time a new feature comes up. And our code will start to get a little messy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*HYXaw1L1EEBSZJaA6rroiw.png" /></figure><p>Now we know we can do better using the <strong>Open-closed principle</strong>. But how? Like I said, the concept is not restricted only to <em>classes</em>, so we can implement the principle using approaches more suited to functions and components. Those approaches are already in React docs, I’m talking about: <a href="https://reactjs.org/docs/composition-vs-inheritance.html"><strong>Composition </strong></a>&amp; <a href="https://reactjs.org/docs/composition-vs-inheritance.html#specialization"><strong>Specialization</strong></a>. So let’s do that..</p><p>First, let’s create the <strong>OpenClosedHeader</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*l0yqEe8G0Zc8z9XG6fMXMw.png" /></figure><p>As you can see, the Header keeps its structure and default style, but it is now truly context-agnostic. We can have something on the left side, some children components in the middle and something on the right side, but everything is optional. That means, we have a component that is open for <strong>extension </strong>but closed for <strong>modification. </strong>We don’t need to change it for every new feature. But how can we extend this component? Well, we can use the <strong>Specialization </strong>approach mentioned before.</p><p>Let’s create a <strong>HeaderTitle. </strong>A<strong> </strong>component that uses the <strong>OpenClosedHeader </strong>behind the scenes, but it renders a <strong>title </strong>instead of hard-coded <strong>Logo </strong>component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*luQka1tmdE2s6pQtJQSRXQ.png" /></figure><p>As you can see, our <strong>Specialized </strong>Header accepts a <strong>title </strong>that can be a simple string which will be rendered in an <strong>&lt;h4&gt; HTML</strong> tag, or it can be a entire new component. Note that it also <strong>accepts and forwards</strong> all the <strong>props </strong>that <strong>OpenClosedHeader </strong>takes. And we can use it like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*62ccdyNjHY9rIEVnLrEtHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*DrblDzpqTIzh_4KoJvCT5A.png" /></figure><p>But this is too basic, let’s make a more interesting <strong>Specialized </strong>component..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*J2TCffAVfPme5Fw4Dr53bA.png" /></figure><p>Using <strong>HeaderNavigation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*OW7mN5dexNF3b-dzT0Jvfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*6jmqOsSMK1dukus9p1ODlw.png" /></figure><p>And more interesting: Since our <strong>HeaderNavigation </strong>is a <strong>specialization </strong>of <strong>OpenClosedHeader,</strong> we can simply pass a complete new component as children to it..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*rrJAaA6rr_InO7Zy4qqSkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*su_jozQ0Dx0LxLkg7vNu_g.png" /></figure><p>To sum up. In order to implement the <strong>Open-Closed</strong> principle, we created a really flexible component <strong>OpenClosedHeader. </strong>This component<strong> </strong>can be extended (<strong>Open</strong>) and it doesn’t need to be modified every time we face a new scenario (<strong>Closed</strong>). We only have to think about the most common cases in our application and implement <strong>Specialized </strong>versions of the original component to cover that cases. For <strong>very specific</strong> cases that the specialized components doesn’t cover, we still can use the basic <strong>OpenClosedHeader</strong> (with its default layout and behavior)<strong>, </strong>and pass an entire customized component as children to it.</p><p>I hope this post was useful and helps you to write better components using good practices like the Open-Closed principle.</p><p>Thank you. Cheers!</p><p>REFERENCES</p><ol><li>SOLID Principles — By <a href="https://www.digitalocean.com/community/conceptual_articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design">Digital Ocean</a></li><li><a href="https://reactjs.org/docs/getting-started.html">React docs</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=248226863276" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSSmallTips — Creating custom matcher assertions with Jest]]></title>
            <link>https://ramonprata.medium.com/jssmalltips-creating-custom-matcher-assertions-with-jest-b334a2777859?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b334a2777859</guid>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 12:41:44 GMT</pubDate>
            <atom:updated>2022-02-02T12:41:44.671Z</atom:updated>
            <content:encoded><![CDATA[<h3>JSSmallTips — Creating custom matcher assertions with Jest</h3><p>If you have been working with Javascript for a while, you’ve probably worked or at least seen something about automated tests using a <em>lib </em>called <strong>Jest</strong>. Currently, <strong>Jest </strong>is the most used and recommended library for dealing with unit and integration tests in Javascipt applications. I think one of the reasons for this is because it comes with a lot of things you can use to create good and reliable automated tests. One “thing” you will definitely be using all the time, while coding your tests, is <strong>matcher assertion</strong>.</p><p><strong><em>Matcher assertions</em></strong> are methods we use in our tests to validate values and verify whether they meet certain conditions. There are a number of built-in matcher assertions provided by <strong>Jest</strong>.</p><p>But, even though it seems that Jest has all types of matchers you might need, it is possible that you find a specific scenario where this isn’t the case. So, wouldn’t be really handy for you, and your team, if there were a matcher that fits exactly that scenario and it’s also <strong>easy to use?</strong> That’s when<strong> custom matcher assertions </strong>comes in. Since creating all possible matchers we need would be an almost impossible task, the <strong>Jest </strong>community has provided a way for us to create our own matchers to suit our needs.</p><p>Let’s see how that works and what are the bennefits of creating our own matchers.</p><h4>Creating our first custom matcher</h4><p>Here is how a custom matcher looks like. Don’t worry, I’ll explain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*YykY2mEl4JVxUuwdMn-0Mg.png" /></figure><p>To create a custom matcher we need to use the <strong><em>expect.extend</em></strong> function which takes an <strong><em>object </em></strong>as an argumment.</p><p>That <em>object </em>must have a function, which is your matcher. The function itself must return an object with <strong>2 keys</strong>:</p><ul><li><strong>pass</strong>: <em>boolean </em>— indicates whether there was a match or not (<em>true or false</em>)</li><li><strong>message</strong>: <em>function </em>— is a function that will returns an error message in case of failure.</li></ul><p><strong>Note: </strong>since we have cases where we need to assert whether <strong>THERE IS A MATCH</strong> or <strong>THERE IS NOT A MATCH</strong>. We need to provide a message for each</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*p3GFAfXzKZKK_07B4_hHYA.png" /></figure><h4>Talk is cheap, show me the code</h4><p>Well, now that we know the theory, let’s create a custom matcher and see what we can do with it.<br>Let’s say we have functions that manipulate <em>arrays of objects</em> (<strong>removing</strong>, <strong>filtering </strong>or <strong>adding objects</strong>). We wanna make sure that our functions are doing what they are supposed to do and returning new <strong><em>arrays </em></strong>with or without <strong>certain objects</strong>.</p><p>To do so, we can use some <em>built-in</em> functions — <strong><em>equals</em></strong>, <strong><em>arrayContaining</em></strong> and <strong><em>objectContaining —</em></strong> that already exists in <strong>Jest</strong> and combine them to create a <strong><em>more straight forward </em></strong><em>and </em><strong><em>easy to use</em></strong> custom matcher. Given any <strong><em>key/value</em></strong> pair we pass as an argument to the matcher, it should tell us weather there is an object inside that array that matches the argument or not.</p><p>So, lets do that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*4hwQJvdDvdrlTQiCOKf9hg.png" /></figure><h4>Now, the usage</h4><p><strong><em>Scenario</em></strong>: We have a fellowship with some members and we wanna make sure that our functions, <strong>addMember </strong>and <strong>removeMember,</strong> are working fine.</p><p>To use our custom matcher the only thing we need to do is importing our <strong><em>jestCustomMatchers </em></strong>file with the custom matcher we just created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Ky5s4kyk-M_VzgBvRetj5A.png" /></figure><h4><strong>Result</strong></h4><p>Our tests passed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*3GIrW2kZmz4305nfceOmog.png" /></figure><p>To make sure it is everything alright, let’s force an error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*wXk1nVso3tmrMnEmFemL_g.png" /></figure><p>Well, apparently our matcher is working just as expected.</p><p>So, that’s how we create our own matcher using <strong>Jest</strong>. Now it’s your time. Take a look into your application’s tests, maybe there is something you are doing repeatedly that you could <strong>improve </strong>by using this <strong>trick</strong>. <strong>Make your tests more readable </strong>and <strong>easy to use</strong> for you and your team. Explore all the possibilities provided by <strong>Jest</strong>. Btw.. you can create custom matchers that return a <strong>Promise </strong>of an object <strong>for async code</strong>, check that out!</p><p>Thanks for join me,</p><p>Cheers!</p><h4>REFERENCES</h4><ul><li><a href="https://jestjs.io/docs/">https://jestjs.io/docs/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b334a2777859" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactSmallTips — criando um hook para lidar com promises]]></title>
            <link>https://ramonprata.medium.com/reactsmalltips-criando-um-hook-para-lidar-com-promises-aa0c27e001e7?source=rss-a303fddd144a------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa0c27e001e7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Ramon Prata]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 12:56:29 GMT</pubDate>
            <atom:updated>2021-09-08T12:56:29.954Z</atom:updated>
            <content:encoded><![CDATA[<h3>ReactSmallTips — criando um hook para lidar com promises</h3><p>Se você desenvolve em React/React native, provavelmente já teve que criar um componente para <em>renderizar</em> um conteúdo que vem de uma API. Nesses cenários é comum termos que pensar em uma lógica de controle de estado para <em>renderizar </em>na tela, por exemplo, um <em>loading/squeleton</em> até que a chamada da API conclua e por fim <em>renderizar </em>o conteúdo retornado ou um <em>feedback </em>erro ou retorno vazio. Conforme a aplicação cresce percebemos que esse padrão começa a se repetir em diferentes partes da aplicação. Algo como..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tkPXw-ahW-9Ymo8_D-LNg.png" /></figure><p>Hoje em dia já temos <em>libs </em>como — <em>React Query; Redux toolkit (</em>para quem usa<em> Redux)—</em> que facilitam um pouco lidar com cenários como esse. Mas se você quiser algo mais simples e sem precisar instalar mais uma <em>lib</em>, podemos modularizar esse padrão, separando-o em duas 2 partes: a <strong>lógica de estado </strong>e a <strong>lógica de renderização. </strong>Assim fica mais fácil reusa-las em vários locais na aplicação sem muito trabalho e duplicação de código. Para isso vamos criar um hook(<strong>usePromise)</strong> para reuso da lógica de estado e um componente(<strong>FallbackWrapper</strong>) para reuso da lógica de <em>renderização</em></p><ol><li>Crie o <strong>usePromise hook </strong>que<strong> </strong>será responsável por executar nossa promise e gerenciar/retornar os estados (<em>status</em>):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*IC7L0adzph_ppi0Dle8iGQ.png" /></figure><p>2. Crie o <strong>FallbackWrapper component</strong> que será responsável por tratar a nossa lógica de <em>renderização, </em>aplicando uma ideia de encapsulamento que mencionei no meu outro post (<a href="https://ramonprata.medium.com/reactsmalltips-renderiza%C3%A7%C3%A3o-condicional-encapsulada-30eb4ca1833b">Renderização condicional encapsulada</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*u_j9FJByGsCtc8hQ4zmpFA.png" /></figure><p>3. Agora vamos refatorar o <strong>MyComponent </strong>para usar o hook <strong>usePromise</strong> e o componente de renderização <strong>FallbackWrapper:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*S_94GkkwypYEHkkkZCyYrA.png" /></figure><p>Note que <strong>reduzimos </strong>significamente o <strong>tamanho </strong>do nosso <strong>código </strong>além de deixa-lo mais <strong>legível </strong>e <strong>declarativo.</strong></p><p>Separar a logica de estado (<strong>hook</strong>) da lógica de <em>renderização </em>(<strong>component</strong>), potencializa e flexibiliza o reuso em diferentes partes da aplicação. Como são independentes a agnósticos a contexto, o <strong>usePromise e FallbackWrapper </strong>podem ser usados em conjunto ou separados.</p><p><strong>Muito importante! </strong>Observe que criamos nossa promise(<em>loadDataPromise</em>) usando o <strong>useCallback </strong>do <strong>React</strong>. Isso porque no hook <strong>usePromise devemos </strong>passar a <em>promise </em>como dependência para o <strong>useEffect. </strong>Dessa forma, conseguimos “falar” para o <strong>React </strong>quando nossa <em>promise </em>deve/não-deve disparar (dado as mudanças no <em>array </em>de dependências do <strong>useCallbak</strong>).</p><p>O resultado para os possíveis cenários.. <strong>Loading</strong><em>, </em><strong>Success</strong><em>, </em><strong>Error </strong><em>e </em><strong>Empty</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hn8u1rOXXYRIwaNaAQFvhg.png" /></figure><p>Se você leu até aqui, agradeço e espero que essa dica contribua em seus projetos. Até a próxima..</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa0c27e001e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>