How to Generate Automated Tests with Claude Code (Jest, Pytest, Vitest)
Most projects have far less than ideal test coverage. Not because the devs don't know that testing is important -- they do. The problem is that writing tests is tedious, takes time, and when a deadline hits, tests are the first to be cut.
The Claude Code solves this problem. It analyzes your existing code, identifies critical paths, edge cases and points of failure, and generates complete test suites in seconds. Not generic tests -- tests that actually cover the logic of your code.
In this guide, you will see how to generate tests with the most popular frameworks (Jest, Vitest, Pytest, Cypress), how to go from 0 to 80% coverage, and how to use TDD with Claude Code to write better code from scratch.
1. Why use AI to generate tests
Generating tests with AI is not "dev laziness". It is a pragmatic decision. See the numbers:
- Time:Writing tests manually takes on average 30-50% of the total development time. With Claude Code, it drops to 5-10%
- Coverage:devs tend to test the "happy path" and forget about edge cases. The Claude Code identifies scenarios you didn't think of
- Consistency:Generated tests follow the same pattern -- naming conventions, structure, assertions. No style variation between devs
- Legacy code:Adding tests to existing code without tests is the most powerful use case. Claude Code reads the function and generates complete coverage
Actual data:In projects where we used Claude Code to generate legacy code tests, coverage went from 12% to 78% in a single day of work. Manually, this would take weeks.
The crux: AI-generated tests are aexcellent starting point, not the final product. You should always review to ensure that the tests validate behavior, not just that the code runs without error.
2. Unit tests with Jest and Vitest
Generating tests for existing function
Let's say you have this function without tests:
Claude Code generates:
Note how Claude Code automatically identified: coupon case sensitivity, rounding of decimals, zero vs negative price. These are edge cases that many devs forget to test.
Generating tests for entire module
Claude Code scans the folder, identifies which files already have tests, and generates only the missing ones. It respects the design pattern -- if your existing tests usedescribe/it, it follows the same style.
3. Testing with Pytest (Python)
For Python projects, Claude Code generates tests with Pytest using fixtures, tometerize and mocking.
Claude Code used@pytest.mark.tometrizeto avoid duplication of tests, fixtures for dependency injection, and even tested the database failure scenario -- verifying that the welcome email is not sent if the registration fails.
That up there? Skills do automatically.
Every technique you're reading about can be turned into a skill — a command that Claude executes perfectly, every time. The Mega Bundle has 748+ ready-made skills for marketing, dev, SEO, copy and more.
Ver Skills Prontas — $94. Integration tests
Integration tests verify that multiple nodes work together. Claude Code generates tests that raise real dependencies (database, APIs) or use test containers.
5. e2e Tests with Cypress and Playwright
For end-to-end testing, Claude Code generates scripts that simulate the real user navigating through the application.
6. Coverage analysis: from 0 to 80%
Claude Code doesn't just generate tests -- it analyzes your current coverage and identifies exactly where the gaps are.
[Executando: npx vitest run --coverage]
[Coverage atual: 34%]
Arquivos com menor coverage:
src/services/payment.ts -- 8%
src/utils/validation.ts -- 12%
src/middleware/auth.ts -- 15%
Gerando testes to esses 3 arquivos...
The recommended workflow:
- Rotate
coverageto see the current status - Ask Claude Code to focus on files with less coverage
- Review the generated tests
- Run coverage again to check the impact
- Repeat until you reach the goal
7. TDD with Claude Code
Test-Driven Development with Claude Code reverses the traditional test generation flow. Instead of "I have code, generate tests", you say "I have requirements, generate tests, then implement".
The Red-Green-Refactor cycle with AI
> preciso de uma funcao que valide CPF. gere os testes primeiro, sem implementar a funcao. cenarios: CPF valido, invalido, formatado, sem formatacao, sequencias repetidas
# Passo 2: GREEN -- implemente o minimo
> agora implemente a funcao validateCPF que faz todos os testes passarem
# Passo 3: REFACTOR -- melhore o codigo
> refatore a implementacao to ser mais legivel e performatica, sem quebrar os testes
This approach ensures that your tests reflectrequirements, not the implementation. If you generate tests after the code, there is a risk that the tests will be "tainted" by the implementation -- testing how the code works, not what it is supposed to do.
8. Ready-made testing skills
The Dev skills package includes specialized skills for generating tests:
| Skill | What it does |
|---|---|
/test-unit | Generates unit tests for a specific file or function |
/test-integration | Generates integration tests with database setup and APIs |
/test-e2e | Generate end-to-end tests with Playwright or Cypress |
/test-coverage | Analyzes coverage and generates tests for gaps |
/test-api | Generates tests for REST/GraphQL endpoints |
/tdd | Starts TDD cycle: generates tests from requirements |
Advanced Claude Code Configuration Guide
To get the most out of Claude Code, configure these 5 elements:
1. CLAUDE.md Otimizado
The CLAUDE.md file at the project root defines how Claude behaves. A well-crafted CLAUDE.md can double the quality of outputs. Include:
- Tech stack: "This project uses Next.js 14, TypeScript, Tailwind CSS, Supabase"
- Conventions: "Use single quotes, indent with 2 spaces, no semicolons"
- Architecture: "Components in /src/components, API routes in /src/app/api"
- Constraints: "Never use any em TypeScript, nunca use var, always use const"
- Tests: "Tests with Vitest em __tests__/, minimum coverage 80%"
2. Essential MCP Servers
Connect at least these 5 MCP servers: GitHub (PRs and issues), PostgreSQL (direct queries), Slack (notifications), web-search (search) e filesystem (secure file access). With these 5, Claude Code becomes a command center for the entire project.
3. Hooks for Automation
Set up hooks that trigger automatically: pre-commit (lint + format), post-edit (testes relacionados) e pre-push (build completo). This ensures all Claude-generated code passes validation before going to the repository.
4. Custom Slash Commands
Create commands for recurring tasks: /review (code review), /test (generate tests), /deploy (deploy), /doc (generate documentation). Each command saves 5-10 minutes per use — over the course of a month, that's hours.
5. Right Model for Each Task
Use Haiku for simple tasks (classification, formatting — minimum cost), Sonnet for daily coding (best cost-benefit) e Opus for critical decisions (architecture, security, complex refactoring). This strategy reduces costs by 60-70% without losing quality where it matters.
Stop doing it by hand. Let the skills work.
Professionals who use skills deliver 3x faster. It's not theory — it's 748+ skills tested on real projects, organized by area. Install once, use forever.
Get the Mega Bundle — $9FAQ
Yes. This is one of the best use cases. You point Claude Code to a file or module without tests and ask it to generate full coverage. It analyzes the function, identifies inputs, outputs, edge cases and generates unit tests covering the happy path, expected errors and limit cases. Works with Jest, Vitest, Pytest, Go testing and any other framework.
The tests generated by Claude Code are an excellent starting point. They cover the most common main scenarios and edge cases. However, you should always review to ensure that the tests validate the correct behavior (not just that the code runs without error). Tests that only verify that the function returns something, without validating what it returns, give a false sense of security.
Yes. The ideal workflow is: you describe the desired behavior, Claude Code generates the tests first (which will fail), then you ask it to implement the code that makes the tests pass. This ensures that the tests reflect the requirements, not the implementation. Claude Code understands the red-green-refactor cycle and generates tests before code when requested.