Skip to content

How to Test AI-Generated React Components Properly

AI tools write React components fast but skip edge cases. These testing strategies catch the gaps before they reach production.

· · 9 min read

Updated: November 28, 2026

Vitest test that clicks a delete button and expects onDelete to be called with the user id

Quick Take

AI-generated React tests almost always cover one thing, the happy path, and skip empty, loading, and error states and whether callbacks fire with the right arguments. Add those four tests yourself, every time, and write the test file before asking for the component so the contract is explicit. Set Vitest's branch coverage threshold to 75% in vitest.config.ts, run with coverage enabled, and the run exits with code 1 when untested if/else paths pull branch coverage under that floor, even when line coverage looks fine.

Testing AI-generated React components is where most teams get burned. AI generates React components fast. It also generates tests that only test the thing that works. The happy path: valid props, data loaded, user clicks and something happens. What it skips: empty arrays, undefined callbacks, error states, loading states that never resolve. Those paths fail in production, not because the code is wrong, but because nobody wrote the test that would have caught it. This 2026 playbook walks through the tests that actually catch those failures.

You can't outsource the edge cases. That's the part AI consistently leaves for you.

If you're building this into a wider review process, our quality-first framework for AI coding sets the scorecard these test strategies plug into.

Where AI-written tests go wrong

React Testing Library's documentation emphasizes testing behavior over implementation, what the user sees and does, not internal state. AI tools mostly ignore this principle. They generate tests that mirror the implementation rather than the contract.

Here's what that looks like in practice. You ask an AI to write a UserList component and its tests. The component comes back looking reasonable. The tests come back covering exactly one thing: rendering the list when users has data in it.

What's missing?

  • What renders when users is an empty array
  • What shows when isLoading is true
  • What happens when error is a non-empty string
  • What fires when onDelete is called and whether the callback receives the right argument

None of those paths exist in the generated test file. They're not edge cases in some abstract sense, they're the states your users will actually hit. Empty lists happen. Network requests fail. Load states get stuck.

The AI didn't skip them because they're hard. It skipped them because nothing in the prompt asked for them, and the happy path is the one every example of a list component shows.

When the component itself, not just the tests, comes back with the same happy-path shape, the refactoring AI-generated React components guide covers the structural fixes (separating presentational from container concerns, isolating side effects) that make those edge cases easy to add back.

The edge cases AI skips

Every AI-generated component test file is missing the same four tests. Add them manually, every time, without waiting to see if the AI included them. It didn't.

Vitest with React Testing Library makes these short to write.

// AI writes this, the only test you'll get
it('renders user list', () => {
  render(<UserList users={mockUsers} />)
  expect(screen.getByText('Alice')).toBeInTheDocument()
})

// You need to add these three (the callback test, the fourth, is further down)
it('renders empty state when no users', () => {
  render(<UserList users={[]} />)
  expect(screen.getByText('No users found')).toBeInTheDocument()
})

it('shows loading spinner while fetching', () => {
  render(<UserList users={[]} isLoading={true} />)
  expect(screen.getByRole('status')).toBeInTheDocument()
})

it('renders error message on fetch failure', () => {
  render(<UserList users={[]} error="Failed to load" />)
  expect(screen.getByText('Failed to load')).toBeInTheDocument()
})

Here's the opinionated take: if you can't write these three tests, the component interface isn't finished. The props aren't defined. The component doesn't know what to render in those states yet. Writing the tests surfaces that problem before it becomes a production bug.

If you can't write the empty-state, loading-state, and error-state tests, the component interface isn't finished yet.

Share this Post on X Bluesky

Add these four tests to an AI-generated list component and there's a good chance at least one fails on the first run, often the error state, because the component renders nothing instead of an error message. That's a bug caught in development, not in production.

What "No Users Found" Actually Requires

The empty state test looks simple. It often isn't. AI-generated list components frequently skip the empty state branch entirely, the component renders an empty <ul> instead of a message. The test fails not because the component is broken in some subtle way, but because the feature doesn't exist yet.

That's exactly what the test is for. Write it, watch it fail, fix the component.

Test-first prompting

The standard prompting pattern, "write a React component that does X", gives AI maximum freedom to define the interface. Test-first prompting inverts this. You define the contract, the AI writes code that satisfies it.

Write the test file first. Include the props interface. Include assertions for valid data, empty state, error state, and callback behavior. Then send that test file to your AI tool with: "Write a React component that passes these tests."

The result is different in a specific way. The component handles the states you've asserted because those states are in the contract it received. In practice that means fewer revision rounds, since the component handles your edge cases on the first attempt instead of needing three rounds of "add an empty state, now add error handling, now make the callback fire with the right data."

It also forces you to think about the component interface before you have a component. That's arguably the main benefit.

// @vitest-environment jsdom
// Write this test file FIRST, before any component exists
import { render, screen, fireEvent, cleanup } from '@testing-library/react'
import '@testing-library/jest-dom/vitest'
import { afterEach, describe, it, expect, vi } from 'vitest'
import { UserList } from './UserList'

// without `globals: true`, React Testing Library doesn't clean up on its own
afterEach(cleanup)

interface User {
  id: string
  name: string
}

describe('UserList', () => {
  const mockUsers: User[] = [{ id: 'user-123', name: 'Alice' }]

  it('renders user names', () => {
    render(<UserList users={mockUsers} />)
    expect(screen.getByText('Alice')).toBeInTheDocument()
  })

  it('renders empty state', () => {
    render(<UserList users={[]} />)
    expect(screen.getByText('No users found')).toBeInTheDocument()
  })

  it('shows loading state', () => {
    render(<UserList users={[]} isLoading={true} />)
    expect(screen.getByRole('status')).toBeInTheDocument()
  })
})

