<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jagoda Bieniek</title>
    <description>The latest articles on DEV Community by Jagoda Bieniek (@jagodabieniek).</description>
    <link>https://dev.to/jagodabieniek</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1249526%2Fe91ed2ee-da6c-4e8c-8960-19d8875299ca.jpg</url>
      <title>DEV Community: Jagoda Bieniek</title>
      <link>https://dev.to/jagodabieniek</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jagodabieniek"/>
    <language>en</language>
    <item>
      <title>How to Test stopPropagation() in React Testing Library</title>
      <dc:creator>Jagoda Bieniek</dc:creator>
      <pubDate>Wed, 29 Jan 2025 12:21:21 +0000</pubDate>
      <link>https://dev.to/jagodabieniek/how-to-test-stoppropagation-in-react-testing-library-1npc</link>
      <guid>https://dev.to/jagodabieniek/how-to-test-stoppropagation-in-react-testing-library-1npc</guid>
      <description>&lt;h3&gt;
  
  
  🚀 Introduction
&lt;/h3&gt;

&lt;p&gt;Ensuring &lt;code&gt;stopPropagation()&lt;/code&gt; works correctly in React applications is crucial when handling nested click events. Instead of checking if stopPropagation() was explicitly called, the best approach is to test its effect—whether the event propagates or not.&lt;/p&gt;

&lt;p&gt;This article explores:&lt;/p&gt;

&lt;p&gt;✅ The best approach to testing &lt;code&gt;stopPropagation()&lt;/code&gt; (checking event propagation).&lt;/p&gt;

&lt;p&gt;✅  An alternative method using event mocking.&lt;/p&gt;

&lt;p&gt;✅  Which method is better and when to use each approach.&lt;/p&gt;

&lt;h3&gt;
  
  
  🛠 Best Approach: Testing the Effect of &lt;code&gt;stopPropagation()&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;The recommended way to test &lt;code&gt;stopPropagation()&lt;/code&gt; is to wrap the tested component inside a parent &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; with an &lt;code&gt;onClick&lt;/code&gt; handler and check whether the event reaches the parent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Testing Propagation Prevention&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { FormElementsList } from "@/components/FormElementsList";

