Create the Jest Test FileCreate the Jest Test File

Step 3: Create the Jest Test File

Here is the code from the recording: GitHub


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.


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


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.


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

Complete code

Everything was clear?

Section 5. Chapter 3