Vitest React Component Testing

testing
TypeScript
testing
zen
Remix

Comprehensive component tests with user interaction and accessibility checks.

12/8/2025

Prompt

Vitest React Component Testing

Write comprehensive Vitest tests for the React component [ComponentName].

Test Suites

1. Render Test

  • Component renders without crashing
  • Initial state is correct
  • No console errors

2. Props Test

  • Component renders correctly with different props
  • Default props work as expected
  • Props are properly passed to children

3. User Interaction Tests

Use @testing-library/user-event:

Click Events

await user.click(button)
expect(callback).toHaveBeenCalled()

Typing Input

await user.type(input, 'test text')
expect(input).toHaveValue('test text')

Form Submission

await user.click(submitButton)
expect(onSubmit).toHaveBeenCalledWith(expectedData)

4. Accessibility Tests

Use jest-axe:

const { container } = render(<Component />)
const results = await axe(container)
expect(results).toHaveNoViolations()

5. Mock External Dependencies

API Calls

vi.mock('@/lib/api')
mockFetch.mockResolvedValue({ data: mockData })

Routing

vi.mock('next/navigation')
mockPush.mockImplementation(() => {})

6. Async Behavior Testing

Loading States

expect(screen.getByText('Loading...')).toBeInTheDocument()
await waitFor(() => {
  expect(screen.getByText('Success')).toBeInTheDocument()
})

Error States

mockApi.mockRejectedValue(new Error('API Error'))
expect(await screen.findByText('Error occurred')).toBeInTheDocument()

7. Snapshot Test

  • UI regression detection
  • Update when intentional changes made
expect(container).toMatchSnapshot()

8. Edge Cases

  • Empty data
  • Long text overflow
  • Rapid consecutive clicks
  • Invalid inputs
  • Error boundaries

Test Organization

describe('[ComponentName]', () => {
  describe('rendering', () => {
    it('renders without crashing', () => { })
  })
  
  describe('user interactions', () => {
    it('handles click events', async () => { })
  })
  
  describe('async behavior', () => {
    it('shows loading state', async () => { })
  })
})

Best Practices

Query Priority (testing-library)

  1. getByRole - Most accessible
  2. getByLabelText - Form elements
  3. getByPlaceholderText - Inputs
  4. getByText - Non-interactive text
  5. Avoid getByTestId - Implementation detail

Avoid Implementation Details

  • Don't test state directly
  • Test user-observable behavior
  • Query by what users see

Requirements

  • Use describe/it blocks
  • Follow testing-library best practices
  • Cover all user workflows
  • Test accessibility

Tags

vitest
testing
react
testing-library

Tested Models

gpt-4
claude-3-5-sonnet

Comments (0)

Sign in to leave a comment

Sign In
Vitest React Component Testing | vibeprompt.directory