Home
🎥 React Testing: Simple test with React Testing Library
July 22, 2025
1 min

Table Of Contents

01
02
Query Priority

React Testing Library is built on top of DOM Testing Library and encourages testing the app the way users interact with it.

It helps you:

  • Avoid manual DOM setup and cleanup
  • Write more readable, user-focused tests
  • Reduce boilerplate
  • Get better error messages and assertions

The Same Test with React Testing Library

import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import MultiStepForm from './MultiStepForm'
test('completes the multi-step form successfully', async () => {
const handleSubmit = jest.fn()
render(<MultiStepForm onSubmit={handleSubmit} />)
// Step 1
expect(screen.getByText(/step 1/i)).toBeInTheDocument()
await userEvent.type(screen.getByLabelText(/email/i), 'test@mail.com')
await userEvent.click(screen.getByRole('button', { name: /next/i }))
// Step 2
expect(screen.getByText(/step 2/i)).toBeInTheDocument()
await userEvent.type(screen.getByLabelText(/password/i), '123456')
await userEvent.click(screen.getByRole('button', { name: /submit/i }))
expect(handleSubmit).toHaveBeenCalledWith({
email: 'test@mail.com',
password: '123456',
})
})

Query Priority

Query APIWhen to Use
getByRoleMost elements (buttons, inputs, headings, etc.)
getByLabelTextForm fields
getByPlaceholderTextInputs without labels
getByTextStatic text and simple elements
getByDisplayValuePre-filled form values

Quick Reference

AssertionUse Case
toBeInTheDocumentExists in DOM
toHaveTextContentText rendering
toBeDisabled/EnabledForm and button states
toHaveValueInput values
toBeCheckedCheckbox / radio
toHaveAttributeLinks, aria, images

Test a Form

Use CaseWhy It Matters
Happy pathConfirms base functionality
Required validationPrevents bad submissions
Invalid formatsData correctness
Field-level errorsUX clarity
Server errorsRobust failure handling
Loading statesPrevents duplicate submits
Reset behaviorState consistency
Keyboard interactionAccessibility

Custom render

import { render as rtlRender } from '@testing-library/react'
import { ThemeProvider } from '../context/theme'
function render(ui, options) {
return rtlRender(ui, {
wrapper: ({ children }) => <ThemeProvider>{children}</ThemeProvider>,
...options,
})
}
export * from '@testing-library/react'
export { render }

Tags

#ReactTesting

Share

© 2026, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube