Complete Guide dengan Claude Code
Pelajari tentang complete guide menggunakan Claude Code. Dilengkapi tips praktis dan contoh kode.
Design and Implement Your Test Strategy with Claude Code
We all know tests should be written, but deciding what to test and how far to go is often the hard part. With Claude Code, you can efficiently design and implement a strategic test plan based on the testing pyramid.
The Testing Pyramid in Practice
> Propose a test strategy for the project.
> Based on the testing pyramid, organize the ratio
> and scope of unit tests, integration tests, and E2E tests.
| Test Type | Ratio | Scope | Tool |
|---|---|---|---|
| Unit Tests | 70% | Business logic, utilities | Vitest |
| Integration Tests | 20% | API, DB integration, components | Vitest + Testing Library |
| E2E Tests | 10% | Key user flows | Playwright |
Auto-Generating Unit Tests
> Create unit tests for all functions under src/services/.
> Cover success cases, error cases, and boundary values.
> Target 80%+ coverage.
// src/services/pricing.ts
export function calculatePrice(
basePrice: number,
quantity: number,
discountRate: number
): number {
if (quantity < 0) throw new Error("Quantity must be 0 or greater");
if (discountRate < 0 || discountRate > 1) {
throw new Error("Discount rate must be between 0 and 1");
}
const subtotal = basePrice * quantity;
return Math.round(subtotal * (1 - discountRate));
}
// __tests__/services/pricing.test.ts
import { describe, it, expect } from "vitest";
import { calculatePrice } from "../../services/pricing";
describe("calculatePrice", () => {
// Success cases
it("returns base price multiplied by quantity", () => {
expect(calculatePrice(100, 5, 0)).toBe(500);
});
it("applies the discount", () => {
expect(calculatePrice(1000, 1, 0.1)).toBe(900);
});
it("rounds decimal places correctly", () => {
expect(calculatePrice(333, 3, 0.1)).toBe(899);
});
// Boundary values
it("returns 0 for quantity of 0", () => {
expect(calculatePrice(100, 0, 0)).toBe(0);
});
it("returns 0 for 100% discount rate", () => {
expect(calculatePrice(100, 5, 1)).toBe(0);
});
// Error cases
it("throws error for negative quantity", () => {
expect(() => calculatePrice(100, -1, 0)).toThrow("Quantity must be 0 or greater");
});
it("throws error for out-of-range discount rate", () => {
expect(() => calculatePrice(100, 1, 1.5)).toThrow("Discount rate must be between 0 and 1");
expect(() => calculatePrice(100, 1, -0.1)).toThrow("Discount rate must be between 0 and 1");
});
});
Generating Integration Tests
Generate integration tests for API endpoints.
> Create integration tests for the /api/orders endpoint.
> Test actual CRUD operations using a test database.
> Ensure test data doesn't interfere between tests.
import { describe, it, expect, beforeEach, afterAll } from "vitest";
import request from "supertest";
import { app } from "../../app";
import { prisma } from "../../lib/prisma";
describe("Orders API Integration", () => {
beforeEach(async () => {
await prisma.order.deleteMany();
await prisma.user.upsert({
where: { id: "test-user" },
update: {},
create: { id: "test-user", email: "[email protected]", name: "Test" },
});
});
afterAll(async () => {
await prisma.$disconnect();
});
it("creates an order via POST /api/orders", async () => {
const res = await request(app)
.post("/api/orders")
.set("Authorization", "Bearer test-token")
.send({
items: [{ productId: "P1", quantity: 2, price: 1000 }],
});
expect(res.status).toBe(201);
expect(res.body.data.id).toBeDefined();
expect(res.body.data.totalAmount).toBe("2000");
});
it("retrieves order list via GET /api/orders", async () => {
// Create test data
await prisma.order.create({
data: {
userId: "test-user",
totalAmount: 5000,
status: "confirmed",
},
});
const res = await request(app)
.get("/api/orders")
.set("Authorization", "Bearer test-token");
expect(res.status).toBe(200);
expect(res.body.data).toHaveLength(1);
});
});
Generating E2E Tests
Test key user flows with Playwright.
> Create Playwright E2E tests for the user registration
> through login flow.
import { test, expect } from "@playwright/test";
test.describe("User Registration and Login Flow", () => {
test("from new user registration to dashboard display", async ({ page }) => {
// Navigate to registration page
await page.goto("/register");
await expect(page.getByRole("heading", { name: "Sign Up" })).toBeVisible();
// Fill in the form
await page.getByLabel("Email").fill("[email protected]");
await page.getByLabel("Password").fill("SecurePass123");
await page.getByLabel("Confirm Password").fill("SecurePass123");
// Submit registration
await page.getByRole("button", { name: "Sign Up" }).click();
// Redirect to dashboard
await expect(page).toHaveURL("/dashboard");
await expect(page.getByText("Welcome")).toBeVisible();
});
test("shows error for invalid email address", async ({ page }) => {
await page.goto("/register");
await page.getByLabel("Email").fill("invalid-email");
await page.getByRole("button", { name: "Sign Up" }).click();
await expect(page.getByText("Please enter a valid email address")).toBeVisible();
});
});
Improving Test Coverage
> Generate a test coverage report and add tests
> to files with low coverage.
> Target 80%+.
# Commands Claude Code would run
npx vitest --coverage --run
For test-first development with TDD, see TDD and Claude Code. For automated test execution in CI/CD, see the CI/CD Pipeline Guide. For using tests in debugging, also check out the Complete Debugging Guide.
Summary
Building a test strategy hinges on deciding “what to test and at what level.” When you guide Claude Code with the testing pyramid in mind, it can efficiently build an effective test suite. Start with unit tests and gradually expand your coverage.
For test framework details, refer to the official Vitest documentation. For Claude Code, see the official Anthropic documentation.
Related Posts
Setup MCP Server Claude Code dan Use Case Praktis
Panduan lengkap tentang kemampuan MCP server Claude Code. Pelajari cara menghubungkan tool eksternal, mengonfigurasi server, dan contoh integrasi dunia nyata.
Menguasai Claude Code Hooks: Auto-Format, Auto-Test, dan Lainnya
Pelajari cara menyiapkan auto-formatting dan auto-testing dengan Claude Code hooks. Dilengkapi contoh konfigurasi praktis dan use case dunia nyata.
Panduan Lengkap Menulis CLAUDE.md: Best Practice untuk Konfigurasi Project
Panduan menyeluruh untuk menulis file CLAUDE.md yang efektif. Pelajari cara mengkomunikasikan tech stack, konvensi, dan struktur project untuk memaksimalkan kualitas output Claude Code.