Recipes · coding

Unit Test Generator

Genera tests unitarios completos para una función o módulo. Cubre happy paths, edge cases y casos de error con el framework de tu elección.

claude-sonnet-4-5codingtestingvitestjestautomationActualizado 2026-04-23

System Prompt

You are an expert in software testing. Given a function or module, generate
comprehensive unit tests that cover:

1. Happy paths — the expected normal usage.
2. Edge cases — boundary values, empty inputs, maximum values.
3. Error cases — invalid inputs, thrown exceptions, rejected promises.

## Rules
- Use the testing framework and assertion style specified by the user.
- Import only what is necessary. Do not import unused modules.
- Each test must have a descriptive name following the pattern:
  "should [expected behavior] when [condition]"
- Group related tests using describe blocks.
- Mock external dependencies (network, filesystem, database) — do not make
  real calls in unit tests.
- Do not generate tests for implementation details. Test behavior, not code.
- If the function has side effects, verify them explicitly.

User Prompt template

Generate unit tests for the following function.

Framework: {{FRAMEWORK}} (e.g., Vitest, Jest, Node test runner)
Language: {{LANGUAGE}}
{{#if mock_library}}Mock library: {{MOCK_LIBRARY}}{{/if}}

Function to test:
```{{LANGUAGE}}
{{SOURCE_CODE}}
```

{{#if existing_tests}}
Existing tests (do not duplicate):
```
{{EXISTING_TESTS}}
```
{{/if}}

Implementación (TypeScript)

typescript
import Anthropic from "@anthropic-ai/sdk";
import { readFileSync } from "fs";
 
const client = new Anthropic();
 
async function generateTests(options: {
  sourceFile: string;
  framework?: string;
  language?: string;
}): Promise<string> {
  const { sourceFile, framework = "Vitest", language = "TypeScript" } = options;
  const sourceCode = readFileSync(sourceFile, "utf-8");
 
  const response = await client.messages.create({
    model: "claude-sonnet-4-5",
    max_tokens: 4096,
    system: TEST_GENERATOR_SYSTEM_PROMPT,
    messages: [
      {
        role: "user",
        content: [
          `Generate unit tests for the following function.`,
          `Framework: ${framework}`,
          `Language: ${language}`,
          `\nFunction to test:\n\`\`\`${language.toLowerCase()}\n${sourceCode}\n\`\`\``,
        ].join("\n"),
      },
    ],
  });
 
  return response.content
    .filter((b): b is Anthropic.TextBlock => b.type === "text")
    .map((b) => b.text)
    .join("");
}

Ejemplo de output esperado

Para esta función:

typescript
export function clamp(value: number, min: number, max: number): number {
  if (min > max) throw new RangeError("min must be <= max");
  return Math.min(Math.max(value, min), max);
}

El modelo debería generar:

typescript
import { describe, it, expect } from "vitest";
import { clamp } from "./clamp";
 
describe("clamp", () => {
  describe("happy paths", () => {
    it("should return the value when it is within the range", () => {
      expect(clamp(5, 0, 10)).toBe(5);
    });
 
    it("should return min when value is below the range", () => {
      expect(clamp(-5, 0, 10)).toBe(0);
    });
 
    it("should return max when value is above the range", () => {
      expect(clamp(15, 0, 10)).toBe(10);
    });
  });
 
  describe("edge cases", () => {
    it("should return the value when it equals min", () => {
      expect(clamp(0, 0, 10)).toBe(0);
    });
 
    it("should return the value when it equals max", () => {
      expect(clamp(10, 0, 10)).toBe(10);
    });
 
    it("should work with negative ranges", () => {
      expect(clamp(-3, -10, -1)).toBe(-3);
    });
 
    it("should work when min equals max", () => {
      expect(clamp(5, 7, 7)).toBe(7);
    });
  });
 
  describe("error cases", () => {
    it("should throw RangeError when min is greater than max", () => {
      expect(() => clamp(5, 10, 0)).toThrow(RangeError);
      expect(() => clamp(5, 10, 0)).toThrow("min must be <= max");
    });
  });
});

Variaciones del prompt

Para funciones async / API calls

Añade al system prompt:

For async functions:
- Use async/await in tests.
- Mock HTTP calls with the mock library provided.
- Test both successful and failed network responses.
- Verify loading states if the function emits them.

Para React components (con Testing Library)

Framework: Vitest + @testing-library/react
Generate tests that:
- Render the component and verify its initial state.
- Simulate user interactions (click, type, submit).
- Verify the component's output, not its internal state.
- Mock all API calls — do not make real requests.

Pasa el contexto del archivo completo (no solo la función aislada) cuando la función dependa de tipos o constantes definidas en el mismo archivo. El modelo genera tests más precisos con más contexto.

Integración en workflow

bash
# Genera tests para todos los archivos sin test
for file in src/**/*.ts; do
  test_file="${file%.ts}.test.ts"
  if [ ! -f "$test_file" ]; then
    echo "Generating tests for $file..."
    npx tsx scripts/generate-tests.ts "$file" > "$test_file"
  fi
done