it("stops propagation when an element is clicked", async () =&amp;gt; {
  const onOuterClick = jest.fn();

  render(
    &amp;lt;div onClick={onOuterClick}&amp;gt;
      &amp;lt;FormElementsList elementsList={[{ name: "Text Input", type: "text", icon: &amp;lt;span&amp;gt;📝&amp;lt;/span&amp;gt; }]} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );

  const textInputElement = screen.getByText("Text Input");
  await userEvent.click(textInputElement);

  expect(onOuterClick).toHaveBeenCalledTimes(0); // Ensures event does not propagate
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Why This Works ?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The parent &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt; has an &lt;code&gt;onClick&lt;/code&gt; handler (onOuterClick). &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;stopPropagation()&lt;/code&gt; is correctly applied inside &lt;code&gt;FormElementsList&lt;/code&gt;, clicking on an element should not trigger onOuterClick. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The assertion &lt;code&gt;expect(onOuterClick).toHaveBeenCalledTimes(0)&lt;/code&gt; ensures the event was stopped successfully.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  🛠 Alternative: Mocking &lt;code&gt;stopPropagation()&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;If you need to directly verify that stopPropagation() was called, you can mock the event and track the function call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Mocking stopPropagation()&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { render, screen } from "@testing-library/react";
import { FormElementsList } from "@/components/FormElementsList";

it("calls stopPropagation when an element is clicked", async () =&amp;gt; {
  render(&amp;lt;FormElementsList elementsList={[{ name: "Text Input", type: "text", icon: &amp;lt;span&amp;gt;📝&amp;lt;/span&amp;gt; }]} /&amp;gt;);

  const textInputElement = screen.getByText("Text Input");

  const event = new MouseEvent("click", { bubbles: true });
  jest.spyOn(event, "stopPropagation");

  textInputElement.dispatchEvent(event);

  expect(event.stopPropagation).toHaveBeenCalled();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Why This Works ?&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;jest.spyOn(event, "stopPropagation")&lt;/code&gt; tracks whether the function is called.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;dispatchEvent(event)&lt;/code&gt; manually triggers the click event.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;expect(event.stopPropagation).toHaveBeenCalled()&lt;/code&gt; ensures stopPropagation() was executed.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  🛠 Which Method Should You Use?
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Method&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;✅ Pros&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;❌ Cons&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;1. Testing Effect (Wrapper &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt;)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Tests real user behavior&lt;/td&gt;
&lt;td&gt;Doesn’t confirm &lt;code&gt;stopPropagation()&lt;/code&gt; was explicitly called&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;2. Mocking &lt;code&gt;stopPropagation()&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Confirms &lt;code&gt;stopPropagation()&lt;/code&gt; is called&lt;/td&gt;
&lt;td&gt;Tests implementation rather than behavior&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  🚀 &lt;strong&gt;Recommended Approach&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Prioritize testing real behavior over implementation details for better maintainability!&lt;/p&gt;

&lt;p&gt;💬 Have you used different methods for testing event propagation? Share your thoughts in the comments!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>testing</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Getting Started with Redux in React Testing Library: A Guide to Custom Render Functions.</title>
      <dc:creator>Jagoda Bieniek</dc:creator>
      <pubDate>Mon, 04 Mar 2024 14:36:36 +0000</pubDate>
      <link>https://dev.to/jagodabieniek/using-redux-with-react-testing-library-15nc</link>
      <guid>https://dev.to/jagodabieniek/using-redux-with-react-testing-library-15nc</guid>
      <description>&lt;h4&gt;
  
  
  Introduction
&lt;/h4&gt;

&lt;p&gt;Often in our projects we need to manage the state. For this purpose, we can use Redux however in 2024 there is a Redux toolkit , which simplifies the use of Redux itself.  In this tutorial, I want to focus on how to start testing an application that uses the Redux toolkit.&lt;/p&gt;

&lt;h4&gt;
  
  
  Custom render function.
&lt;/h4&gt;

&lt;p&gt;In testing React components, It is often used external libraries, not only &lt;em&gt;redux-toolkit&lt;/em&gt;, but also &lt;em&gt;react-router-dom&lt;/em&gt; or &lt;em&gt;styled-components&lt;/em&gt; . In these cases, it is usefull to create custom render function.&lt;/p&gt;

&lt;p&gt;Let's take as example boardSlice.ts (example from my project): &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2cxay9zz6m5hn2t5g1fr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2cxay9zz6m5hn2t5g1fr.png" alt="Image description" width="591" height="703"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Import the necessary modules and components from React, Redux Toolkit, React Testing Library, and your application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { ReactElement, ReactNode } from 'react';
import { render, RenderOptions } from '@testing-library/react';
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
import { boardSlice } from './store/slices';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Define the CustomRenderOptions interface witch extends the &lt;code&gt;RenderOptions&lt;/code&gt; from &lt;code&gt;@testing-library/react&lt;/code&gt;, excluding the &lt;code&gt;wrapper&lt;/code&gt; property. It adds optional &lt;code&gt;preloadedState&lt;/code&gt; and &lt;code&gt;store&lt;/code&gt; properties. This allows you to pass an initial state for the Redux store or a custom store when calling &lt;code&gt;customRender&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface CustomRenderOptions extends Omit&amp;lt;RenderOptions, 'wrapper'&amp;gt; {
  preloadedState?: Record&amp;lt;string, unknown&amp;gt;;
  store?: ReturnType&amp;lt;typeof configureStore&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create the customRender function  takes a React element and an options object as arguments. The options object defaults to an empty object if not provided. &lt;br&gt;
Create the Redux store: If a store is not provided in the options, a new store is created using the &lt;code&gt;configureStore&lt;/code&gt; function from Redux Toolkit. The store uses the &lt;code&gt;boardSlice.reducer&lt;/code&gt; as its reducer and the &lt;code&gt;preloadedState&lt;/code&gt; as its initial state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const customRender = (
  ui: ReactElement,
  {
    preloadedState = {},
    store = configureStore({
      reducer: { board: boardSlice.reducer },
      preloadedState,
    }),
    ...options
  }: CustomRenderOptions = {}
) =&amp;gt; {
  // ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create the Wrapper component, wraps its children in a Redux &lt;code&gt;Provider&lt;/code&gt;. The &lt;code&gt;Provider&lt;/code&gt; makes the Redux store available to the components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Wrapper = ({ children }: { children: ReactNode }) =&amp;gt; (
  &amp;lt;Provider store={store}&amp;gt;{children}&amp;lt;/Provider&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Call the render function finally, the function calls the &lt;code&gt;render&lt;/code&gt; function from React Testing Library, passing the &lt;code&gt;ui&lt;/code&gt; and the &lt;code&gt;Wrapper&lt;/code&gt; as the &lt;code&gt;wrapper&lt;/code&gt; option.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return render(ui, { wrapper: Wrapper, ...options });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Export the &lt;code&gt;customRender&lt;/code&gt; function,  then exported as &lt;code&gt;render&lt;/code&gt;, so it can be used in place of the &lt;code&gt;render&lt;/code&gt; function from &lt;code&gt;@testing-library/react&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export { customRender as render };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally we receive :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { ReactElement, ReactNode } from 'react';
import { render, RenderOptions } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { configureStore } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';
import { boardSlice } from './store/slices';
interface CustomRenderOptions extends Omit&amp;lt;RenderOptions, 'wrapper'&amp;gt; {
  preloadedState?: Record&amp;lt;string, unknown&amp;gt;;
  store?: ReturnType&amp;lt;typeof configureStore&amp;gt;;
}

const customRender = (
  ui: ReactElement,
  {
    preloadedState = {},
    store = configureStore({
      reducer: { board: boardSlice.reducer },
      preloadedState,
    }),
    ...options
  }: CustomRenderOptions = {}
) =&amp;gt; {
  const Wrapper = ({ children }: { children: ReactNode }) =&amp;gt; (
   // Here you can other providers
    &amp;lt;Provider store={store}&amp;gt;
      {children}
    &amp;lt;/Provider&amp;gt;
  );

  return render(ui, { wrapper: Wrapper, ...options });
};

export * from '@testing-library/react';
export { customRender as render };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Sumarry
&lt;/h4&gt;

&lt;p&gt;In this tutorial, we've explored how to create a custom render function for testing React components that interact with a Redux store, using Redux Toolkit. This custom render function simplifies the testing process by automatically wrapping the component under test in the necessary context providers, such as Redux's &lt;code&gt;Provider&lt;/code&gt; and React Router's &lt;code&gt;MemoryRouter&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We started by importing the necessary modules and defining a &lt;code&gt;CustomRenderOptions&lt;/code&gt; interface to extend the &lt;code&gt;RenderOptions&lt;/code&gt; from &lt;code&gt;@testing-library/react&lt;/code&gt;. This interface allows us to optionally pass an initial state or a custom store to the &lt;code&gt;customRender&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Next, we created the &lt;code&gt;customRender&lt;/code&gt; function, which takes a React element and an options object as arguments. Inside this function, we created a Redux store (if not provided in the options) and a &lt;code&gt;Wrapper&lt;/code&gt; component that wraps its children in a Redux &lt;code&gt;Provider&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Finally, we called the &lt;code&gt;render&lt;/code&gt; function from &lt;code&gt;@testing-library/react&lt;/code&gt;, passing the &lt;code&gt;ui&lt;/code&gt; and the &lt;code&gt;Wrapper&lt;/code&gt; as the &lt;code&gt;wrapper&lt;/code&gt; option, and exported the &lt;code&gt;customRender&lt;/code&gt; function as &lt;code&gt;render&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This custom render function is a powerful tool that can simplify your test setup, reduce repetition in your tests, and make your tests more robust and flexible when working with libraries like Redux Toolkit.&lt;br&gt;
 With this configuration, your application is now equipped to handle Redux Toolkit in unit tests. In subsequent sections, we will delve into the specifics of what to test and how to conduct these tests within the Redux Toolkit context.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>testdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>Getting Started with React Testing Library: Writing Your First Test.</title>
      <dc:creator>Jagoda Bieniek</dc:creator>
      <pubDate>Fri, 23 Feb 2024 16:49:49 +0000</pubDate>
      <link>https://dev.to/jagodabieniek/react-testing-library-322i</link>
      <guid>https://dev.to/jagodabieniek/react-testing-library-322i</guid>
      <description>&lt;p&gt;The difference between Jest and the React Testing Library is important to understand when writing unit tests for React components.&lt;/p&gt;

&lt;h4&gt;
  
  
  Jest:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Jest is a JavaScript testing framework.&lt;/li&gt;
&lt;li&gt;It serves as a test runner, assertion library, and mock/stub/spy library.&lt;/li&gt;
&lt;li&gt;Jest provides a testing environment where you can write and execute your test cases.&lt;/li&gt;
&lt;li&gt;It provides features such as test suites, test cases, mocking functions, code coverage analysis and more.&lt;/li&gt;
&lt;li&gt;Jest is highly optimised for performance and parallelization, making it a popular choice for testing JavaScript applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  React Testing Library:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;It's a utility library for testing React components.&lt;/li&gt;
&lt;li&gt;It provides tools for interacting with React components in tests, simulating user behaviour, and asserting on rendered output.&lt;/li&gt;
&lt;li&gt;It encourages testing components in a way that resembles how they will be used by end users.&lt;/li&gt;
&lt;li&gt;It encourages writing tests that focus on behaviour rather than implementation details, resulting in more robust and maintainable tests.&lt;/li&gt;
&lt;li&gt;The React Testing Library works on top of testing frameworks such as Jest, making it easy to integrate with existing Jest test suites.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Test's Anatomy.
&lt;/h4&gt;

&lt;p&gt;Overall, the test facility is fundamental to writing tests in Jest. It allows you to organise your test cases, specify the behaviour you want to test, and define the expected results.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;test(name, fn, timeout)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;where: &lt;br&gt;
&lt;code&gt;name&lt;/code&gt; is a descriptive string that clearly indicates what aspect of the code is being tested. &lt;br&gt;
&lt;code&gt;fn&lt;/code&gt; is the function containing the actual test code.&lt;br&gt;
&lt;code&gt;timeout&lt;/code&gt; is the maximum amount of time (in milliseconds) that Jest will allow the test case to run before considering it a failure. The default timeout is 5000 milliseconds (5 seconds), but you can change it to suit your tests.&lt;/p&gt;

&lt;p&gt;RTL unit tests consist of 3 stages: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;render the component&lt;/li&gt;
&lt;li&gt;find the element rendered by the component&lt;/li&gt;
&lt;li&gt;assert against the element found in step 2, which passes or fails the test.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
  
  
  RTL Queries.
&lt;/h4&gt;

&lt;p&gt;So how can we find element? &lt;/p&gt;

&lt;p&gt;RTL provides a variety of query methods to find elements on the page when writing tests. Here's a breakdown of the three types of queries you mentioned:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;getBy &amp;amp; getAllBy&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;getBy&lt;/code&gt;&lt;/strong&gt; is used to find a single element that matches the specified criteria. If no matching element is found, it throws an error.&lt;br&gt;
&lt;strong&gt;&lt;code&gt;getAllBy&lt;/code&gt;&lt;/strong&gt; is used to find multiple elements that match the specified criteria. If no matching elements are found, it throws an error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;queryBy &amp;amp; queryAllBy&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;queryBy&lt;/code&gt;&lt;/strong&gt; is similar to getBy, but it returns null if no matching element is found instead of throwing an error.&lt;br&gt;
&lt;strong&gt;&lt;code&gt;queryAllBy&lt;/code&gt;&lt;/strong&gt; is similar to getAllBy, but it returns an empty array if no matching elements are found instead of throwing an error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;findBy &amp;amp; findAllBy&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;findBy&lt;/code&gt;&lt;/strong&gt; is used to find a single element asynchronously. It waits for the specified element to appear in the DOM within a certain timeout period. It returns a Promise that resolves when the element is found or rejects if the element is not found within the timeout.&lt;br&gt;
&lt;strong&gt;&lt;code&gt;findAllBy&lt;/code&gt;&lt;/strong&gt; is similar to findBy, but it finds multiple elements asynchronously. Like findBy, it returns a Promise that resolves to an array of elements when they are found or rejects if no elements are found within the timeout.&lt;/p&gt;
&lt;h4&gt;
  
  
  How to start writing unit tests?
&lt;/h4&gt;

&lt;p&gt;If setup Jest/ React Testing Library is already done &lt;br&gt;
if not please read my article &lt;a href="https://dev.to/jagodabieniek/testing-react-components-with-jest-and-react-testing-library-e6i"&gt;Getting start with React Testing Library&lt;/a&gt; we can move on to writing our first unit test.&lt;/p&gt;

&lt;p&gt;Let's see what to test. In our case it will be simple component: &lt;/p&gt;

&lt;p&gt;&lt;em&gt;HomeView.tsx&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const HomeView = () =&amp;gt; &amp;lt;h1&amp;gt;Hello home view&amp;lt;/h1&amp;gt;;
export default HomeView;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our example component displays the string 'Hello home view', so the test case should check whether the string 'Hello home view' is displayed correctly. &lt;/p&gt;

&lt;p&gt;Create a test file. There are actually 3 ways to do this: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;inside component folder =&amp;gt; ./HomeView/HomeView.test.tsx&lt;/li&gt;
&lt;li&gt;inside component folder =&amp;gt; ./HomeView/HomeView.spec.tsx&lt;/li&gt;
&lt;li&gt;inside create src/&lt;em&gt;tests&lt;/em&gt; ./HomeView.test.tsx &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It is recommended that you always place your tests next to the code they test, so that relative imports are shorter. &lt;/p&gt;

&lt;p&gt;In this tutorial I have chosen the first option.  &lt;/p&gt;

&lt;p&gt;Inside HomeView.test.tsx. Let's import the necessary dependencies&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { render } from '@testing-library/react';
import HomeView from './HomeView';

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we first import the &lt;em&gt;render&lt;/em&gt; function, which allows us to render React components in a test environment, and the function takes a JSX element . Then we can use the utilities mentioned above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { render } from '@testing-library/react';
import HomeView from './HomeView';


 test('HomeView renders the heading with correct text', ()=&amp;gt;{
   // render compoment 
   render(&amp;lt;HomeView/&amp;gt;); 
   // heading element 
   const headingElement = 
     screen.getByRole('heading', { level: 1}); 
   // assertion 
   expect(headingElement).toBeInTheDocument();
  })

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>testing</category>
      <category>react</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Good practices for unit testing with the React Testing Library and beyond.</title>
      <dc:creator>Jagoda Bieniek</dc:creator>
      <pubDate>Sat, 27 Jan 2024 17:56:01 +0000</pubDate>
      <link>https://dev.to/jagodabieniek/good-practices-for-unit-testing-with-the-react-testing-library-and-beyond-33d6</link>
      <guid>https://dev.to/jagodabieniek/good-practices-for-unit-testing-with-the-react-testing-library-and-beyond-33d6</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;An introduction to  Unit Testing ?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;There is no set of rules that determines the answer to this question (which was personally difficult for me), but in this article I would like to give you some guidelines to help you get started with unit testing.&lt;br&gt;
When creating test cases, it is worth keeping in mind how user interfaces will be used by users, and further testing for maintainability.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;What to test ?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Unit testing in the context of front-end development involves testing individual components or features of the user interface to ensure that they work as expected. Here are some aspects to consider when deciding what to test in front-end unit testing: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Component rendering&lt;/strong&gt; whether the component renders correctly with the props, or without them if they are not mandatory, as it will render without them.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Edge cases&lt;/strong&gt; test your components with extreme or unexpected input to ensure they handle edge cases gracefully.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Component behaviour&lt;/strong&gt; test the interaction and behaviour of your components. For example, if you have a button that triggers an action, make sure it behaves as expected when clicked. Check state changes in response to user interaction.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;State management&lt;/strong&gt; if your front-end relies on state management (e.g. with React's state or Redux), test that the state updates as expected. Verify that the UI responds appropriately to state changes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;DOM manipulation&lt;/strong&gt; if your components manipulate the DOM directly, test that these manipulations are correct.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Best Practices for Writing Tests.&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Write descriptive names&lt;/strong&gt;. Write clear and descriptive names for your test cases. This makes it easy for developers to understand the purpose of each test.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Test one separated unit of working code.&lt;/strong&gt; Try to find the smallest but autonomous peace of code. In the case of the front end, it includes: all the user interactions with our front end layer, such as clicks, double clicks, submit ,focus ,typing , etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Test Driven Development approach.&lt;/strong&gt; As I mentioned before, it is essential to test small peace of code, but if you start your implementation from test? this way of writing unit test helps you at the beginning to ensure that your code is designed in accordance with business need expentations, help you remember about &lt;em&gt;every case&lt;/em&gt;  that should be considered. From my own experience, I see that it is easier to 'mock' dependencies for testing witch at the begaing of your path can be challenging. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mock External Dependencies.&lt;/strong&gt; Isolate your unit tests by using mocks or stubs for external dependencies such as API calls or services. This allows you to focus on testing the specific functionality of the component without relying on the entire system. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Selective coverage&lt;/strong&gt; in real time for writing unit tests is limited due to the business pressure to finish development faster, so our role is to organise the work to maintain high quality code and ensure it is delivered on time. My recommendation is to start testing from the Javascript code and then move on to the visual aspect. This way we cover the functional part of the application and protect the critical business logic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do not test implementation details&lt;/strong&gt; its key role due to writing unit test, because in case of possible refactoring of code, which is something common in development of application, the tests related to implementation would be needed to be changed, resulting in generating tons of additional work. &lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Best Practices for Writing Tests with React Testing Library.&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The general guidelines above also apply to writing unit tests using the React Testing Library however it worthy to exdends thiis rules about RTL philosophy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Accesibility&lt;/strong&gt; RTL provides queries, such as getByRole or getByText, that allow you to select elements based on their role or text content, which is essential for verifying that the correct information is being presented to users. Below i present hierarchy of using RTL queries.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// getByRole()
// getByLabelText()
// getByText()
// getByDisplayValue()
// getByTitle()
// getByTestId()( when text is dynamic)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why in that order ? The RTL creators correctly point out that getByTestId, which is related to the DOM, is irrelevant to the user. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-world usability&lt;/strong&gt; testing should reflect user interaction with the application as closely as possible. &lt;/p&gt;

&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;The overall goal is to facilitate the creation of effective tests that reflect real-world usage and ensure the reliability of application components.&lt;br&gt;
Writing unit tests is key to maintaining high code quality, but we should remember that aiming for 100% coverage may not be the best solution. Focus on the most important functionality.&lt;/p&gt;

&lt;p&gt;In the next article, we'll look at the practicalities of writing your first unit tests. We'll guide you through the process of creating tests for simple components using the React Testing Library (RTL), a popular testing tool in the React ecosystem.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>testing</category>
      <category>react</category>
      <category>frontend</category>
    </item>
    <item>
      <title>An Introduction to Testing Library for React components.</title>
      <dc:creator>Jagoda Bieniek</dc:creator>
      <pubDate>Fri, 05 Jan 2024 12:09:09 +0000</pubDate>
      <link>https://dev.to/jagodabieniek/testing-react-components-with-jest-and-react-testing-library-e6i</link>
      <guid>https://dev.to/jagodabieniek/testing-react-components-with-jest-and-react-testing-library-e6i</guid>
      <description>&lt;h3&gt;
  
  
  &lt;strong&gt;React Testing Library - introduction&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;React Testing Library (RTL) is a powerful tool for testing React components. It is built on top of the DOM Testing Library and is focused on simulating user behavior as closely as possible in your tests.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Why should you use React Testing Library?&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Current with React&lt;/strong&gt;, RTL ensures alignment with the most recent versions of React, providing developers confidence that their testing practices remain up-to-date.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lightweight&lt;/strong&gt;, The library provides utility functions on top of 'react-dom' without adding significant overhead.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Easy Setup&lt;/strong&gt;, Starting with Create React App version &amp;gt;=3.4.0, React Testing Library is already included along with the necessary setup.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Increasing Popularity&lt;/strong&gt;, According to npm trends, React Testing Library has gained popularity over its main competitor, Enzyme.js.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Framework Agnostic&lt;/strong&gt; ,For developers working with different frameworks, analogous libraries are available inspired by the same principles, such as Vue Testing Library and Angular Testing Library, etc.  &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--D_WJMQaq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0d9fqcj3r4hbdcxb3u0y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--D_WJMQaq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0d9fqcj3r4hbdcxb3u0y.png" alt="Image description" width="800" height="484"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Features  of RTL&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Accesibility&lt;/strong&gt; RTL encourages you to interact with your components in ways that a real user would, thus it is good practice to use query methods which are based on the role of the element for the user.&lt;br&gt;
&lt;strong&gt;Simple API&lt;/strong&gt; RTL offers set of utilities that simplify much of the underlying complexity of testing React Components. &lt;br&gt;
&lt;strong&gt;Full DOM Rendering&lt;/strong&gt; (RTL) does not provide a "shallow" rendering function like Enzyme's shallow. RTL's philosophy is to test components as closely as possible to how they work in the browser, which means testing them within the context of the full DOM with child components rendered as well.&lt;br&gt;
&lt;strong&gt;Independ from React feature&lt;/strong&gt; If you are aiming to test components without relying on React-specific features or APIs, you can mock out dependencies or use plain JavaScript when asserting and interacting with your components in RTL. &lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Getting Started with RTL&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;As mentioned, for versions greater than or equal to 3.4.0, the configuration is ready to use. Go to your package.json and check if you have the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; "scripts": {
    "test": "react-scripts test"
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and following dependencies: testing-library/jest-dom,testing-library/react and Jest you can start to write your first test. &lt;/p&gt;

&lt;p&gt;For lower version you need intall following dependencies&lt;br&gt;
if you use npm&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save-dev @testing-library/react @testing-library/jest-dom
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or with yarn:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add --dev @testing-library/react @testing-library/jest-dom
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Integrate Jest with React testing Library create file &lt;em&gt;jest.setup.js&lt;/em&gt; and paste following  base configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import '@testing-library/jest-dom';
 module.exports = {
  collectCoverage: true,
  collectCoverageFrom: ['src/**/*.{js,jsx}'],
  coverageDirectory: 'coverage',
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['&amp;lt;rootDir&amp;gt;/jest.setup.js'],
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Summary&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;React Testing Library (RTL) offers developers a robust solution for testing React components that emphasizes &lt;em&gt;real-world user behavior&lt;/em&gt;. Aligning with the latest advancements in React, RTL ensures testing methods remain up-to-date and lightweight, avoiding cumbersome configurations, especially with Create React App (v3.4.0+), where RTL is pre-included.&lt;/p&gt;

&lt;p&gt;The adoption of RTL over Enzyme.js is on the rise as it focuses on &lt;em&gt;full DOM rendering&lt;/em&gt; for realistic test scenarios, &lt;em&gt;accessibility-first&lt;/em&gt; querying, and a simplified API. It also supports testing components without dependency on React-specific APIs by enabling plain JavaScript usage.&lt;/p&gt;

&lt;p&gt;To get started with RTL in projects using Create React App (v3.4.0+), simply check your package.json for the test script and necessary dependencies such as testing-library/jest-dom and testing-library/react. For older setups, installation is straightforward with npm or yarn, followed by a basic Jest configuration in jest.setup.js.&lt;/p&gt;

&lt;p&gt;With this setup, developers can begin writing tests with confidence, benefiting from RTL's focus on &lt;em&gt;user-centric&lt;/em&gt; testing practices and its flexibility to adapt to non-React specific environments.&lt;/p&gt;

&lt;p&gt;However, keep in mind that Enzyme is an older tool; there is more information available about various use cases and issues, which allows developers to better prepare for encountering similar situations in their project.&lt;/p&gt;

&lt;p&gt;In our upcoming articles, we will take a closer look into the world of testing React components. We'll guide you through practical examples and strategies for testing the most popular functionalities within React applications.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>react</category>
      <category>testing</category>
    </item>
  </channel>
</rss>
