Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Second Test Case | 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

bookSecond Test Case

Step 6: Create the second test

Practice

The second test will be dedicated to checking the increment button's functionality. The test case will simulate clicking the increment button two times and then verify if the result element displays the updated value Result: 2. If the expectation is met, the test will pass, indicating that the increment functionality of the counter works correctly. If it fails, there may be an issue with the increment logic or the app's rendering of the result element.

Code explanation:

  • Line 2: This line renders the <App /> component using the render function from Testing Library for React, as done in the previous test. This prepares the component for testing.
  • Line 3-4: These two lines find the increment button and the result element using screen.getByRole and screen.getByText methods, respectively. The increment button is located by its role button and the regular expression /increment/i for the name (case-insensitive). The result element is located by the text that contains result: (case-insensitive).
  • Line 6: This line simulates a user clicking the increment button using the fireEvent.click method from Testing Library. After this click, the counter increments once.
  • Line 7: This Jest expect statement checks if the resultElement has the text Result: 1 after the first click on the increment button. If the text content matches the expected value, the test passes; otherwise, it fails.
  • Line 9: This line simulates another user's click on the increment button. After this second click, the counter increments again.
  • Line 10: This Jest expect statement checks if the resultElement has the text Result: 2 after the second click on the increment button. If the text content matches the expected value, the test passes; otherwise, it fails.

Complete code

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

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