test-generator
БесплатноБез исполняемых скриптовНе проверенGenerate unit, integration, and end-to-end tests for existing code. Use when a user asks to write tests, add test coverage, create unit tests, generate…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Test Generator
Overview
Automatically generate comprehensive tests for existing source code. This skill analyzes functions, classes, and modules to produce well-structured test suites with meaningful assertions, edge case coverage, and proper mocking. It supports multiple frameworks and test types (unit, integration, e2e).
Instructions
When a user asks you to generate tests for their code, follow these steps:
Step 1: Analyze the target code
Read the source file(s) and identify:
- Functions/methods to test, their signatures, parameters, and return types
- Dependencies that need mocking (database calls, API requests, file I/O)
- Edge cases — null inputs, empty arrays, boundary values, error paths
- Side effects — state mutations, event emissions, DOM changes
Step 2: Detect the testing framework
Check the project for existing test setup:
# Check package.json for JS/TS projects
cat package.json | grep -E "jest|vitest|playwright|cypress|mocha|testing-library"
# Check for Python test frameworks
cat requirements.txt pyproject.toml setup.cfg 2>/dev/null | grep -E "pytest|unittest|hypothesis"
# Check for existing test config
ls jest.config* vitest.config* pytest.ini conftest.py .pytest.ini setup.cfg 2>/dev/null
If no framework is detected, recommend based on the project:
- React/Next.js: Vitest + React Testing Library
- Node.js/Express: Jest or Vitest
- Python: Pytest
- E2E/browser: Playwright
Step 3: Generate the test file
Create tests following the framework conventions:
Naming: Place test files next to source files or in a __tests__/tests directory matching the project convention. Use *.test.ts, *.spec.ts, test_*.py, or *_test.py.
Structure each test with:
- Arrange — set up inputs, mocks, and preconditions
- Act — call the function or perform the action
- Assert — verify the output, side effects, or state changes
For each function, generate tests covering:
- Happy path with typical inputs
- Edge cases (empty input, null, zero, max values)
- Error handling (invalid input, thrown exceptions)
- Boundary conditions
Step 4: Set up mocks and fixtures
Mock external dependencies to isolate the unit under test:
JavaScript/TypeScript (Jest/Vitest):
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { processOrder } from './order-service';
import { db } from './database';
import { sendEmail } from './email-service';
vi.mock('./database');
vi.mock('./email-service');
describe('processOrder', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should save the order and send confirmation email', async () => {
const mockOrder = { id: 'ord_123', items: [{ sku: 'WIDGET-A', qty: 2 }], total: 49.98 };
vi.mocked(db.orders.create).mockResolvedValue(mockOrder);
vi.mocked(sendEmail).mockResolvedValue({ delivered: true });
const result = await processOrder({ items: [{ sku: 'WIDGET-A', qty: 2 }] });
expect(db.orders.create).toHaveBeenCalledOnce();
expect(sendEmail).toHaveBeenCalledWith(expect.objectContaining({ orderId: 'ord_123' }));
expect(result.id).toBe('ord_123');
});
});
Python (Pytest):
import pytest
from unittest.mock import patch, MagicMock
from order_service import process_order
@pytest.fixture
def mock_db():
with patch('order_service.db') as mock:
mock.orders.create.return_value = {"id": "ord_123", "total": 49.98}
yield mock
def test_process_order_saves_and_sends_email(mock_db):
result = process_order(items=[{"sku": "WIDGET-A", "qty": 2}])
mock_db.orders.create.assert_called_once()
assert result["id"] == "ord_123"
def test_process_order_rejects_empty_items():
with pytest.raises(ValueError, match="at least one item"):
process_order(items=[])
Step 5: Add integration and e2e tests if requested
Integration tests — test multiple modules together with real (or test) databases:
- Use test containers or in-memory databases
- Test API routes end-to-end through the HTTP layer
- Verify database state after operations
E2E tests (Playwright):
import { test, expect } from '@playwright/test';
test('user can add item to cart and checkout', async ({ page }) => {
await page.goto('/products');
await page.getByTestId('product-widget-a').click();
await page.getByRole('button', { name: 'Add to Cart' }).click();
await page.goto('/cart');
await expect(page.getByTestId('cart-item')).toHaveCount(1);
await expect(page.getByTestId('cart-total')).toContainText('$24.99');
await page.getByRole('button', { name: 'Checkout' }).click();
await expect(page).toHaveURL(/\/checkout/);
});
Step 6: Verify and report coverage
Run the tests and report results:
# JavaScript (once: npm i -D @vitest/coverage-v8)
npx vitest run --coverage
# Python (once: pip install pytest-cov)
pytest --cov=src --cov-report=term-missing
Repo
Установить test-generator в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл test-generator?
Generate unit, integration, and end-to-end tests for existing code. Use when a user asks to write tests, add test coverage, create unit tests, generate integration tests, build e2e tests, improve code coverage, write specs, or add testing to a project. Supports Jest, Vitest, Pytest, Playwright, React Testing Library, and Cypress. Analyzes code to produce meaningful assertions, edge cases, and mock setups.
Как установить скилл test-generator?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл test-generator запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic