React Testing Library And Jest- The Complete Guide Apr 2026
import userEvent from '@testing-library/user-event' test('form submission', async () => const user = userEvent.setup() render(<LoginForm />)
expect(screen.getByText('Loading...')).toBeInTheDocument()
// Don't test props passed to children expect(ChildComponent).toHaveBeenCalledWith( prop: 'value' ) React Testing Library and Jest- The Complete Guide
const button = screen.getByRole('button', name: /click me/i ) expect(button).toBeInTheDocument()
jest.useRealTimers() // restore Controlled component const Toggle = () => const [on, setOn] = useState(false) return ( <button onClick=() => setOn(!on)> on ? 'ON' : 'OFF' </button> ) async () =>
if (!user) return <div>Loading...</div> return <div>user.name</div>
expect(result.current.count).toBe(1) ) Mock functions with Jest const mockFn = jest.fn() mockFn('hello') expect(mockFn).toHaveBeenCalledWith('hello') expect(mockFn).toHaveBeenCalledTimes(1) // Mock return value jest.fn().mockReturnValue('fixed value') jest.fn().mockResolvedValue('async value') jest.fn().mockImplementation(arg => arg * 2) Mock modules // Mock entire module jest.mock('../api', () => ( fetchUser: jest.fn(), )) // Mock with dynamic implementation jest.mock('axios', () => ( get: jest.fn(() => Promise.resolve( data: id: 1 )), )) Mock timers jest.useFakeTimers() test('delayed action', () => render(<DelayedComponent />) const user = userEvent.setup() render(<
// Async (for elements that appear later) await screen.findByText('Loaded')