<?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 Tejashree Bandi on Medium]]></title>
        <description><![CDATA[Stories by Tejashree Bandi on Medium]]></description>
        <link>https://medium.com/@tejashree_77556?source=rss-15190a033654------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-aLn0ZJLRtjHMbMrHHkF6A.png</url>
            <title>Stories by Tejashree Bandi on Medium</title>
            <link>https://medium.com/@tejashree_77556?source=rss-15190a033654------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:45:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tejashree_77556/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[Test Driven Development (TDD) with React Testing Library & Jest]]></title>
            <link>https://medium.com/make-it-heady/test-driven-development-tdd-with-react-testing-library-jest-906085418f?source=rss-15190a033654------2</link>
            <guid isPermaLink="false">https://medium.com/p/906085418f</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Tejashree Bandi]]></dc:creator>
            <pubDate>Tue, 19 May 2020 19:22:16 GMT</pubDate>
            <atom:updated>2022-06-17T07:17:05.437Z</atom:updated>
            <content:encoded><![CDATA[<h3>Test After Development (TAD) with React Testing Library &amp; Jest</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKHUYc6XXS4cUn-_NAwKOA.jpeg" /></figure><p>There are multiple tools and libraries in React for testing. These include <em>Jest, React Testing Library, Mocha, Chai, Karma, Jasmine, Cypress IO, Puppeteer, Enzyme, </em>and more. Is there a good reason to choose one of these over the others? Personally, I prefer React Testing Library (RTL) to test my React components.</p><p>Many developers choose to work with Enzyme or React Testing Library from list of testing libraries mentioned above. Initially, I had started with Enzyme and Jest. Jest is mainly used for assertion, while Enzyme deals with testing react component like render components, and checking things like props and states. But as our team started to work with React hooks for our applications, Enzyme was no longer able to meet our requirements. (Despite these issues, I wouldn’t say that it’s bad practice to use Enzyme, but it does take extra effort to write the right sort of code practices.)</p><p>After looking for an alternative, I started using React Testing Library (RTL). With RTL, I found that I could write cleaner code and user-interactive test cases. When I converted my Enzyme code to RTL, I was able to write more optimized code, and could remove many lines of code. RTL interacts with DOM nodes; it doesn’t care whether the state is true or false. Since RTL works more directly with DOM nodes, using it with Jest-DOM can improve assertions.</p><p><em>“</em><a href="https://twitter.com/kentcdodds/status/977018512689455106"><em>The more your tests resemble the way your software is used, the more confidence they can give you.</em></a><em>” — </em><a href="https://twitter.com/kentcdodds/status/977018512689455106?lang=en"><em>Kent Dodds</em></a></p><p><strong>Test Driven Development</strong> (TDD) is the process of testing specific parts of an application’s behavior. A healthy approach to TDD is to first define the required behavior tests, and then keep on passing the tests through development.</p><h3>Installation</h3><p>If we start our application with <em>create-react-app</em>, we don’t need to add any package installation.</p><p>Otherwise, we will have to install the following dependencies:</p><pre># add with npm <br>npm install --save-dev @testing-library/react</pre><pre># or with yarn <br>yarn add --dev @testing-library/react</pre><pre># add with npm <br>npm install --save-dev @testing-library/jest-dom <br></pre><pre># or with yarn <br>yarn add --dev @testing-library/jest-dom</pre><p><strong>Jest</strong>: We are using Jest for assertion in our tests. Jest is another fast-testing framework, with features like mocking, snapshot testing, and great assertions. It is developed and used by Facebook for its react applications. With <em>create-react-app</em>, there’s no installation headache to set up the Jest.</p><h3>File and Folder Structure</h3><p>Standard guidelines would call for the creation of a __ test __ folder, to hold onto test files. However, I approached this in a different way.</p><p>Personally, I don’t see the advantages of adding a__ test __ folder. This is in part because when Jest crawls your root directory, it only searches for test files to run; it doesn’t look for a folder. Hence, my personal choice is to place test files in the component folder itself.</p><pre>- node_modules<br>- public<br>- src<br>  - components<br>    - TestComponent<br>      - TestComponent.jsx<br>      - styles.scss<br>      - <strong>TestComponent.test.js</strong>      // here is what I do different<br>    - index.js                    // source of truth for component export<br>  - utils<br>    - helpers.js<br>  - App.jsx<br>  - App.test.jsx<br>  - App.styles.js<br>  - index.js</pre><h3><strong>Before Starting with Tests</strong></h3><p>Some basic things to know before moving ahead:</p><blockquote>it or test: This basically describes the test. It requires two parameters, like the name of the test and a function that holds the entire test.</blockquote><blockquote>expect: Condition needed to pass the test. Expect condition will compare the received parameter to a matcher.</blockquote><blockquote>matcher: A function that corresponds to the situation you expect.</blockquote><blockquote>render: A function to render a given component which returns a React element.</blockquote><h3>Snapshot Testing</h3><p>As the name suggests, snapshot testing generates a mirror image of the DOM node of our React component.</p><p>To check a snapshot, first, we need to get our jsx working. Then we can generate a snapshot of it, using theyarn test/npm test command. This will allow us to test if the passed data is properly reflected in the component. Jest will compare the snapshot to the generated output for the test.</p><p>If the test fails, that means some unexpected issues occurred. We’ll need to make some changes in the component to fix the issue and get the expected results, by generating a new snapshot and making sure we pass the test.</p><p>Now, let’s try to generate a new snapshot of the component.</p><p>We will create a snapshot for our very basic <em>App.js</em> file by creating an <em>App.test.js </em>file:</p><pre>//App.test.js</pre><pre>import React from &#39;react&#39;<br>import {render, cleanup} from &#39;@testing-library/react&#39;<br>import App from &#39;./App&#39;<br><br> afterEach(cleanup)<br> <br> test(&#39;should generate a snapshot for app component&#39;, () =&gt; {<br>    const { asFragment } = render(&lt;App /&gt;)<br>    <br>    expect(asFragment(&lt;App /&gt;)).toMatchSnapshot()<br>   })<br>});</pre><p>To take a snapshot, first, we have to import render and cleanup from RTL. These two methods will be used in almost all of our test cases.</p><p>render is a function to render a given component, which returns a React element. And cleanup is passed as a parameter to afterEach to clean up everything after each test and avoid memory leaks.</p><p>Now, we’ll run the test command:</p><pre># add with npm <br>npm test</pre><pre># or with yarn <br>yarn test</pre><p>This will create a new folder __snapshots__ and a file App.test.js.snap in the src which will look like this:</p><pre>//App.test.js inside __snapshots__ folder<br>// Jest Snapshot v1, https://goo.gl/fbAQLP<br><br>exports[`Take a snapshot should take a snapshot 1`] = `<br>&lt;DocumentFragment&gt;<br>  &lt;div class=&quot;App&quot;&gt;<br>    &lt;h1&gt;Testing&lt;/h1&gt;<br>  &lt;/div&gt;<br>&lt;/DocumentFragment&gt;<br>`;</pre><p>If we make any change in <em>App.js</em>, our test will fail, because the snapshot will no longer match the component. To pass the test, we’ll need to press u to update the snapshot. Now, we should be able to pass the test and get the updated snapshot in App.test.js.snap.</p><h3>Testing a List of Items</h3><p>To test a list of React <strong>DOM elements</strong>, we will create a file called <em>List.js </em>inside<em> src -&gt; components -&gt;List </em>and paste the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2591235e5e15d1db5be9dd772ed5bb7b/href">https://medium.com/media/2591235e5e15d1db5be9dd772ed5bb7b/href</a></iframe><p>Then we’ll create a file named <em>List.test.js</em> inside <em>List</em> folder and paste the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcc0a9ba2e00fe9eff37eeaff0180efc/href">https://medium.com/media/bcc0a9ba2e00fe9eff37eeaff0180efc/href</a></iframe><p>In the first test (“<em>should render List component</em>”): I have rendered the List component and checked its existence. In the current scenario, we should pass the test.</p><p>In the second (“<em>renders data correctly</em>”): I am trying to render correct data. I have created one fake JSON object to compare with my actual data, and expect that it should get the same results from my actual data.</p><p>In the last one (“<em>Total length of list should be 3</em>”): I am trying to get the total length of my DOM Node child elements (number of li’s).</p><p>Now if we save the test file and run again in our terminal yarn test/npm test, the test should pass.</p><p><em>Woo-hoo! We’re are done with our first test, and we passed!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ghOGS5COV3Ww9wgs" /><figcaption>Photo by <a href="https://unsplash.com/@schmidy?utm_source=medium&amp;utm_medium=referral">Austin Schmid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Test Component Events</h3><p>To test React <strong>DOM elements</strong>, we’ll create a file called <em>Button.js </em>inside<em> src -&gt; components -&gt;Button</em> and paste the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda992e07181ae02b05f883ea271e366/href">https://medium.com/media/bda992e07181ae02b05f883ea271e366/href</a></iframe><p>Next, we’ll create test file called <em>Button.test.js</em> in the same <em>Button</em> folder and paste the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdd2cbe606f3963e756ebdf77ceb6537/href">https://medium.com/media/bdd2cbe606f3963e756ebdf77ceb6537/href</a></iframe><p>The component receives a callback function, and renders a button. So we have to test whether the callback function is called when the button is clicked.</p><p>Like the <em>List</em> example above, I rendered the component and used an assertion to check its existence. After that, I rendered the component again with different props (for example, text=‘Go’ as a prop), and expected the changes in assertion.</p><p>In the second test (“<em>calls correct function on click”</em>): to test the click event I used Jest’s mock function. Mock function lets us inspect the behavior of a function.</p><p>fireEvent.click creates a click event and sends that event on the given DOM node. This is a good way to test what happens when any action or event is fired.</p><p>In the last test (‘<em>The button should be enabled</em>’): I am using toHaveAttribute method. This checks that the disable attribute is not present in the button element. Now we can run the test, and it should work as expected.</p><h3>Test Asynchronous Actions</h3><p>As the name indicates, we will be using async/await to handle the events and two mock functions to request and resolve the data. To do so, we’ll create <em>Employees.js in component -&gt; listEmployees</em> folder and paste the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/939a7431151dcf40b50f8d2ba9e92f06/href">https://medium.com/media/939a7431151dcf40b50f8d2ba9e92f06/href</a></iframe><p>Next, we’ll create another test file named with <em>Employees.test.js</em>, using the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cb1db57e8c3b44bcfa646346745cecc/href">https://medium.com/media/6cb1db57e8c3b44bcfa646346745cecc/href</a></iframe><p>For an example of this Employee component: if we click on Get Employee List button, it calls a fetchEmployees function. To get the response, it calls the listEmployees callback function, which returns a <em>promise</em> to display a list of employees. So, we can say that the listEmployees callback function is in some parent component which performs some async request response API, and returns a <em>promise</em> in array.</p><p><strong>describe()</strong>:- As you can see, I have used describe(), which is used to divide test cases in some groups within the same file. I have only one test here, but I just wanted to illustrate the concept of describe(). If we had additional code in the Employee component or we added more test cases in this file (like error, DOM nodes, or other fire events), we could use describe() more effectively.</p><p>Now, let’s move ahead with the test. To test an async action, we have to pass a mock function that will return a <em>promise</em>. I have created a mock function using jest.fn(), which is used to resolve the <em>promise</em>.</p><p>First, we render the component by passing the listEmployees callback function as a prop. In the first assertion, it gives us empty results, because the click event has not fired yet. So, we should get a pass result.</p><p>Next, we fire a button click event, it calls listEmployees callback function and returns a <em>promise</em> to set our state employees .</p><p>During this process, if we check the emp-wrap element, it will still shows as empty, because the code is waiting for the listEmployees <em>promise</em> to return. Until the <em>promise</em> returns, we can use the waitForElement function to wait, until the element exists in the DOM. Once the DOM is ready with all the listing elements, we can now check with our assertion whether the content of the result matches the passed mock data.</p><p>Now, if we test this using yarn test/npm test, we should pass.</p><p>Using the above steps, we can check for an api error state by passing another mock function.</p><h3>Abstract</h3><p>React Testing is a great package for unit testing. It has many options for matching nodes, useful methods for firing DOM events, various utilities to deal with async code, and many more. I am still exploring it, but I personally enjoy working with RTL.</p><p>If this article helped you, I suggest that you to start with this package in your future developments. Thank you.</p><pre>P.S : We&#39;re hiring at Heady! 👋 If you would like to come work with us on some really cool apps please check out our careers page.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906085418f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/make-it-heady/test-driven-development-tdd-with-react-testing-library-jest-906085418f">Test Driven Development (TDD) with React Testing Library &amp; Jest</a> was originally published in <a href="https://medium.com/make-it-heady">make it heady</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>