<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" 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" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title><![CDATA[React Testing Library - Rafael Quintanilha]]></title>
<description><![CDATA[Essays about software engineering, web development, artificial intelligence, quantitative analysis, financial markets, books and tradition.]]></description>
<link>https://rafaelquintanilha.com/topic/react-testing-library/</link>
<image><url>https://rafaelquintanilha.com/content/images/2022/12/Logo-Design--2-.png</url><title>React Testing Library - Rafael Quintanilha</title><link>https://rafaelquintanilha.com/topic/react-testing-library/</link></image>
<lastBuildDate>Sun, 04 Dec 2022 23:32:35 GMT</lastBuildDate>
<atom:link href="https://rafaelquintanilha.com/topic/react-testing-library/rss/" rel="self" type="application/rss+xml"/>
<ttl>60</ttl>
<item>
<title><![CDATA[Writing Tests as User Stories in React]]></title>
<description><![CDATA[A mental model for designing UI tests.]]></description>
<link>https://rafaelquintanilha.com/writing-tests-as-user-stories-in-react/</link>
<guid isPermaLink="false">63706b6742a473003d9dcb9e</guid>
<category><![CDATA[React]]></category><category><![CDATA[React Testing Library]]></category><category><![CDATA[Testing]]></category><category><![CDATA[Best Practices]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Thu, 02 Apr 2020 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<figure class="image"><img alt="Writing tests as user stories" loading="lazy" decoding="async" width="730" height="412" src="https://rafaelquintanilha.com/_astro/cover.C8BHRagE_ZXhSWk.webp"><figcaption>Writing tests as user stories</figcaption></figure>
<p>Testing code can be a controversial subject, largely due to the multitude of ways one can go about writing a test.</p>
<p>There are no clear rules, and ultimately you are the one in charge of deciding what’s worth testing and how you’re going to do it.</p>
<p>One common mistake is to test implementation details, but perhaps you’ve read that already.</p>
<p>Let me take a step back then — what is the end goal of a test?</p>
<h2 id="writing-user-stories">Writing user stories</h2>
<p>A common software abstraction is to write user stories — that is, possible actions that a user can take when interacting with your application.</p>
<p>Suppose you are to build a Celsius-to-Fahrenheit converter. A legitimate story could be something like:</p>
<p><em>“As a user, I want to be able to convert from Celsius to Fahrenheit.”</em></p>
<p>Naturally, as a careful developer, you want to assert that for a given set of numbers and inputs the conversion works (or it fails gracefully for invalid inputs like “banana”).</p>
<p>Note, however, that testing that a function is able to successfully handle the conversion from Celsius to Fahrenheit is only half the story.</p>
<p>If you are able to perform the most expensive and relevant calculation but your end user can’t access it, all effort will be in vain.</p>
<p>Why is that?</p>
<p>Well, as a frontend developer, your job is to not only ensure users get the correct answers to their questions but also to make sure they can use your application.</p>
<p>Therefore, you need to assess that the user has interacted with your application as expected.</p>
<p>In our example, that means that somewhere on the screen you expect some text to be displayed like this: “25ºC equals 77ºF.”</p>
<p>Now, that’s a relevant test. You just assessed that, for a given input, the user satisfactorily got the right answer on the screen.</p>
<h2 id="stories-mostly-dont-care-about-details">Stories (mostly) don’t care about details</h2>
<p>The main takeaway here is that the user stories aren’t centered on your development implementations, so your tests shouldn’t be, either.</p>
<p>Of course, the scenarios in question are related to application-wide tests (things that have context), not bare-bones libraries.</p>
<p>If your goal is to create a library that converts Celsius to Fahrenheit to Kelvin, then it’s fine to test the details once you are detached of context.</p>
<p>Now that we understand that tests should resemble user stories, you can predict where semantics come from.</p>
<p>At the end of the day, your tests should have clear semantics such that you could read them in plain English—the same way you describe user stories.</p>
<p>We’ll see how we can leverage the <a href="https://github.com/testing-library/react-testing-library" rel="noopener noreferrer" target="_blank">React Testing Library API</a> to write semantic tests that make sense.</p>
<h2 id="case-study-temperature-converter">Case study: Temperature Converter</h2>
<p>Let’s dive further into the Temperature Converter application.</p>
<p>We’ll pretend that a competent Project Manager heard the complaints of their clients (probably any non-American who has moved recently to the US) and came up with the following requirements:</p>
<ul>
<li>As a user, I want to be able to convert from Celsius to Fahrenheit</li>
<li>As a user, I want to be able to convert from Fahrenheit to Celsius</li>
<li>As a user, I want to click on a Reset button so I can easily convert many values with minimal effort</li>
</ul>
<p>Apart from the lack of creativity of the PM when writing stories, the requirements are pretty straightforward.</p>
<p>We will sketch a simple app, do a good ol’ smoke test to check that everything looks alright, and then apply what we just learned in order to write better tests.</p>
<p>Consider the following CodeSandbox for our sample application:
<a href="https://codesandbox.io/s/temperature-converter-mw7se" rel="noopener noreferrer" target="_blank">https://codesandbox.io/s/temperature-converter-mw7se</a></p>
<p>Diving into the specifics of the code is beyond the scope of this article (check <a href="https://rafaelquintanilha.com/how-to-reuse-logic-with-react-hooks">“How to Reuse Logic With React Hooks</a>” for more context on how to use Hooks to create React applications).</p>
<p>However, the code should be pretty straightforward. We are basically requiring user input and allowing them to convert from Celsius to Fahrenheit or vice-versa.</p>
<p>We then display the results and a Reset button shows up. Upon clicking the button, the input is cleared and regains focus.</p>
<p>This aligns with what our users are looking for: we’ll improve the usability of the app and, most importantly, preserve its accessibility.</p>
<p>Now that we have a live application that seems to work, let’s be responsible developers and write some tests.</p>
<p>We’ll try to match each user story to a single test. By doing that, we will be confident that each requirement is being fulfilled with a set of tests backing us up.</p>
<p>Consider this basic skeleton for <code>App.test.js</code>:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user is able to convert from celsius to fahrenheit'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* story 1 goes here */</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user is able to convert from fahrenheit to celsius'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* story 2 goes here */</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user can reset calculation and automatically focus on the input'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  /* story 3 goes here */</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>(We are using <a href="https://jestjs.io/" rel="noopener noreferrer" target="_blank">Jest</a> as our test runner, but that’s not relevant to the main point presented in the article.)</p>
<p>Notice that our three tests are really straightforward and any failures in them would quickly expose what is really going on.</p>
<p>Now we’ll leverage RTL and write the first test in a way that makes sense:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> App </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './App.js'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { cleanup, render, screen } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> userEvent </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/user-event'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user is able to convert from celsius to fahrenheit'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">App</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> input </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Temperature:'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'25'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'25ºC equals to 77ºF'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'0'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'0ºC equals to 32ºF'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'banana'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'result'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeFalsy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">/* code goes on */</span></span></code></pre></figure>
<p>There are a couple of things to notice with the dependencies:</p>
<p>First, we import the component in question <code>App.js</code>.</p>
<p>Then, notice that we are importing <code>render</code> and <code>screen</code> from RTL. While the first has been around since the library’s first launch, <code>screen</code> is a new addition <a href="https://github.com/testing-library/react-testing-library/releases/tag/v9.4.0" rel="noopener noreferrer" target="_blank">shipped on version 9.4.0</a>. We will see its main advantage shortly.</p>
<p>We also import a new dependency, <a href="https://github.com/testing-library/user-event" rel="noopener noreferrer" target="_blank">userEvents</a>, straight from <code>@testing-library/user-event</code>. This library will boost our test readability and help us achieve our goal of improving our semantics.</p>
<p>Let’s actually dive into the test. If you are used to RTL, the first thing you’ll notice is that <code>render</code> is not returning anything. In fact, that’s the main advantage of importing <code>screen</code>.</p>
<p>What <code>screen</code> does is basically expose all queries that allow you to select elements in the screen (hence the name).</p>
<p>This is a pretty good change because it helps you avoid bloating the test with lots of <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="noopener noreferrer" target="_blank">destructuring</a>, which is always annoying when you are not sure yet which queries to use.</p>
<p>Also, the code looks cleaner. (Note: there’s still a case for de-structuring <code>container</code> and <code>rerender</code> as mentioned by Kent C. Dodds <a href="https://twitter.com/kentcdodds/status/1224790664354779136" rel="noopener noreferrer" target="_blank">in this tweet</a>.)</p>
<p>The other difference from conventional tests you might have been writing is the <code>userEvent</code> object.</p>
<p>This object provides a handful of user interactions that are semantically understandable and conceal implementation details. Consider the following example:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A7A49E;font-style:italic">// Previously</span></span>
<span class="line"><span style="color:#EDCC95">fireEvent.change</span><span style="color:#ECEBE8">(input, { target: { value: </span><span style="color:#97CCAE">'25'</span><span style="color:#ECEBE8"> } })</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">// With userEvents</span></span>
<span class="line"><span style="color:#EDCC95">userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'25'</span><span style="color:#ECEBE8">)</span></span></code></pre></figure>
<p>Not only is our code is shorter, but it also makes much more sense now.</p>
<p>Remember that our goal is to write a test as close as possible to plain English. By encapsulating implementation details, <code>userEvent</code> really puts us on the right track.</p>
<p>If you are curious, <a href="https://github.com/testing-library/user-event" rel="noopener noreferrer" target="_blank">go ahead and check their documentation</a>.</p>
<p>Once we are able to fill the input, we can now assert that the correct text is being displayed.</p>
<p>Now we can test a bunch of other options and confirm that what is displayed in the screen is expected (e.g., an invalid input like <code>banana</code> won’t work).</p>
<p>Note: in a modular application, the conversion functions could be extracted in their own file and have their own tests (with many more test scenarios).</p>
<p>If you test the function separately, there’s no need to make redundant checks in the user stories as well (test is code and you want it maintainable as such).</p>
<p>With a test that is only eight lines long, we were able to check that our first scenario works as expected.</p>
<p>Let’s jump into our second user story — convert from Fahrenheit to Celsius (maybe a New Yorker having some fun on a beach in South America).</p>
<p>The test should be pretty similar to our first one, with a single caveat: we need to make sure that the user has selected the right option.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user is able to convert from fahrenheit to celsius'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">App</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> fahrenheitOption </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Fahrenheit to Celsius'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.click</span><span style="color:#ECEBE8">(fahrenheitOption)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> input </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Temperature:'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'77'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'77ºF equals to 25ºC'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'32'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'32ºF equals to 0ºC'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'banana'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'result'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeFalsy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>That’s it. By leveraging <code>userEvent</code> again, emulating a click event becomes trivial.</p>
<p>Our code is perfectly readable and guarantees that the reverse direction (F to C) works as expected.</p>
<p>Our third and final test is slightly different — now our goal is to test the user experience rather than whether or calculator works.</p>
<p>We want to make sure that our application is accessible and that users can rapidly test several values:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user can reset calculation and automatically focus on the input'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#EDCC95">  render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">App</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> input </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Temperature:'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.type</span><span style="color:#ECEBE8">(input, </span><span style="color:#97CCAE">'25'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'result'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> resetButton </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> screen.getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Reset'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  userEvent.click</span><span style="color:#ECEBE8">(resetButton)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">screen.queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'result'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeFalsy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(document.activeElement)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(input)</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>There you have it. We basically made three checks:</p>
<ul>
<li>Whenever a user adds some input, there’s a result displayed (the actual message shown is omitted from the test once this isn’t what is being checked here)</li>
<li>When the Reset button is clicked, the result is not there anymore</li>
<li>The focus on the screen is back to the input</li>
</ul>
<p>One of my favorite things about RTL is how easy it is to assert where a focus really is.</p>
<p>Notice how semantic <code>expect(document.activeElement).toBe(input)</code> is. That pretty much looks like plain English to me.</p>
<p>And that’s it. Our three stories are covered, the Project Manager is happier, and hopefully our tests will keep the code clean for a long time.</p>
<h2 id="conclusion">Conclusion</h2>
<p>The aim of this article was to expose the recent modifications in the React Testing Library’s API and show you how you can explore it to write better tests for you and your team.</p>
<p>I feel way more confident when I write tests that I understand because I stop chasing meaningless metrics (e.g. code coverage) to pay attention to what really matters (e.g. if my designed scenario works as expected).</p>
<p>React Testing Library was a big step in the right direction, mainly if you have some Enzyme background (in which case you might want to check “<a href="https://rafaelquintanilha.com/react-testing-library-common-scenarios/">React Testing Library Common Scenarios</a>,” where I explore how you tackle everyday scenarios in a React application).</p>
<p>It really facilitates testing what your application should do rather than how it does it. The semantics make a difference.</p>]]></content:encoded>
</item>
<item>
<title><![CDATA[React Testing Library Common Scenarios]]></title>
<description><![CDATA[How to write tests that are common to many applications using React Testing Library.]]></description>
<link>https://rafaelquintanilha.com/react-testing-library-common-scenarios/</link>
<guid isPermaLink="false">637058a042a473003d9dcaf3</guid>
<category><![CDATA[React]]></category><category><![CDATA[React Testing Library]]></category><category><![CDATA[Testing]]></category>
<dc:creator><![CDATA[Rafael Quintanilha]]></dc:creator>
<pubDate>Tue, 16 Jul 2019 03:00:00 GMT</pubDate>

<content:encoded><![CDATA[<p><strong>tl;dr – <a href="https://react-testing-library-examples.netlify.app" rel="noopener noreferrer" target="_blank">React Testing Library Examples</a></strong></p>
<p>When I was first introduced to <a href="https://testing-library.com/react" rel="noopener noreferrer" target="_blank">React Testing Library</a>, my first reaction was "alright, yet another React framework" and I didn't pay much attention to it. The library quickly gained traction, but as I had been working with Enzyme for a while, I didn't bother.</p>
<p>With the introduction of React Hooks, testing with Enzyme became harder. To be frank, I never completely enjoyed Enzyme and paradoxically this was the main reason I relucted to switch libraries – I was too committed. Moreover, most of the test scenarios I use in my workdays were already developed and I needed to do little thinking when creating new tests.</p>
<p>Yet, every now and then I'd struggle writing some test, especially if it involved mocking API calls. Somehow the tests didn't feel right. Finally, I decided to give React Testing Library a shot and, well, as you might have imagined, I love it!</p>
<p><strong>This article is a compilation of common test scenarios that you are likely to find when developing your application</strong>. For each scenario, I describe the problem and how you can write a test for it with <a href="https://jestjs.io" rel="noopener noreferrer" target="_blank">Jest</a> + React Testing Library.</p>
<h3 id="why-react-testing-library">Why React Testing Library</h3>
<blockquote>
<p>The more your tests resemble the way your software is used, the more confidence they can give you.</p>
</blockquote>
<p>The above sentence is the <a href="https://testing-library.com/docs/guiding-principles" rel="noopener noreferrer" target="_blank">guiding principle</a> of React Testing Library and in fact says a lot about it. With Enzyme, tests were always uncomfortably implementation-dependent. They were fragile to changes.</p>
<p>With RTL, when you render a component, you have the actual DOM element exposed to you. This makes your test way more predictable and reduces the learning curve (it boils down to good ol' JavaScript).</p>
<p>One can argue that all you can do with RTL is possible to be done with Enzyme. True. But in the end, RTL was designed to <em>enforce good practices</em>. That's why you <code>render</code> and access elements through accessibility-compliant attributes (get via semantic attributes such as text, label and placeholder, instead of using meaningless class selectors).</p>
<p>Another pleasant difference is that tests are smaller, <a href="https://rafaelquintanilha.com/how-to-become-a-bad-developer/#take-pleasure-in-writing-more-code">which is a good thing</a>.</p>
<p>Enough with the prelude, let us take a look at our first scenario.</p>
<h2 id="scenario-1---controlled-component">Scenario 1 - Controlled Component</h2>
<p>Suppose that you need to create a button component that is meant to be shared across your app:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Button</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> props </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{props.onClick}>{props.text}&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Button</span></span></code></pre></figure>
<p>There are two things that you might want to assert:</p>
<ol>
<li>The button is rendered with the correct text;</li>
<li>Whatever function passed as the <code>onClick</code> prop is called after click.</li>
</ol>
<p>Here's how you can write a test to address the first point:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Button </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Button'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#ECEBE8"> defaultProps </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  onClick: </span><span style="color:#EDCC95">jest.fn</span><span style="color:#ECEBE8">(),</span></span>
<span class="line"><span style="color:#ECEBE8">  text: </span><span style="color:#97CCAE">'Submit'</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'button renders with correct text'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { queryByText } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Button</span><span style="color:#ECEBE8"> {</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">defaultProps} />)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">queryByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Submit'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>Notice that <code>render</code> returns functions that allow you to select and manipulate DOM elements. In our case, we are using <a href="https://testing-library.com/docs/dom-testing-library/api-queries#queryby" rel="noopener noreferrer" target="_blank">queryByText</a>, which (surprise!) allows you to query nodes by their text. It will return <code>null</code> if no nodes satisfy the query and throw an error if more than one is found (when you might consider using <a href="https://testing-library.com/docs/dom-testing-library/api-queries#queryallby" rel="noopener noreferrer" target="_blank">queryAllBy</a>).</p>
<p>So our test was able to assert that there is a DOM node whose text is <em>Submit</em>. And if we want to make sure that it works for other prop values too?</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'button renders with correct text'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { queryByText, rerender } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Button</span><span style="color:#ECEBE8"> {</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">defaultProps} />)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">queryByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Submit'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Change props</span></span>
<span class="line"><span style="color:#EDCC95">  rerender</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Button</span><span style="color:#ECEBE8"> {</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">defaultProps} </span><span style="color:#EDCC95">text</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"Go"</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">queryByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Go'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>The <code>rerender</code> function allows you to manually trigger a rerender, this time with a different prop. Our first test is done!</p>
<p>Now let's check how we can guarantee that by clicking on the button we call the <code>onClick</code> prop:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Button </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Button'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, fireEvent, cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span><span style="color:#ECEBE8">;</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'calls correct function on click'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> onClick </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> jest.fn</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByText } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">Button</span><span style="color:#ECEBE8"> {</span><span style="color:#A1C1E4">...</span><span style="color:#ECEBE8">defaultProps} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{onClick} /></span></span>
<span class="line"><span style="color:#ECEBE8">  );</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(defaultProps.text));</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(onClick)</span><span style="color:#EDCC95">.toHaveBeenCalled</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>Here we are creating a simple <a href="https://jestjs.io/docs/en/mock-functions" rel="noopener noreferrer" target="_blank">Jest mock function</a> and passing it as the <code>onClick</code> prop to the <code>Button</code> component. We then use <a href="https://testing-library.com/docs/dom-testing-library/api-queries#getby" rel="noopener noreferrer" target="_blank">getByText</a> to select the button this time (<code>getByText</code> will throw an error if 0 or more than one element matches the query).</p>
<p>With the node selected, we then call <code>fireEvent.click</code>, which is the declarative way of RTL firing events. All we need to do next is to confirm that our mock function was indeed called.</p>
<p>And our first basic scenario is complete. <a href="https://github.com/rafaelquintanilha/react-testing-library-examples/blob/master/src/Button.test.js" rel="noopener noreferrer" target="_blank">The complete test is in GitHub.</a></p>
<h2 id="scenario-2---input-change">Scenario 2 - Input Change</h2>
<p>Another very common use case is an input change that modifies the UI. Consider a text field for the user's name and a greeting that changes with the input:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">function</span><span style="color:#EDCC95"> ChangeInput</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [name, setName] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">''</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">span</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"change-input-greeting"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        Welcome, {name </span><span style="color:#A1C1E4">===</span><span style="color:#97CCAE"> ''</span><span style="color:#A1C1E4"> ?</span><span style="color:#97CCAE"> 'Anonymous User'</span><span style="color:#A1C1E4"> :</span><span style="color:#ECEBE8"> name}!</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">span</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">br</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">input</span></span>
<span class="line"><span style="color:#EDCC95">        type</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"text"</span></span>
<span class="line"><span style="color:#EDCC95">        aria-label</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"user-name"</span></span>
<span class="line"><span style="color:#EDCC95">        placeholder</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"Your name"</span></span>
<span class="line"><span style="color:#EDCC95">        value</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{name}</span></span>
<span class="line"><span style="color:#EDCC95">        onChange</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{e </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setName</span><span style="color:#ECEBE8">(e.target.value)}</span></span>
<span class="line"><span style="color:#ECEBE8">      /></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> ChangeInput</span></span></code></pre></figure>
<p>Notice that we are using React Hooks to manage the state. However, <strong>internal implementations shouldn't matter at all</strong>. Here's how the test would look like:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> ChangeInput </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './ChangeInput'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, fireEvent, cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'displays the correct greeting'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByLabelText, getByTestId } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">ChangeInput</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> input </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'user-name'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> greeting </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'change-input-greeting'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(input.value)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">''</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(greeting.textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Welcome, Anonymous User!'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.change</span><span style="color:#ECEBE8">(input, { target: { value: </span><span style="color:#97CCAE">'Rafael'</span><span style="color:#ECEBE8"> } })</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(input.value)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Rafael'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(greeting.textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Welcome, Rafael!'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>Pretty straightforward, we select the input via the <code>aria-label</code> attribute (a good example of the library enforcing accessibility good practices) and also check that both the greeting and the input have the correct initial value. Then, we call <code>fireEvent.change</code> to trigger a change event, making sure we pass the correct event object with the new input.</p>
<p>Finally, we need to assert that the input has the correct value and the right greeting is being displayed. And there are two of my favorite things with RTL stands:</p>
<ol>
<li>We access values and attributes as we would with regular DOM nodes. So getting an element's text is as easy as accessing <code>textContent</code>.</li>
<li>Nodes are passed as <em>reference</em>, so if you assign them to a variable <em>before</em> a change, you can use the same variable to later check if any of its attributes have changed. This is a huge plus over Enzyme, where I found myself many times dealing with bugs where I assumed a change would be there but I needed to select the element again. Notice how the same <code>greeting</code> variable has different <code>textContent</code> values based on the event triggered.</li>
</ol>
<h2 id="scenario-3---focused-element">Scenario 3 - Focused Element</h2>
<p>Accessible applications need to keep track of the focused element. For example, suppose you want to make sure that after clicking on a button, the focus goes to a given input.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useRef } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> FocusInput</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> inputRef </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useRef</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">null</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">input</span></span>
<span class="line"><span style="color:#EDCC95">        type</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"text"</span></span>
<span class="line"><span style="color:#EDCC95">        aria-label</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"focus-input"</span></span>
<span class="line"><span style="color:#EDCC95">        ref</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{inputRef}</span></span>
<span class="line"><span style="color:#EDCC95">        placeholder</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"Focus me!"</span></span>
<span class="line"><span style="color:#ECEBE8">      /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> inputRef.current.focus</span><span style="color:#ECEBE8">()}>Click to Focus&#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> FocusInput</span></span></code></pre></figure>
<p>The <code>useRef</code> hook stores the input's reference. You can find more about refs in <a href="https://rafaelquintanilha.com/the-complete-guide-to-react-refs/">The Complete Guide to React Refs</a>.</p>
<p>Let's write a test to assert that the input receives focus after click:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> FocusInput </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './FocusInput'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, fireEvent, cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'clicking on button trigger focus on input'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByPlaceholderText, getByText } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">FocusInput</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Click to Focus'</span><span style="color:#ECEBE8">))</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> input </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> getByPlaceholderText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Focus me!'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(input)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(document.activeElement)</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>This time we introduce <code>getByPlaceholderText</code>, which can be handy in some situations (however, <a href="https://www.nngroup.com/articles/form-design-placeholders/" rel="noopener noreferrer" target="_blank">a placeholder is not a substitute for a label</a>.</p>
<p>The experience of testing focused elements is, in my opinion, very superior to Enzyme's. In particular, I love how idiomatic <code>expect(input).toBe(document.activeElement)</code> is.</p>
<h4 id="snapshots">Snapshots</h4>
<p>Let me introduce how you can do snapshot testing with React Testing Library:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'FocusInput matches snapshot'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { container } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">FocusInput</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(container.firstChild)</span><span style="color:#EDCC95">.toMatchSnapshot</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>Notice that <code>render</code> returns a <code>container</code> element. By default, every component is rendered into a <code>div</code>. That's why we access the element via <code>container.firstChild</code>. There are some occasions when you don't want to render into a <code>div</code>, e.g. when your component renders a <code>tr</code> and therefore the container needs to be a <code>table</code> element. You can check the <a href="https://testing-library.com/docs/react-testing-library/api#render-options" rel="noopener noreferrer" target="_blank">render API</a> for more information.</p>
<h2 id="scenario-4---effects">Scenario 4 - Effects</h2>
<p>We have already covered <code>useState</code> and <code>useRef</code>. Next, let us combine them with <code>useEffect</code>. Consider a component where the user can increment a counter and mark a checkbox in order to display the count in the document's title.</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState, useEffect, useRef } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Button </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Button'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">function</span><span style="color:#EDCC95"> Counter</span><span style="color:#ECEBE8">() {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [count, setCount] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [checked, setChecked] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> initialTitleRef </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useRef</span><span style="color:#ECEBE8">(document.title)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">    document.title </span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8"> checked</span></span>
<span class="line"><span style="color:#A1C1E4">      ?</span><span style="color:#97CCAE"> `Total number of clicks: ${</span><span style="color:#97CCAE">count</span><span style="color:#97CCAE">}`</span></span>
<span class="line"><span style="color:#A1C1E4">      :</span><span style="color:#ECEBE8"> initialTitleRef.current</span></span>
<span class="line"><span style="color:#ECEBE8">  }, [checked, count])</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">span</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"count"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        Clicked {count} time{count </span><span style="color:#A1C1E4">===</span><span style="color:#97CCAE"> 1</span><span style="color:#A1C1E4"> ?</span><span style="color:#97CCAE"> ''</span><span style="color:#A1C1E4"> :</span><span style="color:#97CCAE"> 's'</span><span style="color:#ECEBE8">}</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">span</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">br</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">Button</span><span style="color:#EDCC95"> onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setCount</span><span style="color:#ECEBE8">(count </span><span style="color:#A1C1E4">+</span><span style="color:#97CCAE"> 1</span><span style="color:#ECEBE8">)} </span><span style="color:#EDCC95">text</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"Increment"</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">input</span></span>
<span class="line"><span style="color:#EDCC95">          type</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"checkbox"</span></span>
<span class="line"><span style="color:#EDCC95">          id</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"checkbox-title"</span></span>
<span class="line"><span style="color:#EDCC95">          checked</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{checked}</span></span>
<span class="line"><span style="color:#EDCC95">          onChange</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{e </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setChecked</span><span style="color:#ECEBE8">(e.target.checked)}</span></span>
<span class="line"><span style="color:#ECEBE8">        /></span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">label</span><span style="color:#EDCC95"> htmlFor</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"checkbox-title"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          Check to display count in document title</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">label</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Counter</span></span></code></pre></figure>
<p>First, let us make sure that the counter works as expected:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Counter </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Counter'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, fireEvent, cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'count starts with 0'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByTestId } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Counter</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'count'</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Clicked 0 times'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'clicking on button increments counter'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByText, getByTestId } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Counter</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Increment'</span><span style="color:#ECEBE8">))</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'count'</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Clicked 1 time'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Increment'</span><span style="color:#ECEBE8">))</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'count'</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Clicked 2 times'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>Nothing really new so far. Time to test the effect:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'window title changes after every increment if checkbox is checked'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#ECEBE8">  global.window.document.title </span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE"> "My Awesome App"</span><span style="color:#ECEBE8">;</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByText, getByLabelText } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Counter</span><span style="color:#ECEBE8"> />);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // When checkbox is unchecked, incrementing has no effect</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Increment"</span><span style="color:#ECEBE8">));</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(global.window.document.title)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"My Awesome App"</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Check and assert the document title changes</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> checkbox </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> getByLabelText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Check to display count in document title"</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(checkbox);</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(global.window.document.title)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Total number of clicks: 1"</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Works if you increment multiple times</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Increment"</span><span style="color:#ECEBE8">));</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(global.window.document.title)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Total number of clicks: 2"</span><span style="color:#ECEBE8">);</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Unchecking will return to the original document title</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(checkbox);</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(global.window.document.title)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"My Awesome App"</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>The test should be straightforward to follow. Some remarks:</p>
<ul>
<li>We start by defining <code>document.title</code> in the <code>global.window</code> object. Notice that we initialize it once and then the effect is responsible for further changes;</li>
<li>Even though the checkbox has an <code>onChange</code> event handler, we need to fire a <code>click</code> event;</li>
<li>Differently from the <code>aria-label</code> example in Scenario 2, we now use a <code>label</code> element to select the input.</li>
</ul>
<p>This example is heavy on Hooks. If you want to learn more about them, make sure to check <a href="https://rafaelquintanilha.com/how-to-reuse-logic-with-react-hooks">How to Reuse Logic with React Hooks</a>.</p>
<h2 id="scenario-5---settimeout">Scenario 5 - setTimeout</h2>
<p>All of our examples so far were synchronous, meaning that we didn't need to wait for anything before checking the result of an operation. From now on, the examples will include async code. Async code is mostly found in timeouts, intervals and API calls.</p>
<p>Let us start with a simple application that should display a message 5 seconds after a button is clicked:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> useTimeout </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'use-timeout'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> TimeoutMessage</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [message, setMessage] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'This will timeout in 5 seconds'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  useTimeout</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setMessage</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Timeout!'</span><span style="color:#ECEBE8">), </span><span style="color:#97CCAE">5000</span><span style="color:#ECEBE8">)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"timeout-message"</span><span style="color:#ECEBE8">>{message}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> TimeoutMessage</span></span></code></pre></figure>
<p>First thing we will do is confirm that <code>TimeoutMessage</code> has the expected behavior. It initially displays a message that is changed upon timeout:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> TimeoutMessage </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './TimeoutMessage'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">jest.useFakeTimers</span><span style="color:#ECEBE8">()</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'renders with default text'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByTestId } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">TimeoutMessage</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'timeout-message'</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">    'This will timeout in 5 seconds'</span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'text changes after timeout'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByTestId } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">TimeoutMessage</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#EDCC95">  jest.runAllTimers</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'timeout-message'</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Timeout!'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>The key here is to use <a href="https://jestjs.io/docs/en/timer-mocks" rel="noopener noreferrer" target="_blank">Jest timer mocks</a>. We declare <code>jest.useFakeTimers()</code> at the top of the test file and then call <code>jest.runAllTimers()</code> in order to run the timeout.</p>
<p>Now, let us integrate <code>TimeoutMessage</code> into our main <code>Timeout</code> component:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useState } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> TimeoutMessage </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './TimeoutMessage'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Timeout</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [hasClicked, setHasClicked] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useState</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">false</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span><span style="color:#EDCC95"> disabled</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{hasClicked} </span><span style="color:#EDCC95">onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> setHasClicked</span><span style="color:#ECEBE8">(</span><span style="color:#A1C1E4">true</span><span style="color:#ECEBE8">)}></span></span>
<span class="line"><span style="color:#ECEBE8">        Click to trigger timeout</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {hasClicked </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">TimeoutMessage</span><span style="color:#ECEBE8"> />}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Timeout</span></span></code></pre></figure>
<p>For some extra fun, we also want the button to be disabled once the user has clicked. Now, we have two ways to proceed with the test:</p>
<ol>
<li><code>TimeoutMessage</code> returns a div with <code>data-testid="timeout-message"</code>. We can create a test that will check that an element with this <code>data-testid</code> is present in the DOM after click. That would be enough to assure that we are rendering <code>TimeoutMessage</code>, however, we wouldn't have the whole feature (click + timeout message) integrated.</li>
<li>We can assert that the correct messages are being displayed after click and timeout. In the end, that's what matters. Consider also that <code>TimeoutMessage</code> could be more generic, e.g. accepting two props <code>initialMessage</code> and <code>timeoutMessage</code>, and then it would make sense to check that the right text is displayed.</li>
</ol>
<p>Here's the integration test:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Timeout </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Timeout'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, fireEvent, cleanup } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">jest.useFakeTimers</span><span style="color:#ECEBE8">()</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'clicking on button displays timeout message'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByText, queryByTestId, getByTestId } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Timeout</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> button </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Click to trigger timeout'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'timeout-message'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeNull</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(button)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'timeout-message'</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">    'This will timeout in 5 seconds'</span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#EDCC95">  jest.runAllTimers</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'timeout-message'</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Timeout!'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p><code>Timeout</code> has no knowledge of <code>TimeoutMessage</code>, yet we have asserted that the whole app is integrated.</p>
<p>Finally, we need to confirm that the button is disabled after click:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'clicking on button makes it disabled'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByText } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Timeout</span><span style="color:#ECEBE8"> />);</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> button </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Click to trigger timeout"</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(button.disabled)</span><span style="color:#EDCC95">.toBeFalsy</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(button);</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(button.disabled)</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">();</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>Again, as <code>button</code> is a regular DOM element, we can access its <code>disabled</code> attribute just fine. Pretty neat!</p>
<h2 id="scenario-6---fetch">Scenario 6 - Fetch</h2>
<p>A very common use case is to assert changes in the UI after data is fetched from an API. This is what we are going to do now. Our next application will fetch a Chuck Norris joke after click and display it to the user. Here's the <code>Fetch</code> component:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> useAPI </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './useAPI'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> Fetch</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [response, callAPI] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useAPI</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span></span>
<span class="line"><span style="color:#EDCC95">        onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> callAPI</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'https://api.chucknorris.io/jokes/random'</span><span style="color:#ECEBE8">)}</span></span>
<span class="line"><span style="color:#ECEBE8">      ></span></span>
<span class="line"><span style="color:#ECEBE8">        Get a Chuck Norris joke</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {response.loading </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"fetch-loading"</span><span style="color:#ECEBE8">>Loading...&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">      {response.error </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"fetch-error"</span><span style="color:#ECEBE8">>{response.error}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">>}</span></span>
<span class="line"><span style="color:#ECEBE8">      {response.success </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"fetch-joke"</span><span style="color:#ECEBE8">>{response.data.value}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      )}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> Fetch</span></span></code></pre></figure>
<p>I've used a custom hook called <code>useAPI</code> that returns the response from the server and a function to invoke the API. The implementation of <code>useAPI</code> is out of the scope of this article, but you shouldn't have any trouble to <a href="https://github.com/rafaelquintanilha/react-testing-library-examples/blob/master/src/useAPI.js" rel="noopener noreferrer" target="_blank">follow along with the source code</a>.</p>
<p>Let's get to the tests. First thing we want to do is assert that no jokes are displayed when the component renders:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> Fetch </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './Fetch'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, fireEvent, cleanup, wait } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'starts without any joke'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { queryByTestId } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Fetch</span><span style="color:#ECEBE8"> />)</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">queryByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'fetch-joke'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeNull</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>Recall that we use <code>queyByTestId</code> when we want to assert that an element is <em>not</em> present (<code>getByTestId</code> would throw an error).</p>
<p>Next, let's write a test to confirm a loading message is displayed after click:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">...</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'after clicking on button, displays loading message'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> { getByTestId, getByText } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(&#x3C;</span><span style="color:#A1C1E4">Fetch</span><span style="color:#ECEBE8"> />);</span></span>
<span class="line"><span style="color:#EDCC95">  fireEvent.click</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Get a Chuck Norris joke"</span><span style="color:#ECEBE8">));</span></span>
<span class="line"><span style="color:#EDCC95">  expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"fetch-loading"</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">"Loading..."</span><span style="color:#ECEBE8">);</span></span>
<span class="line"><span style="color:#ECEBE8">});</span></span></code></pre></figure>
<p>So far so good. But how do we assert the async response?</p>
<p>The answer is the <a href="https://testing-library.com/docs/dom-testing-library/api-async#wait" rel="noopener noreferrer" target="_blank">wait</a> function that comes with RTL. <code>wait</code> allows you to halt the test until the relevant element is visible in the DOM:</p>
<figure class="code"><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="plaintext"><code><span class="line"><span>...</span></span>
<span class="line"><span></span></span>
<span class="line"><span>test('after clicking on button, displays joke if API succeeds', async () => {</span></span>
<span class="line"><span>  const joke = "Chuck Norris counted to infinity. Twice.";</span></span>
<span class="line"><span></span></span>
<span class="line"><span>  // Mock API</span></span>
<span class="line"><span>  jest.spyOn(global, 'fetch')</span></span>
<span class="line"><span>    .mockImplementation(() => Promise.resolve({</span></span>
<span class="line"><span>      status: 200,</span></span>
<span class="line"><span>      json: () => Promise.resolve({</span></span>
<span class="line"><span>        value: joke</span></span>
<span class="line"><span>      })</span></span>
<span class="line"><span>    }));</span></span>
<span class="line"><span></span></span>
<span class="line"><span>  const { getByTestId, getByText } = render(&#x3C;Fetch />);</span></span>
<span class="line"><span>  fireEvent.click(getByText("Get a Chuck Norris joke"));</span></span>
<span class="line"><span>  await wait(() => getByTestId("fetch-joke"));</span></span>
<span class="line"><span></span></span>
<span class="line"><span>  expect(getByTestId("fetch-joke").textContent).toBe(joke);</span></span>
<span class="line"><span>  expect(global.fetch).toHaveBeenCalledTimes(1);</span></span>
<span class="line"><span>  expect(global.fetch.mock.calls[0][0]).toBe("https://api.chucknorris.io/jokes/random");</span></span>
<span class="line"><span></span></span>
<span class="line"><span>  // Clear mock</span></span>
<span class="line"><span>  global.fetch.mockClear();</span></span>
<span class="line"><span>});</span></span></code></pre></figure>
<ol>
<li><a href="https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname" rel="noopener noreferrer" target="_blank">jest.spyOn</a> mocks the global <code>fetch</code> function. I strongly recommend that you read the docs to get a better sense of how the spy works.</li>
<li><a href="https://jestjs.io/docs/en/mock-function-api.html#mockfnmockimplementationfn" rel="noopener noreferrer" target="_blank">mockImplementation</a> defines which function the spy will invoke. Once <code>fetch</code> returns a Promise that later will be converted to <code>json</code>, we mock the two functions. Also notice that the <code>status</code> is 200 so our <code>useAPI</code> hook doesn't throw an error.</li>
<li><code>await wait(() => getByTestId("fetch-joke"))</code> basically waits for the element with <code>data-testid="fetch-joke"</code> to become visible in the DOM. This is our async mark.</li>
<li>Now that we have waited for the Promises to resolve and the DOM element to become visible, the next step is as simple as checking that the joke is where it was supposed to be.</li>
<li>Lastly, we assert that we indeed called the right API. <code>mock.calls</code> return an array of calls, each of them composed of an array of args. So <code>mock.calls[0][0]</code> is the first arg of the first call, <code>mock.calls[0][1]</code> is the second arg of the first call and so on.</li>
</ol>
<p>As of now we are able to test the majority of the use cases you will find when developing React applications. But there is one last scenario that I would like to mention.</p>
<h2 id="scenario-7---multiple-api-calls">Scenario 7 - Multiple API calls</h2>
<p>What if you trigger a <em>second</em> API call as a result of the first API call? This is what we are going to see now.</p>
<p>Consider an application that fetches a blog post and, once the post is retrieved, fetches all comments related to the post:</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React, { useEffect } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> useAPI </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './useAPI'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">const</span><span style="color:#EDCC95"> MultipleFetches</span><span style="color:#A1C1E4"> =</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [postResponse, callPostAPI] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useAPI</span><span style="color:#ECEBE8">()</span></span>
<span class="line"><span style="color:#A1C1E4">  const</span><span style="color:#ECEBE8"> [commentsResponse, callCommentsAPI] </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> useAPI</span><span style="color:#ECEBE8">()</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  useEffect</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A1C1E4">    if</span><span style="color:#ECEBE8"> (postResponse.success) {</span></span>
<span class="line"><span style="color:#EDCC95">      callCommentsAPI</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'https://jsonplaceholder.typicode.com/posts/1/comments'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">    }</span></span>
<span class="line"><span style="color:#ECEBE8">  }, [postResponse.success, callCommentsAPI])</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">  return</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">button</span></span>
<span class="line"><span style="color:#EDCC95">        onClick</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{() </span><span style="color:#A1C1E4">=></span></span>
<span class="line"><span style="color:#EDCC95">          callPostAPI</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'https://jsonplaceholder.typicode.com/posts/1'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">        }</span></span>
<span class="line"><span style="color:#ECEBE8">      ></span></span>
<span class="line"><span style="color:#ECEBE8">        Fetch post and comments</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">button</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        {postResponse.loading </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"fetch-loading-post"</span><span style="color:#ECEBE8">>Loading post...&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        )}</span></span>
<span class="line"><span style="color:#ECEBE8">        {postResponse.error </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"fetch-error-post"</span><span style="color:#ECEBE8">>{postResponse.error}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        )}</span></span>
<span class="line"><span style="color:#ECEBE8">        {postResponse.success </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">          &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"fetch-post"</span><span style="color:#ECEBE8">>{postResponse.data.title}&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">        )}</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      {</span><span style="color:#A1C1E4">!</span><span style="color:#ECEBE8">postResponse.loading </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          {commentsResponse.loading </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"fetch-loading-comments"</span><span style="color:#ECEBE8">>Loading comments...&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          )}</span></span>
<span class="line"><span style="color:#ECEBE8">          {commentsResponse.error </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"fetch-error-comments"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">              {commentsResponse.error}</span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          )}</span></span>
<span class="line"><span style="color:#ECEBE8">          {commentsResponse.success </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">              {</span><span style="color:#EDCC95">commentsResponse.data.slice</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">, </span><span style="color:#97CCAE">10</span><span style="color:#ECEBE8">)</span><span style="color:#EDCC95">.map</span><span style="color:#ECEBE8">(comment </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">                &#x3C;</span><span style="color:#A1C1E4">li</span><span style="color:#EDCC95"> key</span><span style="color:#A1C1E4">=</span><span style="color:#ECEBE8">{comment.id} </span><span style="color:#EDCC95">data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"comment-author"</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">                  {comment.name}</span></span>
<span class="line"><span style="color:#ECEBE8">                &#x3C;/</span><span style="color:#A1C1E4">li</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">              ))}</span></span>
<span class="line"><span style="color:#ECEBE8">            &#x3C;/</span><span style="color:#A1C1E4">ul</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">          )}</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      )}</span></span>
<span class="line"><span style="color:#ECEBE8">      {postResponse.success </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> commentsResponse.success </span><span style="color:#A1C1E4">&#x26;&#x26;</span><span style="color:#ECEBE8"> (</span></span>
<span class="line"><span style="color:#ECEBE8">        &#x3C;</span><span style="color:#A1C1E4">div</span><span style="color:#EDCC95"> data-testid</span><span style="color:#A1C1E4">=</span><span style="color:#97CCAE">"multiple-fetch-success"</span><span style="color:#ECEBE8">>All fetched!&#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">      )}</span></span>
<span class="line"><span style="color:#ECEBE8">    &#x3C;/</span><span style="color:#A1C1E4">div</span><span style="color:#ECEBE8">></span></span>
<span class="line"><span style="color:#ECEBE8">  )</span></span>
<span class="line"><span style="color:#ECEBE8">}</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">export</span><span style="color:#A1C1E4"> default</span><span style="color:#ECEBE8"> MultipleFetches</span></span></code></pre></figure>
<p>We now use a combination of <a href="https://github.com/rafaelquintanilha/react-testing-library-examples/blob/master/src/useAPI.js" rel="noopener noreferrer" target="_blank">useAPI</a> and <code>useEffect</code>. Once the first call succeeds, the second API is called. What's the difference from the single fetch example?</p>
<figure class="code"><figcaption>jsx</figcaption><pre class="astro-code linha" style="background-color:#1b1814;color:#ecebe8; overflow-x: auto;" tabindex="0" data-language="jsx"><code><span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> React </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> 'react'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> MultipleFetches </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> './MultipleFetches'</span></span>
<span class="line"><span style="color:#A1C1E4">import</span><span style="color:#ECEBE8"> { render, fireEvent, cleanup, wait } </span><span style="color:#A1C1E4">from</span><span style="color:#97CCAE"> '@testing-library/react'</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">afterEach</span><span style="color:#ECEBE8">(cleanup)</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">describe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'API tests'</span><span style="color:#ECEBE8">, () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">  // Group API tests so we can clear the mock more easily</span></span>
<span class="line"><span style="color:#EDCC95">  afterEach</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span><span style="color:#EDCC95"> global.fetch.mockClear</span><span style="color:#ECEBE8">())</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">  test</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'displays post if API succeeds'</span><span style="color:#ECEBE8">, </span><span style="color:#A1C1E4">async</span><span style="color:#ECEBE8"> () </span><span style="color:#A1C1E4">=></span><span style="color:#ECEBE8"> {</span></span>
<span class="line"><span style="color:#A7A49E;font-style:italic">    // Mock API</span></span>
<span class="line"><span style="color:#ECEBE8">    jest</span></span>
<span class="line"><span style="color:#EDCC95">      .spyOn</span><span style="color:#ECEBE8">(global, </span><span style="color:#97CCAE">'fetch'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">      .mockImplementationOnce</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span></span>
<span class="line"><span style="color:#EDCC95">        Promise.resolve</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">          status: </span><span style="color:#97CCAE">200</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#EDCC95">          json</span><span style="color:#ECEBE8">: () </span><span style="color:#A1C1E4">=></span></span>
<span class="line"><span style="color:#EDCC95">            Promise.resolve</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">              title: </span><span style="color:#97CCAE">'How to Become a Bad Developer'</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#ECEBE8">            }),</span></span>
<span class="line"><span style="color:#ECEBE8">        })</span></span>
<span class="line"><span style="color:#ECEBE8">      )</span></span>
<span class="line"><span style="color:#EDCC95">      .mockImplementationOnce</span><span style="color:#ECEBE8">(() </span><span style="color:#A1C1E4">=></span></span>
<span class="line"><span style="color:#EDCC95">        Promise.resolve</span><span style="color:#ECEBE8">({</span></span>
<span class="line"><span style="color:#ECEBE8">          status: </span><span style="color:#97CCAE">200</span><span style="color:#ECEBE8">,</span></span>
<span class="line"><span style="color:#EDCC95">          json</span><span style="color:#ECEBE8">: () </span><span style="color:#A1C1E4">=></span></span>
<span class="line"><span style="color:#EDCC95">            Promise.resolve</span><span style="color:#ECEBE8">([</span></span>
<span class="line"><span style="color:#ECEBE8">              { id: </span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">, name: </span><span style="color:#97CCAE">'Rafael'</span><span style="color:#ECEBE8"> },</span></span>
<span class="line"><span style="color:#ECEBE8">              { id: </span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">, name: </span><span style="color:#97CCAE">'Andressa'</span><span style="color:#ECEBE8"> },</span></span>
<span class="line"><span style="color:#ECEBE8">            ]),</span></span>
<span class="line"><span style="color:#ECEBE8">        })</span></span>
<span class="line"><span style="color:#ECEBE8">      )</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> { getByTestId, getByText, getAllByTestId } </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> render</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#ECEBE8">      &#x3C;</span><span style="color:#A1C1E4">MultipleFetches</span><span style="color:#ECEBE8"> /></span></span>
<span class="line"><span style="color:#ECEBE8">    )</span></span>
<span class="line"><span style="color:#EDCC95">    fireEvent.click</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Fetch post and comments'</span><span style="color:#ECEBE8">))</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    await</span><span style="color:#EDCC95"> wait</span><span style="color:#ECEBE8">()</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">    expect</span><span style="color:#ECEBE8">(global.fetch)</span><span style="color:#EDCC95">.toHaveBeenCalledTimes</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">2</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">    expect</span><span style="color:#ECEBE8">(global.fetch.mock.calls[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">])</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">      'https://jsonplaceholder.typicode.com/posts/1'</span></span>
<span class="line"><span style="color:#ECEBE8">    )</span></span>
<span class="line"><span style="color:#EDCC95">    expect</span><span style="color:#ECEBE8">(global.fetch.mock.calls[</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">][</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">])</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">      'https://jsonplaceholder.typicode.com/posts/1/comments'</span></span>
<span class="line"><span style="color:#ECEBE8">    )</span></span>
<span class="line"></span>
<span class="line"><span style="color:#EDCC95">    expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'fetch-post'</span><span style="color:#ECEBE8">).textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span></span>
<span class="line"><span style="color:#97CCAE">      'How to Become a Bad Developer'</span></span>
<span class="line"><span style="color:#ECEBE8">    )</span></span>
<span class="line"><span style="color:#EDCC95">    expect</span><span style="color:#ECEBE8">(</span><span style="color:#EDCC95">getByText</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'All fetched!'</span><span style="color:#ECEBE8">))</span><span style="color:#EDCC95">.toBeTruthy</span><span style="color:#ECEBE8">()</span></span>
<span class="line"></span>
<span class="line"><span style="color:#A1C1E4">    const</span><span style="color:#ECEBE8"> authors </span><span style="color:#A1C1E4">=</span><span style="color:#EDCC95"> getAllByTestId</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'comment-author'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">    expect</span><span style="color:#ECEBE8">(authors[</span><span style="color:#97CCAE">0</span><span style="color:#ECEBE8">].textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Rafael'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#EDCC95">    expect</span><span style="color:#ECEBE8">(authors[</span><span style="color:#97CCAE">1</span><span style="color:#ECEBE8">].textContent)</span><span style="color:#EDCC95">.toBe</span><span style="color:#ECEBE8">(</span><span style="color:#97CCAE">'Andressa'</span><span style="color:#ECEBE8">)</span></span>
<span class="line"><span style="color:#ECEBE8">  })</span></span>
<span class="line"><span style="color:#ECEBE8">})</span></span></code></pre></figure>
<p>First, we are now using <a href="https://jestjs.io/docs/en/mock-function-api.html#mockfnmockimplementationoncefn" rel="noopener noreferrer" target="_blank">jest.mockImplementationOnce</a> as we need more control over the fetches (each call should have a different response).</p>
<p>Plus, we use <code>await wait()</code>, with no function as argument. The result of doing that is waiting for the next <em>tick</em> in <a href="https://nodejs.org/fa/docs/guides/event-loop-timers-and-nexttick/" rel="noopener noreferrer" target="_blank">Node event loop</a>. Without going into many details, what it does is to wait until the next async operation is performed.</p>
<p>Once we have awaited the resolution of both calls, the next is easy: just assert that every call was called with the correct API and that the data is being displayed in the DOM.</p>
<p>The full test file including the failure scenarios is <a href="https://github.com/rafaelquintanilha/react-testing-library-examples/blob/master/src/MultipleFetches.test.js" rel="noopener noreferrer" target="_blank">available in GitHub</a>.</p>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>I hope this article helps you when creating tests with Jest and React Testing Library. Don't forget that you can consult <a href="https://react-testing-library-examples.netlify.app" rel="noopener noreferrer" target="_blank">React Testing Library Examples</a> as a shorter reference when convenient.</p>]]></content:encoded>
</item>
</channel>
</rss>
