Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Create the Jest Test File | Jest
Expert React
course content

Contenido del Curso

Expert React

Expert React

1. React Key Concepts
2. React Router
3. Redux Toolkit
4. Formik
5. Jest
6. Next Steps

bookCreate the Jest Test File

Step 3: Create the Jest Test File

Theory

We follow a naming convention for our Jest test files to keep things organized. The test file should have the same name as the component file it tests, with the additional extension .test.js. For example, if our component file is named MyComponent.js, the corresponding test file would be MyComponent.test.js.

Practice

We create a new file for our Jest tests in the src folder. We name it as App.test.js. This naming convention makes it easier to understand the relationship between the test file and the component it tests.

Step 4: Import modules

Theory

To begin writing tests, we need to import the necessary modules. Let's break down each module and understand its purpose:

  • render function is used to render a React component into a virtual DOM (in-memory DOM) for testing. It provides a way to interact with and query the component during testing without needing an actual browser or rendering it in the real DOM.
  • screen module provides various query functions that allow us to select elements rendered in the virtual DOM. These query functions, such as getByText, getByTestId, and more, enable us to find elements and perform assertions during testing.
  • fireEvent module allows us to simulate user interactions with the rendered React components. We can use fireEvent to trigger events like clicks, typing, form submissions, and more on the virtual DOM elements.
  • @testing-library/jest-dom/extend-expect - this import extends the expect function from Jest with additional useful matches when testing React components. For example, it enables us to use expect(...).toBeInTheDocument() to check if an element is present in the DOM.

Practice

Additionally, we need to import the component we want to test. Here's an example of the imports:

Complete code

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 3
some-alt