Chapter 9

Chapter 9: Testing with AI

Testing is often postponed when delivery pressure rises. AI can draft tests and suggest cases, while you remain responsible for the test strategy, assertions, fixtures, and coverage of real risks.

Published: · Last reviewed: Nov 1 2026

This chapter covers the core testing workflow. The standalone Testing with AI guide extends it — integration tests, TDD patterns, mocking, edge case generation, and framework-specific prompts.

Why Developers Skip Testing

Common reasons include time pressure, unclear test boundaries, fragile fixtures, and the belief that the code is simple enough. AI can reduce some writing effort, but generated tests still require review, execution, and maintenance.

The Real Cost

Untested behavior creates future uncertainty. The eventual cost varies, but regressions are usually harder to diagnose without a useful test suite. AI may lower the drafting cost; it does not remove the cost of designing, reviewing, running, and maintaining tests.


The Testing Pyramid

Not all tests are equal. The testing pyramid is a common guideline for the distribution of test types — more fast, focused unit tests at the base, fewer slow, broad tests at the top.

E2E Tests
Few — Slow, brittle, expensive
Integration Tests
Some — Test component interaction
Unit Tests
Many — Fast, focused, reliable

AI is especially useful for drafting unit and integration tests, which are usually the cheapest to run and maintain. It can read a function's signature, logic branches, and edge cases and draft tests for them; you still check that the suite covers the function's contract.


Generating Unit Tests with AI

A common use of AI in testing is to provide a function and ask for a draft test suite. The following prompt is a starting pattern; adapt it to the function's contract and the risks that matter.

Write unit tests for this function using Jest:

[paste your function]

Cover:
- Normal cases (expected inputs, expected outputs)
- Edge cases (empty arrays, null values, boundary values)
- Error cases (invalid inputs, missing parameters)

Use descriptive test names that explain what's being tested.
Group related tests with describe blocks.

Example: testing a filter function

function filterActivities(
  activities: Activity[],
  members: string[],
  day: string | null
): Activity[] {
  return activities.filter(a => {
    const memberMatch = members.length === 0 ||
      members.includes(a.member);
    const dayMatch = !day || a.day === day;
    return memberMatch && dayMatch;
  });
}

AI generates tests like:

describe('filterActivities', () => {
  const activities = [
    { id: '1', name: 'Soccer', member: 'Alice', day: 'Monday' },
    { id: '2', name: 'Piano', member: 'Bob', day: 'Tuesday' },
    { id: '3', name: 'Swim', member: 'Alice', day: 'Wednesday' },
    { id: '4', name: 'Dance', member: 'Carol', day: 'Monday' },
  ];

  describe('member filtering', () => {
    it('returns all activities when no members selected', () => {
      expect(filterActivities(activities, [], null)).toHaveLength(4);
    });

    it('filters by single member', () => {
      const result = filterActivities(activities, ['Alice'], null);
      expect(result).toHaveLength(2);
      expect(result.every(a => a.member === 'Alice')).toBe(true);
    });

    it('filters by multiple members', () => {
      const result = filterActivities(activities, ['Alice', 'Bob'], null);
      expect(result).toHaveLength(3);
    });
  });

  describe('day filtering', () => {
    it('keeps every day when day is null', () => {
      const result = filterActivities(activities, ['Alice'], null);
      expect(result.map(a => a.day)).toEqual(['Monday', 'Wednesday']);
    });

    it('filters by specific day', () => {
      const result = filterActivities(activities, [], 'Monday');
      expect(result).toHaveLength(2);
    });
  });

  describe('combined filtering', () => {
    it('applies both member and day filters', () => {
      const result = filterActivities(activities, ['Alice'], 'Monday');
      expect(result).toHaveLength(1);
      expect(result[0].name).toBe('Soccer');
    });
  });

  describe('edge cases', () => {
    it('handles empty activities array', () => {
      expect(filterActivities([], ['Alice'], null)).toEqual([]);
    });

    it('returns empty when no matches found', () => {
      expect(filterActivities(activities, ['Nobody'], null)).toEqual([]);
    });
  });
});

Notice the structure: descriptive describe blocks group related tests, each it block checks a specific behavior, and selected edge cases get their own group. Compare the suite with the function's contract and add missing risks; this example is not comprehensive by itself.

PASS src/__tests__/filterActivities.test.ts
✓ returns all activities when no members selected (2 ms)
✓ filters by single member
✓ filters by multiple members (1 ms)
✓ keeps every day when day is null
✓ filters by specific day
✓ applies both member and day filters (1 ms)
✓ handles empty activities array
✓ returns empty when no matches found
Tests: 8 passed, 8 total

Integration Tests with AI

Integration tests verify that components work together correctly — not just in isolation. This is where you test that your React component renders properly, handles user interactions, and integrates with hooks and state.

Write integration tests for this React component
using React Testing Library:

[paste component code]

Test:
- Component renders without crashing
- Displays correct initial data
- User interactions work (clicking, typing, submitting)
- State updates reflect in the UI
- Error states display correctly

Use userEvent for interactions, not fireEvent.

The instruction to use userEvent instead of fireEvent matters — it simulates real user behavior more accurately. Small details like this bring the generated tests closer to how users actually interact with the component.


Test-Driven Development with AI

