Unit testing in React
Tags: javascript, react, programming, productivity
Published: 2022-04-22 09:56:49

*In case it helped :)*
<a href="https://www.buymeacoffee.com/aseemwangoo" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Pass Me A Coffee!!" style="height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>


<!-- wp:paragraph -->
<p>We will cover briefly:</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>Write unit tests for components</li><li>Snapshot Testing with Jest</li></ol>
<!-- /wp:list -->

{% youtube hyIacC653_A %}

<!-- wp:heading {"level":3} -->
<h3>About Unit&nbsp;Testing</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Unit testing is a testing method that tests an individual software unit in isolation. This involves verifying the <em>output</em> of a function or component for a given <em>input</em>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In terms of React components, this means checking that the component</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>renders as expected for the specified props.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>The main goal is to write tests that verify whether our component works as expected.</p>
<!-- /wp:paragraph -->

{% youtube 4edYJZkmqs0 %}

<!-- wp:heading {"level":4} -->
<h4>Intro to&nbsp;Jest</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We will make use of <a href="https://jestjs.io/" rel="noreferrer noopener" target="_blank">jest</a> in order to test our react components. As per the documentation</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Jest is a JavaScript testing framework designed to ensure correctness of any JavaScript codebase. It allows you to write tests with an approachable, familiar and feature-rich API that gives you results quickly.</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>Let's see how to install it</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Install the following dev dependencies</li></ul>
<!-- /wp:list -->

```javascript
npm i --save-dev @testing-library/react react-test-renderer
```

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Note: Make sure your <code>react</code> and <code>react-test-renderer</code> are using the same version</p></blockquote>
<!-- /wp:quote -->

<!-- wp:heading {"level":4} -->
<h4>Write unit tests for components</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We will start by creating a simple text component, which looks like this</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://cdn-images-1.medium.com/max/1600/1*m4j4_6bdvWhoOevKV4wtTg.png" alt="Simple Text Component"/><figcaption>Simple Text Component</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>It takes in a parameter <code>text</code> and displays using the <code>h3</code> style tag onto the screen.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Take note of the <strong>data-testid. </strong>This will be used for testing this component</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>Let’s test this component now,</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>We create a folder called <code>__tests__</code> which is present inside the <code>components</code> folder. Inside this, we create component-specific folders</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://cdn-images-1.medium.com/max/1600/1*EX_1LanSBv46PnJajCH9_Q.png" alt="Folder structure"/><figcaption>Folder structure</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>We have all the components under <code>components</code> and all the tests under <code>__tests__</code> This way we can create subfolders per component.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>eg: For <code>components/Text</code> we have the corresponding test under <code>components/__tests__/Text</code> folder</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>All the tests should be comprised of the convention <code>&lt;TestName&gt;.test.js</code> This helps jest to understand the test files</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>So our test file would be <code>Text.test.js</code>&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Next, we import the package <code><em>testing-library/react</em></code><em> </em>along with the jest as</li></ul>
<!-- /wp:list -->

```javascript
import { render, screen, cleanup } from "@testing-library/react";
import Text from "../../Text/Text";
import "@testing-library/jest-dom";
```
<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Note: we also need to import the component which we want to test. In our case, it's the <code>Text</code></p></blockquote>
<!-- /wp:quote -->

<!-- wp:list -->
<ul><li>This is how our test looks like</li></ul>
<!-- /wp:list -->

```javascript
test("should render text component", () => {
  render(<Text />);
  var textElem = screen.getByTestId("text");
  expect(textElem).toBeInTheDocument();
});
```

<!-- wp:paragraph -->
<p><strong>test</strong>: This creates a test closure, and takes in the par<em>am</em> <code>name</code> (name of your test) and param <code>fn</code> (function for your test)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>render</strong>: This comes from the <code><em>testing-library/react</em></code>It renders into a container that is appended to the document body.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>In our case, we render the <code>Text</code> component</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p><strong>screen</strong>: This can be thought of as a <code>document.body</code>, which has every query that is bounded to the component you rendered in the previous call</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>We assigned a <strong>data-testid </strong>to our Text component, and we try to get that using <a href="https://testing-library.com/docs/queries/bytestid/" rel="noreferrer noopener" target="_blank">getByTestId</a></p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>Finally, we use <code>expect</code> and <code>toBeInTheDocument</code> to test that the element is present inside the rendered document.&nbsp;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The <code><a href="https://testing-library.com/docs/ecosystem-jest-dom" rel="noreferrer noopener" target="_blank">jest-dom</a></code> utility library provides the&nbsp;<code>.toBeInTheDocument()</code> matcher, which can be used to assert that an element is in the body of the document, or not.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Run the tests using</li></ul>
<!-- /wp:list -->

```javascript
npm test
```
<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://cdn-images-1.medium.com/max/1600/1*IeMq8iA5SIWoriit8pSmVw.png" alt="Results from the unit test"/><figcaption>Results from the unit&nbsp;test</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>And, we wrote our first test 🎉🎉🎉</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Snapshot Testing with&nbsp;Jest</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Any snapshot test case renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated as per the new version of the UI component.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let’s test our <code>Text</code> component.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://cdn-images-1.medium.com/max/1600/1*I5lep5PgozgmaUq7efYmng.png" alt="Snapshot testing with Jest"/><figcaption>Snapshot testing with&nbsp;Jest</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li>We will be making use of our <code><em>react-test-renderer</em></code><em> </em>library which we installed in the previous step.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Instead of rendering the graphical UI, which would require building the entire app, we can use a test renderer to quickly generate a serializable value for your React tree.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>We use <code>renderer</code> to create the <code>Text</code> component</li><li>Next, we save the response in the JSON using <code>toJSON</code>&nbsp;</li><li>Finally, we use the <code>expect</code> to compare the result using <code><a href="http://This%20ensures%20that%20a%20value%20matches%20the%20most%20recent%20snapshot" rel="noreferrer noopener" target="_blank">toMatchSnapshot</a> </code>which ensures that the value matches the most recent snapshot.</li><li>Run the tests using</li></ul>
<!-- /wp:list -->

```javascript
npm test
```

<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://cdn-images-1.medium.com/max/1600/1*XYLwJo4g0AAoojYNm1wh3w.png" alt="Snapshot testing in React"/><figcaption>Snapshot testing in&nbsp;React</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>Note: There will be no snapshots present when you run the snapshot tests for the first time. The console will tell to generate the snapshots&nbsp;</p></blockquote>
<!-- /wp:quote -->

<!-- wp:list -->
<ul><li>The snapshots are generated inside the <code>__snapshots__</code> folder as&nbsp;</li></ul>
<!-- /wp:list -->

<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://cdn-images-1.medium.com/max/1600/1*AmK8noXVKTy8hDuhdlww-Q.png" alt="Snapshots generated"/><figcaption>Snapshots generated</figcaption></figure></div>
<!-- /wp:image -->

*In case it helped :)*
<a href="https://www.buymeacoffee.com/aseemwangoo" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Pass Me A Coffee!!" style="height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>

{% youtube hyIacC653_A %}

<!-- wp:paragraph -->
<p><a rel="noreferrer noopener" href="https://github.com/AseemWangoo/expriments_with_react" target="_blank"><em>Source code.</em></a>

<!-- wp:paragraph -->
<p><strong><em>Website: </em></strong><a href="https://funwithreact.web.app/" rel="noreferrer noopener" target="_blank"><strong><em>https://funwithreact.web.app/</em></strong></a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->