Workflow Testing

Testing with AI

AI can help draft unit tests, integration tests, edge cases, mocks, and TDD workflows. Review the requirements, run the examples, and verify that important faults fail.

Published: · Last reviewed: Oct 27 2026


Why Testing Is Different with AI

Testing requires an explicit account of expected behavior, boundaries, and failures. AI can draft that account as code, but you still need to check that each assertion follows from the requirements.

AI removes much of that friction. Given a function, AI can draft candidate tests. Given a description of failure modes, it can suggest cases to review. Given a failing test, it can propose an explanation and a fix; verify both against the requirements and the actual run.

The result can be better testing, not just faster testing: when an additional test case is cheap to draft, there is less reason to skip the awkward paths. That only holds if you review what was generated — a large suite of weak assertions gives coverage without confidence.

The Core Shift

AI-assisted testing needs both drafting and review. Check whether the proposed inputs and assertions express the intended behavior before using a passing run as evidence.


Example Environment and Scope

Checked on Node.js 24.13.0, Vitest 5.0.5, Vite 8.3.5, and TypeScript 7.0.2 in Vitest's Node environment. Install exact versions and retain the generated lockfile. These examples are not Browser Mode tests. A fresh example project can use:

npm init -y
npm install --save-dev --save-exact vitest@5.0.5 vite@8.3.5 typescript@7.0.2 @types/node@24.19.2
# Integration examples also require:
npm install --save-exact express@5.3.0 supertest@7.3.1 better-sqlite3@13.0.3 bcryptjs@3.0.3
npm install --save-dev --save-exact @types/express@5.0.6 @types/supertest@7.2.1 @types/better-sqlite3@9.6.0

Save the source and tests below, save this configuration as vitest.config.mts, then run npx vitest run. Tests are sequential within each file; each integration test creates its own database. The native SQLite package needs a supported binary or local build tools.

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: { environment: 'node', clearMocks: true, sequence: { concurrent: false } },
});

The slug, notification, profile, and rate-limiter examples use source and test files side by side in their own directories. Save the prompt's source function before running its test. Notification tests replace the email module with a factory mock; keep real transport initialization outside import-time code. Profile tests similarly replace the repository module. The calculateDiscount signature and other prompt-only fragments are inputs to a design conversation, not complete modules.

The HTTP examples are integration templates for your own app. They require src/app.ts exporting createApp(db), migrations exporting migrate(db), a users table with email and password_hash, and the registration, login, and authenticated bookmark routes described below. Place their tests and helpers as follows:

src/app.ts                 # your app, no listen() during import
src/db/migrations.ts       # your schema and migrate(db)
tests/register.test.ts
tests/helpers.ts
tests/bookmarks.test.ts

The registration contract below uses a nonempty string ID, an email, and an ISO date string in the response. Its password fixture assumes bcrypt; verify against your application's actual hasher if it uses another algorithm. These templates do not implement authentication or a production registration service. Vitest transforms TypeScript to run it; also type-check the assembled examples with your project's strict TypeScript configuration.


Part 1: Unit Tests

Small, isolated functions are a useful starting point for AI-assisted testing. The context is small and self-contained: a function goes in, a test suite comes out. That makes them the best place to start — and the easiest place to check whether the generated tests actually pin down behavior.

The Basic Prompt

Start with the simplest possible ask: paste the function, ask for tests.

You

Write unit tests for this function using Vitest:

export function slugify(text: string): string {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

Cover: normal inputs, edge cases, and anything that could realistically go wrong.

Here is a candidate suite for the stated ASCII-oriented behavior. It deliberately removes accented characters rather than transliterating them; change the requirements and expected results if your product needs Unicode slugs:

import { describe, it, expect } from 'vitest';
import { slugify } from './slugify';

describe('slugify', () => {
  // Normal inputs
  it('converts a basic phrase to a slug', () => {
    expect(slugify('Hello World')).toBe('hello-world');
  });

  it('handles multiple words', () => {
    expect(slugify('The Quick Brown Fox')).toBe('the-quick-brown-fox');
  });

  // Whitespace handling
  it('trims leading and trailing whitespace', () => {
    expect(slugify('  hello world  ')).toBe('hello-world');
  });

  it('collapses multiple spaces into one hyphen', () => {
    expect(slugify('hello   world')).toBe('hello-world');
  });

  // Special characters
  it('removes special characters', () => {
    expect(slugify('Hello, World!')).toBe('hello-world');
  });

  it('removes characters that are not word chars, spaces, or hyphens', () => {
    expect(slugify('café & crème')).toBe('caf-crme');
  });

  // Hyphen handling
  it('replaces underscores with hyphens', () => {
    expect(slugify('hello_world')).toBe('hello-world');
  });

  it('removes leading and trailing hyphens', () => {
    expect(slugify('-hello world-')).toBe('hello-world');
  });

  it('collapses consecutive hyphens', () => {
    expect(slugify('hello---world')).toBe('hello-world');
  });

  // Edge cases
  it('returns empty string for empty input', () => {
    expect(slugify('')).toBe('');
  });

  it('returns empty string for whitespace-only input', () => {
    expect(slugify('   ')).toBe('');
  });

  it('returns empty string for special characters only', () => {
    expect(slugify('!@#$%')).toBe('');
  });

  it('handles a single word', () => {
    expect(slugify('Hello')).toBe('hello');
  });

  it('preserves numbers', () => {
    expect(slugify('chapter 1 intro')).toBe('chapter-1-intro');
  });
});

Why "anything that could realistically go wrong" matters

That phrase can suggest additional cases, but it does not guarantee coverage. Name important boundaries explicitly, check the requirements, and verify that a plausible fault makes the corresponding test fail.

Generating Edge Cases Explicitly

For complex functions, ask for edge cases as a separate step before writing tests. This surfaces assumptions you didn't know you had.

You

Before writing tests for this function, list every edge case you can think of — inputs that might behave unexpectedly, boundary conditions, and failure modes. Don't write code yet.

export function calculateDiscount(
  price: number,
  quantity: number,
  couponCode?: string
): number

A good AI response surfaces cases like: negative price, zero quantity, floating point precision at exact tier boundaries, an empty string vs. undefined coupon, expired coupons if the function checks dates, very large quantities that lose precision above Number.MAX_SAFE_INTEGER. Many of these you'd miss in a first pass.

Review the List, Then Generate Tests

The two-step approach — edge cases first, code second — keeps you in control of what matters. You can delete irrelevant cases, add business-specific ones, and make the list your test plan before a line of test code exists.

Testing Pure vs. Impure Functions

Pure functions (same input → same output, no side effects) test cleanly with the pattern above. Impure functions — ones that read files, make network calls, or write to a database — need controlled dependencies. Use mocks for isolated unit tests and real test resources for integration checks. Tell AI which category you're in:

You

Write Vitest unit tests for this function. It calls an external service — mock sendEmail so tests don't send real emails. Verify it's called with the right arguments.

import { sendEmail } from './email';

export async function notifyUserOnSignup(email: string, name: string) {
  if (!email.includes('@')) throw new Error('Invalid email');
  await sendEmail({
    to: email,
    subject: 'Welcome to the platform',
    body: `Hi ${name}, thanks for signing up!`,
  });
}

The includes('@') check is a teaching fixture for branching, not production email validation. The top-level mock replaces the email export before the source module loads, and each test resets its implementation as well as call history.

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { notifyUserOnSignup } from './notify';
import { sendEmail } from './email';

vi.mock('./email', () => ({ sendEmail: vi.fn() }));

describe('notifyUserOnSignup', () => {
  beforeEach(() => {
    vi.mocked(sendEmail).mockReset();
  });

  it('calls sendEmail with correct arguments', async () => {
    const sendEmailSpy = vi.mocked(sendEmail).mockResolvedValue(undefined);

    await notifyUserOnSignup('user@example.com', 'Alice');

    expect(sendEmailSpy).toHaveBeenCalledOnce();
    expect(sendEmailSpy).toHaveBeenCalledWith({
      to: 'user@example.com',
      subject: 'Welcome to the platform',
      body: 'Hi Alice, thanks for signing up!',
    });
  });

  it('throws on invalid email', async () => {
    await expect(notifyUserOnSignup('notanemail', 'Alice'))
      .rejects.toThrow('Invalid email');
  });

  it('does not call sendEmail when email is invalid', async () => {
    const sendEmailSpy = vi.mocked(sendEmail).mockResolvedValue(undefined);

    await expect(notifyUserOnSignup('notanemail', 'Alice')).rejects.toThrow();
    expect(sendEmailSpy).not.toHaveBeenCalled();
  });

  it('propagates errors from sendEmail', async () => {
    vi.mocked(sendEmail).mockRejectedValue(new Error('SMTP timeout'));

    await expect(notifyUserOnSignup('user@example.com', 'Alice'))
      .rejects.toThrow('SMTP timeout');
  });
});

Part 2: Integration Tests

Integration tests verify that multiple pieces work together — a route handler reading from a real database, an API endpoint returning the right status code, a service composing two repositories. They catch the bugs unit tests miss.

They require explicit setup and cleanup. AI can draft that setup, but you must check the application wiring, migrations, isolation, and failure paths.

Testing an API Route

The most common integration test pattern: HTTP request in, database state or response body out. Give AI the route, the database schema, and your test framework:

You

Write integration tests for this Express route using Vitest and Supertest. Use an in-memory SQLite database for tests — set it up fresh before each test, tear it down after.

Route: POST /api/users/register

Behavior:

  • Creates a user with email and hashed password
  • Returns 201 with { id, email, createdAt }
  • Returns 400 if email is already registered
  • Returns 422 if email format is invalid
  • Returns 422 if password is under 8 characters

Schema: [paste users table schema]

import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import request from 'supertest';
import Database from 'better-sqlite3';
import { compare } from 'bcryptjs';
import { createApp } from '../src/app';
import { migrate } from '../src/db/migrations';

let db: Database.Database;
let app: ReturnType<typeof createApp>;

beforeEach(() => {
  db = new Database(':memory:');
  migrate(db);
  app = createApp(db);
});

afterEach(() => {
  db?.close();
});

describe('POST /api/users/register', () => {
  const validPayload = {
    email: 'alice@example.com',
    password: 'securepassword',
  };

  it('creates a user and returns 201 with user data', async () => {
    const res = await request(app).post('/api/users/register').send(validPayload);

    expect(res.status).toBe(201);
    expect(res.body).toMatchObject({
      email: 'alice@example.com',
    });
    expect(Object.keys(res.body).sort()).toEqual(['createdAt', 'email', 'id']);
    expect(res.body.id).toEqual(expect.any(String));
    expect(res.body.id.length).toBeGreaterThan(0);
    expect(res.body.createdAt).toEqual(expect.any(String));
    expect(Number.isFinite(Date.parse(res.body.createdAt))).toBe(true);
  });

  it('returns 400 when email is already registered', async () => {
    await request(app).post('/api/users/register').send(validPayload).expect(201);
    const res = await request(app).post('/api/users/register').send(validPayload);

    expect(res.status).toBe(400);
    expect(res.body.error).toMatch(/already/i);
  });

  it('returns 422 when email format is invalid', async () => {
    const res = await request(app)
      .post('/api/users/register')
      .send({ email: 'notanemail', password: 'securepassword' });

    expect(res.status).toBe(422);
    expect(res.body.error).toBeDefined();
  });

  it('returns 422 when password is too short', async () => {
    const res = await request(app)
      .post('/api/users/register')
      .send({ email: 'alice@example.com', password: 'short' });

    expect(res.status).toBe(422);
    expect(res.body.error).toBeDefined();
  });

  it('does not store plaintext password in database', async () => {
    await request(app).post('/api/users/register').send(validPayload).expect(201);

    const user = db.prepare('SELECT password_hash FROM users WHERE email = ?')
      .get(validPayload.email) as { password_hash: string } | undefined;
    expect(user).toBeDefined();
    if (!user) throw new Error('Registered user was not stored');
    expect(user.password_hash).not.toBe(validPayload.password);
    expect(await compare(validPayload.password, user.password_hash)).toBe(true);
    expect(await compare('wrong-password', user.password_hash)).toBe(false);
  });
});

In-Memory Databases for Tests

Using new Database(':memory:') gives you a fresh, isolated database for every test. No cleanup scripts, no shared state, no order-dependent failures. Each test is a clean slate. SQLite is not a drop-in stand-in for every production database, though: types, constraints, locking and SQL dialect differ. If production runs PostgreSQL, run the integration suite against PostgreSQL too — for example in a container — with a fresh schema or a rolled-back transaction per test.

Writing Test Helpers with AI

Repeated setup code belongs in a helper. Ask AI to generate it:

You

Create a test helper file for our API tests. It should export:

  • createTestDb() — returns a fresh in-memory SQLite db with migrations run
  • createTestApp(db) — returns the Express app wired to the test db
  • registerUser(app, overrides?) — registers a default test user, returns the response body
  • loginUser(app, email, password) — logs in and returns the JWT token
  • authHeader(token) — returns the Authorization header object
import Database from 'better-sqlite3';
import request from 'supertest';
import { createApp } from '../src/app';
import { migrate } from '../src/db/migrations';

export function createTestDb() {
  const db = new Database(':memory:');
  try { migrate(db); return db; }
  catch (error) { db.close(); throw error; }
}

export function createTestApp(db: Database.Database) {
  return createApp(db);
}

const defaultUser = {
  email: 'test@example.com',
  password: 'testpassword123',
  name: 'Test User',
};

export async function registerUser(
  app: ReturnType<typeof createApp>,
  overrides: Partial<typeof defaultUser> = {}
) {
  const payload = { ...defaultUser, ...overrides };
  const res = await request(app).post('/api/users/register').send(payload).expect(201);
  if (typeof res.body.id !== 'string' || !res.body.id ||
      typeof res.body.email !== 'string' || typeof res.body.createdAt !== 'string' ||
      !Number.isFinite(Date.parse(res.body.createdAt))) throw new Error('Invalid user response');
  return res.body as { id: string; email: string; createdAt: string };
}

export async function loginUser(
  app: ReturnType<typeof createApp>,
  email = defaultUser.email,
  password = defaultUser.password
): Promise<string> {
  const res = await request(app).post('/api/auth/login').send({ email, password }).expect(200);
  if (typeof res.body.token !== 'string' || !res.body.token.trim()) throw new Error('Missing token');
  return res.body.token;
}

export function authHeader(token: string) {
  return { Authorization: `Bearer ${token}` };
}

With helpers in place, subsequent test files become clean and expressive:

import { beforeEach, afterEach, describe, it, expect } from 'vitest';
import request from 'supertest';
import { createTestDb, createTestApp, registerUser, loginUser, authHeader } from './helpers';

let db: ReturnType<typeof createTestDb>;
let app: ReturnType<typeof createTestApp>;
let token: string;

beforeEach(async () => {
  db = createTestDb();
  app = createTestApp(db);
  await registerUser(app);
  token = await loginUser(app);
});

afterEach(() => db?.close());

describe('POST /api/bookmarks', () => {
  it('creates a bookmark for the authenticated user', async () => {
    const res = await request(app)
      .post('/api/bookmarks')
      .set(authHeader(token))
      .send({ url: 'https://example.com', title: 'Example' });

    expect(res.status).toBe(201);
    expect(res.body.data.url).toBe('https://example.com');
  });

  it('returns 401 without a token', async () => {
    const res = await request(app)
      .post('/api/bookmarks')
      .send({ url: 'https://example.com', title: 'Example' });

    expect(res.status).toBe(401);
  });
});

Part 3: TDD with AI

Test-Driven Development — write the test before the implementation — pairs surprisingly well with AI. The classic complaint about TDD is that writing tests for non-existent code is mentally exhausting. With AI, you describe the behavior in a prompt, get the test, and then ask for the implementation that passes it.

The Red-Green-Refactor Loop with AI

Here is a single-process fixed-window teaching example. It is not a distributed production abuse-control service. It uses a monotonic clock by default, copies validated configuration, and bounds key storage. Expired entries are removed on the next check; cleanup scans at most the configured capacity. Set that capacity to your resource budget. At capacity, new keys are denied until an existing window expires; active counters are retained so key rotation cannot evict them.

Step 1 — Describe the behavior, get the test:

You

Write a Vitest test for a RateLimiter class that doesn't exist yet. It should:

  • Accept a limit (max requests) and a window (time in ms)
  • Track requests per key (e.g., IP address)
  • Return { allowed: true } when under the limit
  • Return { allowed: false, retryAfter: number } when over the limit
  • Reset the count after the window expires

Use vi.useFakeTimers() with an injected test clock. Require positive safe-integer limits, milliseconds, and key capacity. Reject invalid or oversized keys. Keep at most maxKeys active keys: deny new keys at capacity without evicting active counters, and reclaim expired keys. Do not implement the class yet — just the tests.

import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { RateLimiter, type RateLimiterOptions } from './rateLimiter';

describe('RateLimiter', () => {
  beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(0); });
  afterEach(() => vi.useRealTimers());
  // Production defaults to performance.now(); tests inject the controlled clock.
  const create = (options: RateLimiterOptions) => new RateLimiter(options, () => Date.now());

  it('allows exactly the configured number of requests', () => {
    const limiter = create({ limit: 2, windowMs: 1000 });
    expect(limiter.check('a')).toEqual({ allowed: true });
    expect(limiter.check('a')).toEqual({ allowed: true });
    expect(limiter.check('a')).toEqual({ allowed: false, retryAfter: 1000 });
  });

  it('tracks keys independently', () => {
    const limiter = create({ limit: 1, windowMs: 1000 });
    expect(limiter.check('a')).toEqual({ allowed: true });
    expect(limiter.check('b')).toEqual({ allowed: true });
    expect(limiter.check('a').allowed).toBe(false);
  });

  it('blocks just before expiry and resets at the exact boundary', () => {
    const limiter = create({ limit: 1, windowMs: 1000 });
    limiter.check('a');
    vi.advanceTimersByTime(999);
    expect(limiter.check('a')).toEqual({ allowed: false, retryAfter: 1 });
    vi.advanceTimersByTime(1);
    expect(limiter.check('a')).toEqual({ allowed: true });
  });

  it('returns the exact remaining milliseconds', () => {
    const limiter = create({ limit: 1, windowMs: 5000 });
    limiter.check('a');
    vi.advanceTimersByTime(2000);
    expect(limiter.check('a')).toEqual({ allowed: false, retryAfter: 3000 });
  });

  it.each([0, -1, NaN, Infinity, 1.5, Number.MAX_SAFE_INTEGER + 1])('rejects invalid limit %s', (limit) => {
    expect(() => create({ limit, windowMs: 1000 })).toThrow(RangeError);
  });

  it.each([0, -1, NaN, Infinity, 0.5])('rejects invalid window %s', (windowMs) => {
    expect(() => create({ limit: 1, windowMs })).toThrow(RangeError);
  });

  it.each([0, -1, NaN, Infinity, 1.5])('rejects invalid key capacity %s', (maxKeys) => {
    expect(() => create({ limit: 1, windowMs: 1000, maxKeys })).toThrow(RangeError);
  });

  it('denies new keys at capacity without evicting an active limit', () => {
    const limiter = create({ limit: 1, windowMs: 1000, maxKeys: 1 });
    limiter.check('a');
    expect(limiter.check('b')).toEqual({ allowed: false, retryAfter: 1000 });
    expect(limiter.check('a').allowed).toBe(false);
    vi.advanceTimersByTime(1000);
    expect(limiter.check('b')).toEqual({ allowed: true });
  });

  it('reclaims expired keys during repeated admission', () => {
    const limiter = create({ limit: 1, windowMs: 1, maxKeys: 2 });
    for (let n = 0; n < 100; n++) {
      expect(limiter.check(`key-${n}`)).toEqual({ allowed: true });
      vi.advanceTimersByTime(1);
    }
  });

  it.each(['', 'x'.repeat(129)])('rejects invalid keys', (key) => {
    expect(() => create({ limit: 1, windowMs: 1000 }).check(key)).toThrow(TypeError);
  });

  it('copies the supplied policy', () => {
    const options = { limit: 1, windowMs: 1000, maxKeys: 1 };
    const limiter = create(options);
    options.limit = 100;
    limiter.check('a');
    expect(limiter.check('a').allowed).toBe(false);
  });

  it('rejects backward or nonfinite injected time', () => {
    let now = 10;
    const limiter = new RateLimiter({ limit: 1, windowMs: 1000 }, () => now);
    limiter.check('a');
    now = 9;
    expect(() => limiter.check('a')).toThrow('Invalid clock');
    now = NaN;
    expect(() => limiter.check('a')).toThrow('Invalid clock');
  });
});

