Course Content
Expert React
Expert React
First 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 therender
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 rolesbutton
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 textresult:
(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 textResult: 0
. If it does, the test passes; otherwise, it fails.
- Line 8: This checks if the
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.
Thanks for your feedback!