Pass this file to your AI tool. Ask it to write the component. You'll get a UserList that handles all three states on the first attempt. The contract was explicit.

Test-first is not the only way to give an agent a contract. When the components already exist, you can let it read their real props instead of guessing them. Storybook's MCP addon serves your component API to Claude Code, and the walkthrough on generating a Storybook with Claude Code covers the setup and the configuration failures that quietly degrade it. It is still a preview feature and the API may change. It was React-only when this post first went up. The Storybook 10.6 docs now list Vue and Angular builders next to the React ones for the component-API toolset, and other frameworks get the development and testing tools without it, so check your framework before building a workflow on it.

Callback and event contracts

AI generates onClick handlers. It almost never tests that those handlers fire with the right arguments. A delete button that calls onDelete might pass the wrong id, format the data incorrectly, or fire with undefined. It looks fine visually. The test would catch it in 10 lines.

vi.fn() from Vitest makes this straightforward:

it('calls onDelete with user id when delete button clicked', () => {
  const onDelete = vi.fn()
  render(<UserList users={mockUsers} onDelete={onDelete} />)
  fireEvent.click(screen.getByRole('button', { name: /delete alice/i }))
  expect(onDelete).toHaveBeenCalledWith('user-123')
})

This test catches the "fires wrong data" bug that passes visual inspection. The button renders. It fires. Something happens. But onDelete received undefined instead of 'user-123', and now the server gets a delete request with no id. That's a real bug class. The test above catches it before the component ships.

Callback contract tests are also the ones AI almost never generates. It'll test that a button exists. It won't test what the button does when you click it.

The three strategies compared

What it catchesEffort
Add the 4 skipped edge-case testsEmpty state, loading state, error state, callback argsManual, every component
Test-first promptingSame states, but built into the component from the startWrite tests before the component, fewer revision rounds
Branch coverage thresholdUntested if/else paths, automatically, in the test runOne-time vitest.config.ts setup

Coverage thresholds in Vitest

The first two strategies require you to write tests manually. This strategy makes the gap visible automatically. Vitest is the runner I'd pick here because it's the one my own projects use now, after moving off Jest; Claude Code handled that migration and the API fixes it needed quickly. Configure Vitest coverage thresholds and the run fails when coverage drops below your floor. Per the Vitest config reference (linked in the sources below), a positive threshold is the minimum percentage required, and coverage collection is off by default (coverage.enabled defaults to false), so run vitest run --coverage in CI or set enabled: true. When a number falls short, Vitest's coverage code logs ERROR: Coverage for branches (...) does not meet global threshold (75%) and sets the process exit code to 1, which is what turns a red number into a failed CI job.

// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    coverage: {
      provider: 'v8',
      thresholds: {
        lines: 80,
        branches: 75,
        functions: 80,
      },
      include: ['src/**/*.tsx', 'src/**/*.ts'],
    },
  },
})

Branch coverage is the signal that matters most for AI-generated React code. Line coverage counts lines executed. Branch coverage counts if/else paths taken. When the component has an empty state branch and the AI's tests never run it, line coverage might stay above 80% while branch coverage drops. That's the gap the threshold catches.

With branches: 75, the run fails when the share of tested branches across the included files drops under 75%. The figure is global unless you set perFile: true, so one weak component can hide behind well-tested ones. Coverage also counts only the code that exists: a component that never got an empty state has no branch to report, which is why you still write that test yourself. The threshold pairs well with the CI/CD quality gates setup if you want the threshold enforced on every pull request automatically.

This threshold earns its keep fast on React projects. When AI-generated tests ship without edge cases, branch coverage is the metric that drops first. Line coverage holds steady. Branch coverage slips below 75% and the build fails. That's the threshold doing exactly what it's supposed to.

The pattern is the same across all three strategies: you can't trust AI to test its own assumptions. It generated the happy path because that's all the prompt described. Your job is the edge cases, write them before, add them after, enforce them with thresholds. That's what keeps AI-assisted development sustainable.

For the broader picture on building quality into AI-assisted workflows, the quality-first framework for AI coding covers how TypeScript types and coverage thresholds work together from the start.

Frequently Asked Questions

Why does AI-generated React code often have poor test coverage?
AI tools optimize for the happy path, the function call that works, the state that renders. Error states, empty arrays, undefined props, and network failures aren't in the prompt unless you put them there, so they tend to get left out. The result is technically accurate code with zero coverage on the paths that actually fail in production.
What's the difference between snapshot tests and behavioral tests for AI components?
Snapshot tests capture rendered HTML, they catch unintended markup changes but don't verify behavior. Behavioral tests check what the component does: does it call the right callback, render the error state, handle an empty list? AI-generated components need behavioral tests because the happy-path HTML often looks fine while the error handling is missing entirely.
How do I write tests before asking AI to generate a component?
Write the test file first with the props interface and the assertions you expect, what it renders with valid data, what it shows with an empty array, what it does when a callback fires, what error state looks like. Then pass the test file to the AI tool with: 'Write a React component that passes these tests.' You get better code on the first attempt.
What Vitest coverage threshold should I set for AI-generated React code?
80% line coverage and 75% branch coverage is a reasonable floor. Branch coverage matters more for AI code, it exposes the if/else paths no test runs. Set these in vitest.config.ts thresholds and run with coverage enabled (coverage.enabled defaults to false); Vitest then logs an error and exits with code 1 when untested paths pull coverage below either floor.