Step 2 — Run the tests (they fail — that's correct).

Step 3 — Ask for the implementation that passes them:

You

Implement the RateLimiter class to make these tests pass: [paste tests above]

TypeScript. No external dependencies.

export interface RateLimiterOptions {
  limit: number;
  windowMs: number;
  maxKeys?: number;
}

type CheckResult =
  | { allowed: true }
  | { allowed: false; retryAfter: number };

export class RateLimiter {
  private readonly store = new Map<string, { count: number; windowStart: number }>();
  private readonly limit: number;
  private readonly windowMs: number;
  private readonly maxKeys: number;
  private lastNow = -Infinity;

  constructor(options: RateLimiterOptions, private readonly now = () => performance.now()) {
    const { limit, windowMs, maxKeys = 1000 } = options;
    if (![limit, windowMs, maxKeys].every((n) => Number.isSafeInteger(n) && n > 0)) {
      throw new RangeError('Expected positive safe integers');
    }
    // Copy values so later caller mutations cannot change the policy.
    this.limit = limit;
    this.windowMs = windowMs;
    this.maxKeys = maxKeys;
  }

  check(key: string): CheckResult {
    if (typeof key !== 'string' || key.length === 0 || key.length > 128) {
      throw new TypeError('Expected a key of 1-128 UTF-16 code units');
    }
    const now = this.now();
    if (!Number.isFinite(now) || now < this.lastNow) throw new Error('Invalid clock');
    this.lastNow = now;

    // Bounded O(maxKeys) scan: remove expired entries before admitting a new key.
    for (const [id, entry] of this.store) {
      if (now - entry.windowStart >= this.windowMs) this.store.delete(id);
    }
    const entry = this.store.get(key);
    if (!entry) {
      if (this.store.size >= this.maxKeys) {
        let remaining = this.windowMs;
        for (const e of this.store.values()) remaining = Math.min(remaining, this.windowMs - (now - e.windowStart));
        return { allowed: false, retryAfter: Math.ceil(remaining) };
      }
      this.store.set(key, { count: 1, windowStart: now });
      return { allowed: true };
    }
    if (entry.count < this.limit) {
      entry.count++;
      return { allowed: true };
    }
    return { allowed: false, retryAfter: Math.ceil(this.windowMs - (now - entry.windowStart)) };
  }
}

Step 4 — Run the tests again and inspect failures against the requirements. The tests above check exact expiry, retry timing, invalid configuration, capacity denial, reclamation, and clock errors. For multiple workers or replicas, use a shared limiter with atomic updates and test its concurrency and failure policy separately.

Tests as a Spec

The TDD loop uses tests as an executable part of the specification. Tests capture selected examples of the requirements. They can omit boundaries, state lifecycles, concurrency, and security rules. Review those requirements independently and use fault injection or mutation testing to check whether important mistakes are detected.


Part 4: Mocking and Isolation

Isolated tests control dependencies so unrelated services do not determine the result. Use factory mocks or injected dependencies for unit tests, and dedicated real resources for integration checks. State what should be replaced and which interactions matter.

Mocking Modules

You

Write tests for this function. Mock the ../db/userRepo module — I don't want a real database in these tests. Verify the function calls the repo with the right arguments and handles the case where the user isn't found.

import { userRepo } from '../db/userRepo';

export async function getUserProfile(userId: string) {
  const user = await userRepo.findById(userId);
  if (!user) throw new Error('User not found');
  return { id: user.id, name: user.name, email: user.email };
}
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { getUserProfile } from './getUserProfile';

vi.mock('../db/userRepo', () => ({
  userRepo: {
    findById: vi.fn(),
  },
}));

import { userRepo } from '../db/userRepo';

describe('getUserProfile', () => {
  beforeEach(() => {
    vi.mocked(userRepo.findById).mockReset();
  });

  it('returns formatted profile when user exists', async () => {
    const mockUser = { id: '123', name: 'Alice', email: 'alice@example.com', passwordHash: 'x' };
    vi.mocked(userRepo.findById).mockResolvedValue(mockUser);

    const result = await getUserProfile('123');

    expect(result).toEqual({
      id: '123',
      name: 'Alice',
      email: 'alice@example.com',
    });
  });

  it('calls userRepo.findById with the correct userId', async () => {
    vi.mocked(userRepo.findById).mockResolvedValue(
      { id: '456', name: 'Bob', email: 'bob@example.com', passwordHash: 'x' }
    );

    await getUserProfile('456');

    expect(userRepo.findById).toHaveBeenCalledWith('456');
  });

  it('throws when user is not found', async () => {
    vi.mocked(userRepo.findById).mockResolvedValue(null);

    await expect(getUserProfile('nonexistent')).rejects.toThrow('User not found');
  });

  it('does not expose passwordHash in the result', async () => {
    vi.mocked(userRepo.findById).mockResolvedValue(
      { id: '123', name: 'Alice', email: 'alice@example.com', passwordHash: 'secret' }
    );

    const result = await getUserProfile('123');

    expect(result).not.toHaveProperty('passwordHash');
  });

  it('propagates repository failures', async () => {
    vi.mocked(userRepo.findById).mockRejectedValue(new Error('Database unavailable'));
    await expect(getUserProfile('123')).rejects.toThrow('Database unavailable');
  });
});

Generating a Full Mock from a Type

When you have a complex interface and need a realistic-looking fake for tests, paste the type and ask for a factory:

You

Write a createMockUser factory function for tests. It should return a valid user object matching this interface, with sensible defaults, and accept an optional overrides parameter:

interface User {
  id: string;
  email: string;
  name: string;
  role: 'admin' | 'member' | 'viewer';
  createdAt: Date;
  lastLoginAt: Date | null;
  isEmailVerified: boolean;
}
import type { User } from '../src/types';

let idCounter = 0;

export function createMockUser(overrides: Partial<User> = {}): User {
  idCounter++;
  return {
    id: `user-${idCounter}`,
    email: `user${idCounter}@example.com`,
    name: `Test User ${idCounter}`,
    role: 'member',
    createdAt: new Date('2024-01-01T00:00:00Z'),
    lastLoginAt: null,
    isEmailVerified: true,
    ...overrides,
  };
}

// Reset between test runs if needed
export function resetFactoryCounters() {
  idCounter = 0;
}

Usage in tests becomes readable and explicit:

const admin = createMockUser({ role: 'admin', isEmailVerified: true });
const unverified = createMockUser({ isEmailVerified: false });
const neverLoggedIn = createMockUser({ lastLoginAt: null });

Part 5: Coverage and Review

Coverage tools tell you which lines were executed. They don't tell you whether the tests were any good. Use AI for both: generating tests toward coverage gaps, and reviewing what was generated.

Filling Coverage Gaps

You

Here's a function and its current tests. The coverage report shows lines 12–18 are uncovered (the error handling branch). Write additional tests that cover the missing lines.

[paste function + existing tests + coverage output]

This is more useful than chasing 100% coverage blindly. You're targeting specific gaps with tests that have a reason to exist — not padding for the metric.

Asking AI to Review Its Own Tests

AI-generated tests can have blind spots — testing implementation details, writing assertions that always pass, or missing the actual behavior under test. Build review into the workflow:

You

Review these tests critically. Look for:

  • Tests that would pass even if the implementation were completely wrong
  • Missing assertions (tests that call the function but don't assert enough about the output)
  • Tests that depend on implementation details instead of behavior
  • Edge cases that aren't covered
  • Duplicate tests that cover the same path

[paste generated tests]

Treat the critique as a checklist to verify, not a verdict. Typical findings: an assertion like expect(result).toBeDefined() that passes even when result is wrong; a test that mocks so much there's nothing real being tested; a missing assertion on the return value shape.

The Mutation Testing Prompt

For critical functions, ask AI to mentally mutate the implementation and check if the tests would catch it: "If I changed this condition from > to >=, which of these tests would fail? If none would, what test should I add?" This surfaces tests that provide false confidence. For code where it matters, confirm the answer with a mutation-testing tool such as Stryker, which actually applies the mutations and runs your suite. Follow the pinned mutation-testing experiment to see a covered boundary fault survive a weak assertion and then get caught by a requirement-based check.


Part 6: Prompt Patterns That Work

The quality of AI-generated tests depends heavily on the prompt. These patterns make your requirements easier to inspect; verify the generated result rather than assuming prompt wording guarantees quality.

Specify the Framework Explicitly

Don't assume AI knows your stack. Always name the framework and version if it matters:

// Good
"Write tests using Vitest and Testing Library."
"Write tests using Jest with ts-jest. We're on Jest 30."
"Write integration tests using Supertest. The app is Express 5."

// Too vague
"Write tests for this function."

Describe What Counts as Success

"Test this function" produces generic tests. "Test that it returns X when Y, throws Z when W, and calls Q with R" produces useful ones:

You

Write tests for applyPromoCode(cart, code). Success means:

  • Valid SAVE20 code applies a 20% discount to cart total
  • Discount is applied to items, not shipping
  • Already-discounted items don't get double-discounted
  • Expired codes throw PromoExpiredError
  • Unknown codes throw PromoNotFoundError
  • Codes are case-insensitive

Use "Given / When / Then" Language

Structured descriptions map cleanly to test cases:

You

Write tests in Given/When/Then structure:

  • Given an authenticated user, when they delete their own post, then the post is removed and they receive 204
  • Given an authenticated user, when they try to delete another user's post, then they receive 403
  • Given an unauthenticated request, when they try to delete any post, then they receive 401
  • Given an authenticated user, when they try to delete a post that doesn't exist, then they receive 404

Ask for a Test Plan Before the Tests

For complex areas, generate a list of what should be tested first, confirm it looks right, then ask for the code:

You

Before writing tests for the checkout function, list every scenario that should be tested. Include happy paths, failure modes, and edge cases. Don't write code yet.

Review the list. Add anything domain-specific the AI missed. Delete anything irrelevant. Then: "Now write the tests for items 1, 2, 3, 5, 7, and 9."


Testing as a First-Class Workflow

Build a suite around risky behavior and independently reviewed requirements. Generated code is a draft; coverage and a green run do not establish that its assertions detect the mistakes you care about.

Write the prompt, review the tests, run the tests, and check that meaningful faults fail. A green suite supports only the behaviors it actually asserts.


Testing with AI — Summary

For a controlled capacity experiment, follow LLM load testing with k6: run your app against a model mock and record latency, errors and dropped iterations at fixed arrival rates.

This guide is part of the quality assurance path: Testing → Code Review → Debugging. Chapter 9 of the manual introduces the testing fundamentals this guide builds on.

Sources and Review Scope

Primary sources checked Oct 27 2026: the Vitest 5 migration guide, module mocking guide, mock utility API, and bcrypt.js API. Exact dependency versions above were checked in the npm registry. In Vitest 5, clearing mock history before each test is enabled by default; it does not reset implementations. Factory mocks and explicit resets here make the isolation contract visible. Spying on a native module namespace has Browser Mode restrictions.

The examples were run with real Vitest and strict TypeScript checks. HTTP templates were exercised against a purpose-built local fixture with real Express, Supertest, SQLite, and bcrypt; that does not validate your own app, production database, email transport, authentication design, or Browser Mode. Review by Nov 26 2026, or sooner when a pinned dependency, mock API, or application contract changes.

Related Guides

Debugging with AI

When a test fails and you need to investigate — the systematic debugging workflow, stack traces, async bugs, and a 7-prompt library.

AI Code Review: From Diff to Production Confidence

Generate test ideas directly from a diff — and use AI to review whether your test coverage matches the real risk surface.

AI Evals in Production

Move from test generation to production quality control with eval datasets, scoring, and CI quality gates.

When AI Gets It Wrong: A Field Guide

AI's nine most common failure modes in code generation, including how tests specifically can appear to pass while masking real bugs.

AI Regression Test Plan Template

A copy-paste template for scoping what could break before you merge, not after a bug report.

→
Back to Home