unit-test-generator
Generates comprehensive unit tests with AAA pattern (Arrange-Act-Assert), edge cases, error scenarios, and coverage analysis. Creates test files matching source structure with complete test suites. Use for "unit testing", "test generation", "Jest tests", or "test coverage".
What this skill does
# Unit Test Generator
Generate comprehensive unit tests with edge cases and AAA pattern.
## AAA Pattern Template
```typescript
// tests/utils/validator.test.ts
import { describe, it, expect } from "vitest";
import { validateEmail } from "@/utils/validator";
describe("validateEmail", () => {
it("should return true for valid email", () => {
// Arrange
const email = "[email protected]";
// Act
const result = validateEmail(email);
// Assert
expect(result).toBe(true);
});
it("should return false for invalid email - missing @", () => {
// Arrange
const email = "userexample.com";
// Act
const result = validateEmail(email);
// Assert
expect(result).toBe(false);
});
it("should return false for invalid email - missing domain", () => {
// Arrange
const email = "user@";
// Act
const result = validateEmail(email);
// Assert
expect(result).toBe(false);
});
});
```
## Comprehensive Test Cases
```typescript
// src/utils/calculator.ts
export function divide(a: number, b: number): number {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}
// tests/utils/calculator.test.ts
describe("divide", () => {
describe("happy path", () => {
it("should divide positive numbers", () => {
expect(divide(10, 2)).toBe(5);
});
it("should divide negative numbers", () => {
expect(divide(-10, 2)).toBe(-5);
expect(divide(10, -2)).toBe(-5);
expect(divide(-10, -2)).toBe(5);
});
it("should handle decimal results", () => {
expect(divide(10, 3)).toBeCloseTo(3.333, 3);
});
});
describe("edge cases", () => {
it("should handle zero dividend", () => {
expect(divide(0, 5)).toBe(0);
});
it("should handle very large numbers", () => {
expect(divide(Number.MAX_SAFE_INTEGER, 2)).toBe(
Number.MAX_SAFE_INTEGER / 2
);
});
it("should handle very small numbers", () => {
expect(divide(0.0001, 0.0001)).toBe(1);
});
});
describe("error cases", () => {
it("should throw error when dividing by zero", () => {
expect(() => divide(10, 0)).toThrow("Division by zero");
});
it("should throw error when dividing by negative zero", () => {
expect(() => divide(10, -0)).toThrow("Division by zero");
});
});
});
```
## Async Function Testing
```typescript
// src/services/userService.ts
export async function fetchUser(id: string): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`User not found: ${id}`);
}
return response.json();
}
// tests/services/userService.test.ts
describe("fetchUser", () => {
beforeEach(() => {
global.fetch = vi.fn();
});
afterEach(() => {
vi.resetAllMocks();
});
it("should fetch user successfully", async () => {
// Arrange
const mockUser = { id: "123", name: "John" };
(global.fetch as any).mockResolvedValueOnce({
ok: true,
json: async () => mockUser,
});
// Act
const user = await fetchUser("123");
// Assert
expect(user).toEqual(mockUser);
expect(global.fetch).toHaveBeenCalledWith("/api/users/123");
});
it("should throw error when user not found", async () => {
// Arrange
(global.fetch as any).mockResolvedValueOnce({
ok: false,
});
// Act & Assert
await expect(fetchUser("999")).rejects.toThrow("User not found: 999");
});
it("should handle network error", async () => {
// Arrange
(global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
// Act & Assert
await expect(fetchUser("123")).rejects.toThrow("Network error");
});
});
```
## Testing Classes
```typescript
// src/models/ShoppingCart.ts
export class ShoppingCart {
private items: CartItem[] = [];
add(item: CartItem): void {
this.items.push(item);
}
remove(itemId: string): void {
this.items = this.items.filter((i) => i.id !== itemId);
}
getTotal(): number {
return this.items.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
}
clear(): void {
this.items = [];
}
}
// tests/models/ShoppingCart.test.ts
describe("ShoppingCart", () => {
let cart: ShoppingCart;
beforeEach(() => {
cart = new ShoppingCart();
});
describe("add", () => {
it("should add item to cart", () => {
// Arrange
const item = { id: "1", name: "Product", price: 10, quantity: 1 };
// Act
cart.add(item);
// Assert
expect(cart.getTotal()).toBe(10);
});
it("should add multiple items", () => {
// Arrange
const item1 = { id: "1", name: "Product 1", price: 10, quantity: 1 };
const item2 = { id: "2", name: "Product 2", price: 20, quantity: 2 };
// Act
cart.add(item1);
cart.add(item2);
// Assert
expect(cart.getTotal()).toBe(50); // 10 + (20 * 2)
});
});
describe("remove", () => {
it("should remove item from cart", () => {
// Arrange
const item = { id: "1", name: "Product", price: 10, quantity: 1 };
cart.add(item);
// Act
cart.remove("1");
// Assert
expect(cart.getTotal()).toBe(0);
});
it("should not throw when removing non-existent item", () => {
// Act & Assert
expect(() => cart.remove("999")).not.toThrow();
});
});
describe("getTotal", () => {
it("should return 0 for empty cart", () => {
expect(cart.getTotal()).toBe(0);
});
it("should calculate total with quantities", () => {
// Arrange
cart.add({ id: "1", name: "Product", price: 10, quantity: 3 });
// Assert
expect(cart.getTotal()).toBe(30);
});
});
describe("clear", () => {
it("should remove all items", () => {
// Arrange
cart.add({ id: "1", name: "Product 1", price: 10, quantity: 1 });
cart.add({ id: "2", name: "Product 2", price: 20, quantity: 1 });
// Act
cart.clear();
// Assert
expect(cart.getTotal()).toBe(0);
});
});
});
```
## Testing React Components
```typescript
// src/components/Counter.tsx
export function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
// tests/components/Counter.test.tsx
import { render, screen, fireEvent } from "@testing-library/react";
describe("Counter", () => {
it("should render with initial count of 0", () => {
// Arrange & Act
render(<Counter />);
// Assert
expect(screen.getByText("Count: 0")).toBeInTheDocument();
});
it("should increment count when button clicked", () => {
// Arrange
render(<Counter />);
const button = screen.getByText("Increment");
// Act
fireEvent.click(button);
// Assert
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
it("should increment multiple times", () => {
// Arrange
render(<Counter />);
const button = screen.getByText("Increment");
// Act
fireEvent.click(button);
fireEvent.click(button);
fireEvent.click(button);
// Assert
expect(screen.getByText("Count: 3")).toBeInTheDocument();
});
it("should reset count to 0", () => {
// Arrange
render(<Counter />);
fireEvent.click(screen.getByText("Increment"));
// Act
fireEvent.click(screen.getByText("Reset"));
// Assert
expect(screen.getByText("Count: 0")).toBeInTheDocument();
});
});
```
## Edge Case Categories
```typescript
// Test case generation template
interface TestCase {
category: "happy-path" | "edge-case" | "error-case";
description: string;
input: any;
expectedOutput: any;
}
const testCases: TestCase[] = [
// Happy path
{
category: "happy-path",
description: "typical valid input",
input: "[email protected]",
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.