How to Write Your First React Component Test
Writing your first React test is easier than you think. Here is a step-by-step guide using React Testing Library.
How to Write Your First React Component Test
Writing your first React test is easier than beginners expect. Here is a step-by-step guide using React Testing Library.
Step 1: Set Up the Test
Create a test file with a .test.js extension. Import render and screen from RTL, and your component. Jest picks up .test.js files automatically.
Step 2: Write a Test Block
Use Jest's test function to define a case. Give it a description like 'renders the heading'.
Step 3: Render the Component
Call render with your component inside the test. This mounts it in a simulated DOM provided by jsdom.
Step 4: Query an Element
Use a screen query to find an element. For a heading, screen.getByRole('heading', { name: /hello/i }) finds it by role and accessible name.
Step 5: Assert It Is Present
Use expect to assert the element is in the document. expect(heading).toBeInTheDocument() checks it rendered. This is your first passing test.
Step 6: Run the Test
Run your test command, typically npm test, which runs Jest. You should see the test pass.
Step 7: Test Behavior, Not Implementation
The next tests should simulate user events and assert the result, like clicking a button and checking the count changed. This tests real behavior, not implementation details.
The Takeaway
Set up a .test.js file, use Jest's test function, render the component with RTL, query an element by role and name, assert it is present, and run with npm test. Then move to testing behavior with events.
Create a .test.js file, import render and screen from RTL and your component, use Jest's test function, render the component, query an element by role and name, and assert it is in the document. Run with npm test.
Use RTL's screen queries, preferably by role and accessible name, like screen.getByRole('heading', { name: /hello/i }). These are the same queries screen readers use, so they focus on what the user experiences.
It mounts your component in a simulated DOM provided by jsdom, so you can query and interact with the rendered output. After render, you use screen queries to find elements.
Run your test command, typically npm test, which runs Jest. Jest automatically picks up .test.js files. You should see your test pass or fail in the output.
Behavior. Simulate user events like clicks and typing with userEvent, then assert the result, like a count changed or a message appeared. This tests real behavior, not implementation details, and survives refactors.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

