Developer writing automated tests for AI-generated code

How to Write Tests for AI-Generated Code (Without Slowing Vibe Coding)

Tests for AI-generated code are the unglamorous guardrail that keeps vibe coding fast instead of reckless. You do not need a QA department or two-week test sprints — you need a thin layer of automated checks that catch the predictable failures AI introduces: broken imports, hallucinated APIs, missing null guards, and auth logic that only works in the happy path. This guide shows how to add tests without killing momentum. Updated October 2026.

Developer writing automated tests for AI-generated code in a modern IDE without slowing vibe coding workflow
Lightweight tests let you keep prompting fast while catching the failures AI repeats across every project.

If you are still shipping features without any test harness, start with the Vibe Coding Roadmap and our guide on how to review AI-generated code. Tests are the automation layer on top of manual review — they run on every save, every deploy preview, every refactor prompt chain. The goal is not enterprise coverage metrics; it is shipping prompts with a safety net tight enough to catch regressions and loose enough to stay out of your way.

Table of contents

  1. Why test AI code at all
  2. The vibe-coder test pyramid
  3. What to test first
  4. Tools that fit the stack
  5. Prompting AI to write tests
  6. CI without ceremony
  7. Anti-patterns that slow you down
  8. Weekly testing workflow
  9. FAQ

Why test AI-generated code at all

Vibe coding trades upfront planning for iterative speed. That works until the third prompt chain rewrites a utility function and silently breaks checkout. AI does not remember your edge cases. It optimizes for the prompt in front of it, not the regression suite you never wrote.

Tests for AI-generated code buy you three things:

  • Confidence to prompt aggressively — refactor prompts stop feeling like roulette
  • Faster debugging — failing test points at the file before you burn tokens on guesswork
  • Handoff readiness — when you hit the developer handoff threshold, tests are the spec

Pair this mindset with vibe coding vs vibe engineering — engineering adds guardrails; testing is the cheapest one. Without tests, every multi-file prompt is a coin flip. With a thin layer, you treat AI output like a junior developer: fast, creative, needs verification.

Without testsWith thin test layer
Manual click-through after every promptRed/green signal in seconds
Fear of multi-file refactorsPrompt chains with safety net
Production surprises on deployPreview deploy blocks on CI failure
Developer handoff requires full rewriteTests document intended behavior

The regression patterns AI repeats

After reviewing hundreds of vibe-coded repos, the same failures show up: importing from paths that do not exist after a folder restructure, calling Supabase client methods with wrong signatures, forgetting await on server actions, duplicating environment variable names with different casing, and removing error boundaries during “cleanup” prompts. Tests catch these because they exercise real execution paths — not because they are magic.

The vibe-coder test pyramid

Enterprise pyramids assume dedicated QA. Yours is flatter:

  1. Smoke tests (most) — does the app build, do critical routes return 200, does auth redirect work
  2. Unit tests (some) — pure functions: pricing, date formatting, permission checks, Zod schemas
  3. Integration tests (few) — API routes with mocked Supabase, Stripe webhook signature validation
  4. E2E tests (minimal) — one happy-path Playwright flow: sign up → create item → delete item

Spend 80% of test-writing time on layers 1–2. They are fast to run, fast to prompt, and catch 80% of AI mistakes. E2E is expensive in time and flakes — reserve it for the revenue path only.

Time budget that does not kill flow

Target 15 minutes per feature for test scaffolding. If a test takes longer to write than the feature, you are over-testing. Snapshot entire components only when you lack time for assertions — snapshots are debt, but cheaper than zero coverage. The vibe coder’s rule: if you would manually click it three times during development, automate one of those clicks as a test.

What to test first

Prioritize by blast radius and AI failure frequency:

