agentleFS
hoangNguyenAngelhackhoangNguyenAngelhack/ai-agent-setup/.agents/skills/tdd/SKILL.md

tdd

Skill3 starsChanged 6 months agoMITView on GitHub

Test-Driven Development workflow with RED-GREEN-REFACTOR cycle. Use when writing tests first, implementing features with TDD, or ensuring code correctness through testing.

194 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use capture-learning-tools, design-frontend-dev and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • The-Vibe-CompanySkill

    capture-learning-tools

    Turn technical conversations, bugs, CI failures, review comments,

    Also in 5 projects that use this

  • The-Vibe-CompanySkill

    design-frontend-dev

    Clean Impeccable frontend design skill. Use when the user wants to

    Also in 5 projects that use this

  • tristanphvnSkill

    ketchup-video

    Catch the user up like /keel:ketchup, with a short silent video of slides for what happened and the waiting calls as text under it. Use for /keel:ketchup-video.

    Also in 14 projects that use this

  • jaydubya818Skill

    figure-it-out

    Use when novel or multi-phase work needs an auditable workflow and no narrower playbook fits.

    Also in 54 projects that use this

  • jaydubya818Skill

    principle-laziness-protocol

    Apply when a refactor is adding wrappers or abstractions instead of simplifying.

    Also in 45 projects that use this

  • +2 more from The-Vibe-Company
  • +5 more from jaydubya818

The file

We split this skill into the rules it gives an agent

3 rules. 0 are common, 3 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 186 edited versions we read keep these.

  • 3

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Write tests before code using the RED-GREEN-REFACTOR cycle.

    line 12
  2. Distinctive:

    Write a test for the behavior you want.

    line 36
  3. Distinctive:

    Write the minimal code to make the test pass.

    line 57

“Common” is measured: kept by at least 6 in 10 of the 186 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Test-Driven Development

Write tests before code using the RED-GREEN-REFACTOR cycle.

Impact Levels

LevelDescription
CRITICALMust follow - test coverage
HIGHShould follow - test quality
MEDIUMRecommended - patterns

The TDD Cycle (CRITICAL)

┌─────────────────────────────────────────┐
│                                         │
│   RED → GREEN → REFACTOR → (repeat)     │
│                                         │
│   Fail   Pass    Improve                │
│                                         │
└─────────────────────────────────────────┘

RED: Write a Failing Test

Write a test for the behavior you want. The test should fail because the code doesn't exist yet.

// Step 1: Write the test FIRST
describe('UserService', () => {
  it('should create a user with valid data', async () => {
    const service = new UserService(mockRepo);
    
    const user = await service.createUser({
      email: 'test@example.com',
      name: 'Test User',
    });
    
    expect(user.id).toBeDefined();
    expect(user.email).toBe('test@example.com');
  });
});

GREEN: Make It Pass

Write the minimal code to make the test pass. Don't over-engineer.

// Step 2: Write MINIMAL code to pass
class UserService {
  constructor(private repo: UserRepository) {}
  
  async createUser(data: CreateUserInput): Promise<User> {
    return this.repo.create({
      id: generateId(),
      email: data.email,
      name: data.name,
      createdAt: new Date(),
    });
  }
}

REFACTOR: Improve the Code

Clean up while keeping tests green. Extract functions, rename variables, remove duplication.

// Step 3: Improve while staying GREEN
class UserService {
  constructor(private repo: UserRepository) {}
  
  async createUser(data: CreateUserInput): Promise<User> {
    this.validateEmail(data.email);
    return this.repo.create(this.buildUser(data));
  }
  
  private validateEmail(email: string): void {
    if (!isValidEmail(email)) {
      throw new AppError('Invalid email', 422);
    }
  }
  
  private buildUser(data: CreateUserInput): User {
    return {
      id: generateId(),
      email: data.email,
      name: data.name,
      createdAt: new Date(),
    };
  }
}

Test Structure (HIGH)

AAA Pattern (Arrange-Act-Assert)

it('should calculate order total with discount', () => {
  // Arrange - Set up test data
  const order = {
    items: [
      { price: 100, quantity: 2 },
      { price: 50, quantity: 1 },
    ],
    discountPercent: 10,
  };
  
  // Act - Execute the code under test
  const total = calculateOrderTotal(order);
  
  // Assert - Verify the result
  expect(total).toBe(225); // (200 + 50) * 0.9
});

Test Naming

// Pattern: should [expected behavior] when [condition]

it('should return user when found', async () => {});
it('should throw NotFoundError when user does not exist', async () => {});
it('should apply discount when coupon is valid', async () => {});

What to Test (HIGH)

Happy Path

it('should create user successfully with valid data', async () => {
  const user = await service.createUser(validData);
  expect(user).toBeDefined();
});

Error Cases

it('should throw ValidationError for invalid email', async () => {
  await expect(service.createUser({ email: 'invalid' }))
    .rejects.toThrow('Invalid email');
});

Edge Cases

it('should handle empty array gracefully', async () => {
  const result = await service.processItems([]);
  expect(result).toEqual([]);
});

it('should handle null input', async () => {
  const result = service.formatName(null);
  expect(result).toBe('');
});

Boundary Conditions

it('should reject password shorter than 8 characters', () => {
  expect(() => validatePassword('1234567')).toThrow();
});

it('should accept password of exactly 8 characters', () => {
  expect(() => validatePassword('12345678')).not.toThrow();
});

Mocking (MEDIUM)

Mock Dependencies

describe('UserService', () => {
  let service: UserService;
  let mockRepo: jest.Mocked<UserRepository>;
  
  beforeEach(() => {
    mockRepo = {
      create: jest.fn(),
      findById: jest.fn(),
      update: jest.fn(),
      delete: jest.fn(),
    };
    service = new UserService(mockRepo);
  });
  
  it('should call repository with correct data', async () => {
    mockRepo.create.mockResolvedValue({ id: '1', ...validData });
    
    await service.createUser(validData);
    
    expect(mockRepo.create).toHaveBeenCalledWith(
      expect.objectContaining({ email: validData.email })
    );
  });
});

Mock External Services

jest.mock('@/lib/email', () => ({
  sendEmail: jest.fn().mockResolvedValue({ success: true }),
}));

it('should send welcome email after registration', async () => {
  await service.registerUser(userData);
  
  expect(sendEmail).toHaveBeenCalledWith({
    to: userData.email,
    template: 'welcome',
  });
});

Coverage Requirements (CRITICAL)

TierCoverage
Starter50%
Standard80%
Strict95%

Anti-Patterns to Avoid (HIGH)

// DON'T: Test implementation details
it('should call private method', () => {
  // Testing internal implementation, not behavior
});

// DO: Test behavior/outcomes
it('should return formatted user name', () => {
  expect(formatUser(user)).toEqual(expectedOutput);
});

// DON'T: Multiple assertions testing different things
it('should work correctly', () => {
  expect(result.name).toBe('test');
  expect(result.email).toBe('test@test.com');
  expect(result.age).toBe(25);
  expect(service.callCount).toBe(1); // Different concern!
});

// DO: One concept per test
it('should return user with correct name', () => {});
it('should return user with correct email', () => {});

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.