test-driven-development
Skill30 starsChanged 52 days agoMITView on GitHub
TDD red-green-refactor cycle, test structure, mocking patterns for Vitest/Jest. Use when starting a new feature, fixing a bug, or refactoring — write the test first, then the implementation.
190 other projects use a version of this.
Adopted by
Most recently taken up by
- DemonDamon/AgenticXtheir own version, first seen Nov 9, 2026
- chrysogonus/power-agentstheir own version, first seen Nov 8, 2026
- ishandutta2007/Awesome-Agent-Skillstheir own version, first seen Nov 8, 2026
- roundpilot/superpowers-antigravitytheir own version, first seen Nov 8, 2026
- REPOZY/superpowers-optimizedtheir own version, first seen Nov 8, 2026
- lingyired/status-triotheir own version, first seen Nov 8, 2026
Used with
Projects with it also use chinese-code-review, chinese-commit-conventions 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.
Leodorareluctant259Skillchinese-code-review
中文代码审查规范——在保持专业严谨的同时,用符合国内团队文化的方式给出有效反馈
Also in 8 projects that use this
Leodorareluctant259Skillchinese-commit-conventions
中文 Git 提交规范 — 适配国内团队的 commit message 规范和 changelog 自动化
Also in 8 projects that use this
obraSkilldiagnosing-superpowers
Use when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.
Also in 19 projects that use this
LLl0k0laDSkillusing-agent-skills
Use when starting a session or when you need to discover which skill applies to the current task. This is the meta-skill that governs how all other skills are discovered and invoked.
Also in 39 projects that use this
LLl0k0laDSkillgit-workflow-and-versioning
Use when making any code change. Use when committing, branching, resolving conflicts, or when you need to organize work across multiple parallel streams.
Also in 47 projects that use this
MrCipherSmithSkillconstraint-driven-development
Use when a project needs a persistent, measurable quality bar — starting a project without documented standards, 'set up constraints', or when coverage/perf/a11y thresholds get re-debated per-PR. Produces CONSTRAINTS.md with enforceable numbers, ratchets, and a guard against silent weakening. NOT for throwaway prototypes or a one-off CI setup.
Also in 15 projects that use this
- +3 more from Leodorareluctant259
- +3 more from LLl0k0laD
Other versions190 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 190
- obra/superpowers★ 314ksame name
- NousResearch/hermes-agent★ 262ksame name
- addyosmani/agent-skills★ 114ksame name
- cloudflare/computer★ 9.9ksame name
- jnMetaCode/superpowers-zh★ 8.4ksame name
- openai/plugins★ 7.8ksame name
- farm-fe/farm★ 5.6ksame name
- microsoft/FluidFramework★ 4.9ksame name
- mikeyobrien/ralph-orchestrator★ 3.2ksame name
- crbnos/carbon★ 2.8ksame name
180 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository30 other files it gives its agents.
- AGENTS.mdAGENTS.md
- claude/CLAUDE.mdCLAUDE.md
- llms.txtllms.txt
- api-design-patternsSkill
- auth-patternsSkill
- backend-dev-guidelinesSkill
- brainstormingSkill
- code-review-patternsSkill
- deployment-guideSkill
- docker-patternsSkill
- docx-officialSkill
- frontend-designSkill
- github-actionsSkill
- git-workflowSkill
- nestjs-patternsSkill
- nextjs-app-routerSkill
- pdf-officialSkill
- pptx-officialSkill
- prisma-workflowSkill
- prompt-engineeringSkill
- react-best-practicesSkill
- security-checklistSkill
- skill-creatorSkill
- software-architectureSkill
- systematic-debuggingSkill
- tailwind-patternsSkill
- typescript-patternsSkill
- webapp-testingSkill
- web-design-guidelinesSkill
- xlsx-officialSkill
The file
We split this skill into the rules it gives an agent
9 rules. 0 are common, 7 are distinctive, and 2 are very specific to this project.
0
Common
Most of the 178 edited versions we read keep these.
7
Distinctive
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 16
Never skip the RED step. If you write code before the test, you lose confidence that your test actually tests anything.
- Distinctive: line 306
Never test implementation details — test observable behavior
- Very specific: line 307
Never share mutable state between tests — use beforeEach to reset
- Distinctive: line 308
Never write tests that depend on execution order
- Distinctive: line 309
Never assert on exact error messages from third-party libraries — those can change
- Distinctive: line 310
Never mock the system under test (SUT) itself
- Distinctive: line 311
Never skip the failing test step (RED) — you need to see it fail first
- Distinctive: line 312
Never write tests for trivial getters/setters — focus on behavior
- Very specific: line 313
Never use setTimeout in tests — use fake timers (vi.useFakeTimers())
“Common” is measured: kept by at least 6 in 10 of the 178 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.
Files
Test-Driven Development
The Red-Green-Refactor Cycle
RED → Write a failing test that describes the desired behavior
GREEN → Write the minimum code to make it pass (no more, no less)
REFACTOR → Improve the code without changing behavior; tests stay greenNever skip the RED step. If you write code before the test, you lose confidence that your test actually tests anything.
Test Structure: AAA Pattern
// Arrange → Act → Assert — every test follows this shape
describe('UserService', () => {
describe('create', () => {
it('should hash the password before saving', async () => {
// ARRANGE — set up everything the test needs
const dto: CreateUserDto = {
email: 'jane@example.com',
password: 'S3cureP@ss!',
name: 'Jane Doe',
}
const mockRepo = createMockUserRepo()
const mockHasher = createMockHasher({ result: 'hashed_password' })
const sut = new UserService(mockRepo, mockHasher)
// ACT — call the thing under test
await sut.create(dto)
// ASSERT — verify outcomes
expect(mockHasher.hash).toHaveBeenCalledWith('S3cureP@ss!')
expect(mockRepo.save).toHaveBeenCalledWith(
expect.objectContaining({ passwordHash: 'hashed_password' })
)
})
})
})Vitest Setup
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import tsconfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [tsconfigPaths()],
test: {
globals: true,
environment: 'node',
setupFiles: ['./src/test/setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
thresholds: { lines: 80, functions: 80, branches: 80 },
exclude: ['**/*.dto.ts', '**/*.entity.ts', '**/index.ts'],
},
},
})
// src/test/setup.ts
import { vi } from 'vitest'
// Reset all mocks between tests — prevents state leakage
beforeEach(() => { vi.clearAllMocks() })
afterEach(() => { vi.restoreAllMocks() })Mocking Patterns
Factory Functions for Mocks
// test/factories/user-repo.factory.ts
import { vi } from 'vitest'
import type { IUserRepository } from '../../domain/user/user.repository.interface'
export function createMockUserRepo(
overrides: Partial<IUserRepository> = {}
): jest.Mocked<IUserRepository> {
return {
findById: vi.fn().mockResolvedValue(null),
findByEmail: vi.fn().mockResolvedValue(null),
existsByEmail: vi.fn().mockResolvedValue(false),
save: vi.fn().mockResolvedValue(undefined),
delete: vi.fn().mockResolvedValue(undefined),
...overrides,
}
}
// Usage in a test
const repo = createMockUserRepo({
findByEmail: vi.fn().mockResolvedValue(existingUser),
})Spying on Methods
// Spy on a real object's method without replacing implementation
it('should call findById with the correct id', async () => {
const repo = new UserTypeOrmRepository(dataSource)
const spy = vi.spyOn(repo, 'findById')
const service = new UserService(repo)
await service.findOneOrFail(42)
expect(spy).toHaveBeenCalledWith(42)
expect(spy).toHaveBeenCalledTimes(1)
})Module Mocking
// Mock an entire module
vi.mock('../lib/email-client', () => ({
sendEmail: vi.fn().mockResolvedValue({ messageId: 'mock-id' }),
}))
// In test:
import { sendEmail } from '../lib/email-client'
expect(sendEmail).toHaveBeenCalledWith(
expect.objectContaining({ to: 'jane@example.com' })
)Testing Domain Logic
// Pure domain logic — no mocks needed, just test the entity
describe('User entity', () => {
describe('rename', () => {
it('should return a new User with the updated name', () => {
const user = User.create({ id: UserId.generate(), email: Email.create('j@x.com'), name: 'Old Name' })
const updated = user.rename('New Name')
expect(updated.name).toBe('New Name')
expect(user.name).toBe('Old Name') // original is unchanged — immutability
})
it('should throw DomainError when name is blank', () => {
const user = User.create({ id: UserId.generate(), email: Email.create('j@x.com'), name: 'Jane' })
expect(() => user.rename(' ')).toThrow(DomainError)
expect(() => user.rename(' ')).toThrow('Name cannot be empty')
})
})
describe('promote', () => {
it('should throw DomainError when actor is not admin', () => {
const actor = makeUser({ role: UserRole.USER })
const target = makeUser({ role: UserRole.USER })
expect(() => target.promote(UserRole.ADMIN, actor)).toThrow(DomainError)
})
})
})Testing Services (Unit)
describe('CreateUserHandler', () => {
let handler: CreateUserHandler
let repo: ReturnType<typeof createMockUserRepo>
let hasher: { hash: ReturnType<typeof vi.fn> }
let eventBus: { publish: ReturnType<typeof vi.fn> }
beforeEach(() => {
repo = createMockUserRepo()
hasher = { hash: vi.fn().mockResolvedValue('$2b$12$hashed') }
eventBus = { publish: vi.fn() }
handler = new CreateUserHandler(repo, hasher, eventBus)
})
it('should save a new user and publish UserCreatedEvent', async () => {
const cmd = new CreateUserCommand('jane@example.com', 'Pass123!', 'Jane', 'actor-id')
const userId = await handler.execute(cmd)
expect(repo.save).toHaveBeenCalledTimes(1)
expect(eventBus.publish).toHaveBeenCalledWith(
expect.objectContaining({ eventType: 'user.created', email: 'jane@example.com' })
)
expect(userId).toBeDefined()
})
it('should throw ConflictException when email already exists', async () => {
repo.existsByEmail.mockResolvedValue(true)
await expect(
handler.execute(new CreateUserCommand('taken@example.com', 'Pass123!', 'Bob', 'actor'))
).rejects.toThrow(ConflictException)
expect(repo.save).not.toHaveBeenCalled()
})
})Integration Tests with Test DB
// test/integration/users.integration.spec.ts
import { Test } from '@nestjs/testing'
import { TypeOrmModule } from '@nestjs/typeorm'
import { getRepositoryToken } from '@nestjs/typeorm'
describe('UsersService (integration)', () => {
let app: INestApplication
let service: UsersService
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: ':memory:',
entities: [UserOrmEntity],
synchronize: true,
}),
TypeOrmModule.forFeature([UserOrmEntity]),
UsersModule,
],
}).compile()
app = module.createNestApplication()
service = module.get(UsersService)
await app.init()
})
afterAll(() => app.close())
afterEach(async () => {
// Clean up between tests
const repo = app.get(getRepositoryToken(UserOrmEntity))
await repo.clear()
})
it('should persist and retrieve a user', async () => {
const created = await service.create(
{ email: 'test@example.com', password: 'Pass123!', name: 'Test' },
{ id: 'actor-1' } as AuthUser
)
const found = await service.findOneOrFail(created.id)
expect(found.email).toBe('test@example.com')
expect(found.name).toBe('Test')
})
})Test Doubles Reference
| Type | When to Use |
| Stub | Return a canned value (no assertions needed) |
| Mock | Verify calls were made (use expect(mock).toHaveBeenCalled) |
| Spy | Wrap a real method to observe calls |
| Fake | Lightweight real implementation (in-memory DB) |
| Dummy | Placeholder that's never called (satisfy a constructor) |
Coverage Targets
lines: 80% minimum
functions: 80% minimum
branches: 80% minimumExclude from coverage:
- DTOs, entities, configuration files
index.tsbarrel files- Migration files
- Type declaration files (
*.d.ts)
Test File Organization
src/
├── users/
│ ├── users.service.ts
│ ├── users.service.spec.ts # unit test — same dir
│ └── users.repository.spec.ts
test/
├── integration/
│ └── users.integration.spec.ts # integration — separate dir
├── e2e/
│ └── users.e2e.spec.ts
└── factories/
├── user.factory.ts
└── order.factory.tsForbidden Patterns
- Never test implementation details — test observable behavior
- Never share mutable state between tests — use
beforeEachto reset - Never write tests that depend on execution order
- Never assert on exact error messages from third-party libraries — those can change
- Never mock the system under test (SUT) itself
- Never skip the failing test step (RED) — you need to see it fail first
- Never write tests for trivial getters/setters — focus on behavior
- Never use
setTimeoutin tests — use fake timers (vi.useFakeTimers())
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
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.