Test-Driven Development (TDD) starts with an executable example of desired behavior, then adds code to make it pass. AI can draft tests from a specification, but you must review whether they express the intended contract, meaningful failures, and relevant edge cases.

Red
Write failing test
→
Green
Write minimal code
→
Refactor
Clean up code
→
repeat

TDD with AI: the workflow

TDD Session: Building a Validation Function
You
I need a function validateActivity(data) that checks: name is required and at least 2 characters, day must be a valid weekday, time must be in HH:MM format. Write the tests first — don't write the implementation yet.
AI
[Generates 12 test cases covering: missing name, short name, valid name, invalid day, valid day, malformed time, valid time, multiple errors, etc.]
You
I reviewed the tests and ran them: all 12 fail, as expected. Now write the minimum implementation that makes them pass.
AI
[Writes validateActivity function. The developer runs the suite locally: all 12 tests pass.]
You
Now refactor the implementation for readability, keeping all tests passing.

Each step is explicit: tests first → implement → refactor. The tests are executable examples of part of the specification; passing them does not prove the implementation correct beyond the cases and properties they cover.

Why TDD and AI Fit Together

One barrier to TDD is the upfront work of turning requirements into executable examples. AI can help draft those examples, but you must verify that they express the intended behavior and include meaningful failure cases. Tests reduce regression risk only for behavior they actually exercise.


What to Test (and What Not To)

Not everything needs tests. Knowing where to focus your testing effort is just as important as writing the tests themselves.

Worth Testing

  • Business logic (validation, calculations, filtering)
  • Data transformations (formatting, parsing, mapping)
  • State management (hooks, reducers, stores)
  • API contract compliance (request/response shapes)
  • Edge cases (empty data, null, boundary values)
  • User-facing interactions (forms, buttons, navigation)

Usually Not Worth Testing

  • Pure UI layout (CSS positioning, colors)
  • Third-party library internals
  • Simple pass-through components
  • Constants and configuration
  • Framework behavior (React re-renders)
  • Implementation details (internal state shape)

The principle: test behavior, not implementation. Your tests should verify what the code does, not how it does it internally. This makes tests resilient to refactoring — you can restructure the code completely, and as long as the behavior stays the same, the tests still pass.


AI for Edge Case Discovery

A useful and often overlooked testing ability is suggesting edge cases you didn't think of. Developers tend to test the "happy path" — the normal cases where everything works. AI can quickly list unusual cases for you to evaluate.

Here is my function:

[paste function]

What edge cases should I test that I probably haven't
thought of? Be creative — think about unusual inputs,
boundary values, timing issues, and failure modes.

AI typically identifies edge cases like: what if the array has exactly one element? What if two activities have the same time? What if the member name contains Unicode characters? What if the date is February 29th? Cases like these often cause production bugs because they are easy to forget. Keep the ones that are relevant to the function's contract and risks.

Pro Tip: The Adversarial Tester

Ask AI to act as an adversarial tester: "You're a QA engineer trying to break this function. What inputs would cause it to fail, return wrong results, or behave unexpectedly?" This framing often produces more candidate edge cases than a neutral "write tests" request.


Testing AI-Generated Code

Here's a critical meta-point: code generated by AI needs testing more than code you wrote yourself. You understand your own code's intent intuitively. AI-generated code might look correct but contain subtle logic errors, wrong assumptions, or hallucinated API calls.

🔁

Generate → Test → Iterate

After AI generates code, immediately ask it to write tests. Run the tests. Fix failures. This is the core loop.

🔍

Review Test Logic

AI-generated tests can have the same bugs as AI-generated code. Read the assertions — do they actually test the right thing?

✅

Verify Expectations

Check that expected values in tests are actually correct. AI sometimes generates tests that pass but assert the wrong behavior.

🧪

Add Your Own Cases

AI covers patterns well but may miss domain-specific edge cases. Add tests for scenarios only you know about.

⚠️ Critical Warning

Tests that always pass are worthless. A common AI testing error is generating tests with assertions that are always true regardless of input (like testing that an array "is defined" instead of testing its contents). Always verify that your tests can actually fail — break the code intentionally and confirm the test catches it.


Adding Tests to Existing Code

Adding tests to an existing, untested codebase can feel overwhelming. AI can help draft a test suite that records the existing behavior, giving you a safety net before you make changes.

Here is an existing function that has no tests:

[paste function]

Draft a risk-based test suite that documents its
current behavior. Include tests for:
- What the function does with typical inputs
- What it returns for edge cases
- How it handles errors

I'm about to refactor this function and need tests
to ensure I don't break anything.

This "characterization testing" approach captures existing behavior as tests before you change anything. Now you can refactor with more confidence: a failing test shows which recorded behavior changed. Behavior the suite does not cover can still change without warning.


Common Mistakes

Testing Anti-Patterns

🧪 Practical Exercise

Take a function from one of your projects — ideally one with no tests. Practice three different testing approaches:

Run all tests. If they all pass on the first try, intentionally break the code and verify that tests catch the breakage.


Key Takeaways

Related Guides

Testing with AI

Go deeper on unit tests, integration tests, and TDD prompts.

AI Evals in Production

Test AI behavior itself with datasets and release gates.

→
Previous Chapter AI + Git Workflow
Next Chapter AI-First Development Methodology
→