PriorityWhatWhy AI breaks it
P0Auth guards and RLS assumptionsClient-side-only checks, missing middleware
P0Payment and webhook handlersWrong idempotency, missing signature verify
P1Form validation schemasClient-only validation, schema drift
P1Data transforms and serializersNull access, wrong date parsing
P2UI component renderingMissing loading states — test presence, not pixels
P3Visual regressionDefer until post-launch unless brand-critical

After wiring Supabase, test RLS with two user fixtures — AI constantly writes queries that work for the logged-in user in dev but leak data cross-tenant. Use prompts from Supabase auth and database setup plus explicit test fixtures. For Next.js auth, cross-read add auth to vibe-coded Next.js app.

Mapping features to test types

Dashboard with charts: unit test data aggregation, integration test API route returns correct shape, skip chart pixel tests. User settings form: test Zod schema rejects invalid phone, test server action persists. File upload: test MIME validation and size limits — AI often skips both. Subscription billing: test webhook idempotency with duplicate event IDs.

Tools that fit the vibe coding stack

Default stack from vibe coding starter stack 2026:

  • Vitest — unit and integration; native ESM, fast watch mode in Cursor
  • Testing Library — component tests without brittle selectors
  • Playwright — one E2E spec for the money path
  • MSW — mock fetch in component tests when API is unstable

Install once, commit config, never re-litigate. Prompt: “Add Vitest to this Next.js project with one example test for lib/pricing.ts; match existing tsconfig paths.” Lock versions in package.json — AI sometimes suggests outdated testing packages.

Test runner output showing passing unit tests alongside AI-generated source files in a vibe coding project
Green tests in the sidebar mean you can prompt the next feature without manual regression clicks.

Prompting AI to write tests

AI writes decent tests when you give constraints. Bad prompt: “write tests.” Good prompt:

Write Vitest tests for lib/calculateOrderTotal.ts. Cover: empty cart, single item, discount code, tax rounding to 2 decimals, negative quantity rejection. Do not mock internal helpers. Use table-driven cases. No snapshot tests.

More templates:

  • “Add a Playwright test: user signs up with email, lands on dashboard, sees welcome text. Use test@example.com fixture. Run headless.”
  • “Test API route POST /api/webhooks/stripe with invalid signature returns 400; valid signature with fixture event returns 200.”
  • “Add tests for middleware.ts: unauthenticated request to /dashboard redirects to /login; authenticated passes through.”
  • “Write tests for formatRelativeDate: null input, today, yesterday, 7 days ago, future date throws.”

After AI writes tests, run them before accepting the diff. AI tests often assert implementation details or mock too much. Trim with code review prompts. Add to your agent rules: tests must pass before marking task complete.

Test-first for high-risk code only

Pure vibe coding is test-after. Exception: payment flows, permission systems, and data migration scripts. For those, prompt: “Write failing tests describing expected behavior, then implement until green.” TDD slows exploration but saves money on Stripe disputes.

CI without ceremony

Wire tests into Vercel preview or GitHub Actions with one job:

  1. npm ci
  2. npm run lint
  3. npm run test
  4. npm run build

Four steps. Failing preview deploy is better than failing production. Follow deploy vibe-coded app on Vercel and add the test step before build. Store test env vars in Vercel preview environment — not committed to repo.

Skip parallel browser matrices, coverage thresholds above 60%, and flaky E2E in CI until you have revenue. Add rigor when vibe engineering replaces pure vibe coding.

Anti-patterns that slow you down

  • Testing implementation, not behavior — assert outputs and side effects, not internal state
  • 100% coverage goals — breeds meaningless tests AI generates to hit a number
  • E2E for everything — slow, flaky, blocks prompt velocity
  • No tests because “it’s a prototype” — prototypes become production on Friday
  • Letting AI delete tests during refactors — add rule: “never remove tests without explicit instruction”
  • Testing third-party SDK internals — mock at boundary, trust Stripe/Supabase SDKs

When tests fail after a prompt, use debugging prompts with the failure output pasted in — faster than reverting blindly.

A weekly testing workflow for solo vibe coders

