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

Course Content

Expert React

Expert React

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

bookFirst Test Case

Step 5: Create the first test

Theory

Let's create the first test case for the app. The most logical thing to check is whether the App component renders correctly.

Practice

We need to check whether the App component renders correctly and if it contains the required elements, such as the increment and decrement buttons, as well as the result element with the initial value Result: 0. If all the expectations in this test case pass, the app is rendering correctly.

Code explanation:

  • Line 2: This line renders the <App /> component using the render function provided by Testing Library for React. This simulates rendering the React component as it would be displayed in the actual DOM during the test.
  • Line 4-5: These two lines use the screen.getByRole method from Testing Library to find the buttons with the roles button and names matching the regular expressions /increment/i and /decrement/i, respectively. This ensures that both the increment and decrement buttons are present in the rendered component.
  • Line 6: This line uses the screen.getByText method to find an element that contains the text result: (case-insensitive). It is used to locate the element that displays the result of the counter.
  • Line 8-10: These are Jest expected statements that assert certain conditions are true:
    • Line 8: This checks if the incrementButton element is present in the DOM. If it is, the test passes; otherwise, it fails.
    • Line 9: This checks if the decrementButton element is present in the DOM. If it is, the test passes; otherwise, it fails.
    • Line 10: This checks if the resultElement contains the text Result: 0. If it does, the test passes; otherwise, it fails.

Complete code

Take the time to run the test. To do this, click the "play" button in the top right corner of the CodeSandbox. When you click on the tests after running, you can see the details of each test. Additionally, please pay attention to the App.test.js file to ensure everything is clear.

Note

Additionally, you can intentionally break the app and rerun the test to check whether the test will pass or what error will be encountered.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 4
some-alt