Jest- The Complete Guide | React Testing Library And

render(<Button onClick=handleClick>Click Me</Button>)

render(<UserProfile userId=1 />)

import render, screen from '@testing-library/react' import UserProfile from './UserProfile' // Mock fetch globally global.fetch = jest.fn()

test('should increment counter', () => const result = renderHook(() => useCounter(0)) React Testing Library and Jest- The Complete Guide

test('consumes context', () => const getByText = customRender(<ThemedComponent />, providerProps: initialTheme: 'dark' ) expect(getByText(/dark mode/i)).toBeInTheDocument() ) import renderHook, act from '@testing-library/react' const useCounter = (initial = 0) => const [count, setCount] = useState(initial) const increment = () => setCount(c => c + 1) return count, increment

test('toggles state on click', async () => const user = userEvent.setup() render(<Toggle />)

await user.click(button) expect(button).toHaveTextContent('ON') UserProfile userId=1 /&gt

// Test behavior, not implementation expect(screen.getByText('Welcome John')).toBeInTheDocument()

// Wait for the user name to appear expect(await screen.findByText('John Doe')).toBeInTheDocument()

export default testEnvironment: 'jsdom', setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'], transform: jsx, ) import render

expect(await screen.findByText('Valid email required')).toBeInTheDocument() ) ✅ DO // Query by accessible name screen.getByRole('button', name: /submit/i ) // Use findBy for async elements expect(await screen.findByText('Loaded')).toBeInTheDocument()

// Don't test props passed to children expect(ChildComponent).toHaveBeenCalledWith( prop: 'value' )

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 />)

import '@testing-library/jest-dom/vitest' // or 'jest-dom' Component to test ( Button.jsx ) export const Button = ( onClick, children, disabled = false ) => ( <button onClick=onClick disabled=disabled> children </button> ) Test file ( Button.test.jsx ) import render, screen from '@testing-library/react' import userEvent from '@testing-library/user-event' import Button from './Button' test('renders button with children and handles click', async () => const handleClick = jest.fn() const user = userEvent.setup()

Back
Top