Monday: scaffold tests for last week’s features (30 min). Daily: one test per non-trivial prompt before merge. Friday: run full suite, fix flakes, delete obsolete snapshots. This rhythm adds under an hour per week and prevents weekend firefights.

Document test conventions in AGENTS.md or your system prompt templates for coding agents so every AI session respects the same rules. Include: test file naming (*.test.ts colocated), no any in test files, prefer describe/it blocks, reset mocks in beforeEach.

Tests as handoff artifacts

When you transition to a developer, tests are more valuable than comments. They encode business rules AI discovered through iteration. Export a short README: how to run tests, which fixtures need env vars, what is intentionally untested. Developers trust green CI more than “the AI said it works.”

Measuring whether your test layer is working

Track: time from prompt to confident merge (should decrease), production bugs that tests would have caught (should decrease), test suite runtime (should stay under 2 minutes for unit+integration). If suite exceeds 5 minutes, split E2E to nightly only.

Fixture data that mirrors production chaos

AI tests often use pristine fixtures — single user named “Test User” with a perfect avatar URL. Production has null avatars, unicode names, and deleted accounts referenced by foreign keys. Create fixtures/messy-users.ts with edge-case records and require AI-generated tests to import from it. Prompt: “Use fixtures from fixtures/messy-users.ts for all user-related tests; do not invent inline user objects.”

Compare tooling options in best vibe coding tools 2026 — every tool exports code that benefits from the same test discipline regardless of where it was generated.

Example test suite structure for vibe-coded Next.js

Organize tests where AI and humans find them:

lib/
  pricing.ts
  pricing.test.ts          # unit — colocated
app/
  api/
    webhooks/
      stripe/
        route.ts
        route.test.ts      # integration — colocated
tests/
  e2e/
    signup.spec.ts         # Playwright — separate folder
  fixtures/
    users.ts               # shared messy data

Prompt: “Restructure tests to match this layout; move existing tests without changing assertions.”

Testing Supabase RLS from vibe-coded apps

RLS bugs are silent until a user reports seeing someone else’s data. Test pattern:

  1. Create two test users via Supabase admin API in test setup
  2. Insert row owned by user A
  3. Query as user B’s JWT — expect empty result or permission error
  4. Run in CI against local Supabase via supabase start or test project

Prompt: “Add Vitest integration test for projects table RLS: user A creates project, user B cannot select it. Use service role for setup, anon key with user JWT for queries.”

Cross-reference Supabase setup prompts for migration patterns tests should mirror.

Preview deploy as test gate

Vercel preview URLs are integration test environments. Block merge when preview deploy fails test step. Founders skip this because “it’s just me” — until a Friday prompt breaks production. One GitHub Action or Vercel check is enough.

Minimum CI prompt: “Add GitHub Action on pull_request: install, lint, test, build. Fail on any step. Use Node 20.”

FAQ

Do I need tests if I only use Lovable or Bolt?

Hosted builders hide some failures, but custom code exports still need tests. See Lovable review — export to Cursor adds test layer before scale.

How many tests before first deploy?

Minimum: build passes, one auth test, one money-path E2E or critical API test. Expand after first paying user.

Should AI write tests before or after feature code?

After, for vibe coding speed. For payment and auth, prompt tests in the same chain as the feature — “implement X and add Vitest coverage.”

What if tests slow my Cursor agent?

Run watch mode in a terminal, not inside the agent loop. Agent reads failure output on demand. Keep unit tests under 500ms total where possible.

Tests for AI-generated code are not bureaucracy — they are permission to keep vibing. Start with Vitest on pure functions and auth, add one Playwright happy path, wire CI on preview deploys, and prompt tests with the same discipline you prompt features. Review with AI code review guide, debug failures with debugging prompts, and ship through Vercel deploy guide. Your future self — and any developer you hand off to — will thank you for fifteen minutes of tests per feature.

Leave a Reply

Your email address will not be published. Required fields are marked *