6. Next Steps
Create the Jest Test File
Step 3: Create the Jest Test File
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
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:
renderfunction 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.
screenmodule provides various query functions that allow us to select elements rendered in the virtual DOM. These query functions, such as
getByTestId, and more, enable us to find elements and perform assertions during testing.
fireEventmodule allows us to simulate user interactions with the rendered React components. We can use
fireEventto 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:
Everything was clear?