$npx -y skills add sabahattink/antigravity-fullstack-hq --skill test-driven-developmentTDD 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.
| 1 | # Test-Driven Development |
| 2 | |
| 3 | ## The Red-Green-Refactor Cycle |
| 4 | |
| 5 | ``` |
| 6 | RED → Write a failing test that describes the desired behavior |
| 7 | GREEN → Write the minimum code to make it pass (no more, no less) |
| 8 | REFACTOR → Improve the code without changing behavior; tests stay green |
| 9 | ``` |
| 10 | |
| 11 | Never skip the RED step. If you write code before the test, you lose confidence that your test actually tests anything. |
| 12 | |
| 13 | ## Test Structure: AAA Pattern |
| 14 | |
| 15 | ```typescript |
| 16 | // Arrange → Act → Assert — every test follows this shape |
| 17 | |
| 18 | describe('UserService', () => { |
| 19 | describe('create', () => { |
| 20 | it('should hash the password before saving', async () => { |
| 21 | // ARRANGE — set up everything the test needs |
| 22 | const dto: CreateUserDto = { |
| 23 | email: 'jane@example.com', |
| 24 | password: 'S3cureP@ss!', |
| 25 | name: 'Jane Doe', |
| 26 | } |
| 27 | const mockRepo = createMockUserRepo() |
| 28 | const mockHasher = createMockHasher({ result: 'hashed_password' }) |
| 29 | const sut = new UserService(mockRepo, mockHasher) |
| 30 | |
| 31 | // ACT — call the thing under test |
| 32 | await sut.create(dto) |
| 33 | |
| 34 | // ASSERT — verify outcomes |
| 35 | expect(mockHasher.hash).toHaveBeenCalledWith('S3cureP@ss!') |
| 36 | expect(mockRepo.save).toHaveBeenCalledWith( |
| 37 | expect.objectContaining({ passwordHash: 'hashed_password' }) |
| 38 | ) |
| 39 | }) |
| 40 | }) |
| 41 | }) |
| 42 | ``` |
| 43 | |
| 44 | ## Vitest Setup |
| 45 | |
| 46 | ```typescript |
| 47 | // vitest.config.ts |
| 48 | import { defineConfig } from 'vitest/config' |
| 49 | import tsconfigPaths from 'vite-tsconfig-paths' |
| 50 | |
| 51 | export default defineConfig({ |
| 52 | plugins: [tsconfigPaths()], |
| 53 | test: { |
| 54 | globals: true, |
| 55 | environment: 'node', |
| 56 | setupFiles: ['./src/test/setup.ts'], |
| 57 | coverage: { |
| 58 | provider: 'v8', |
| 59 | reporter: ['text', 'html', 'lcov'], |
| 60 | thresholds: { lines: 80, functions: 80, branches: 80 }, |
| 61 | exclude: ['**/*.dto.ts', '**/*.entity.ts', '**/index.ts'], |
| 62 | }, |
| 63 | }, |
| 64 | }) |
| 65 | |
| 66 | // src/test/setup.ts |
| 67 | import { vi } from 'vitest' |
| 68 | |
| 69 | // Reset all mocks between tests — prevents state leakage |
| 70 | beforeEach(() => { vi.clearAllMocks() }) |
| 71 | afterEach(() => { vi.restoreAllMocks() }) |
| 72 | ``` |
| 73 | |
| 74 | ## Mocking Patterns |
| 75 | |
| 76 | ### Factory Functions for Mocks |
| 77 | ```typescript |
| 78 | // test/factories/user-repo.factory.ts |
| 79 | import { vi } from 'vitest' |
| 80 | import type { IUserRepository } from '../../domain/user/user.repository.interface' |
| 81 | |
| 82 | export function createMockUserRepo( |
| 83 | overrides: Partial<IUserRepository> = {} |
| 84 | ): jest.Mocked<IUserRepository> { |
| 85 | return { |
| 86 | findById: vi.fn().mockResolvedValue(null), |
| 87 | findByEmail: vi.fn().mockResolvedValue(null), |
| 88 | existsByEmail: vi.fn().mockResolvedValue(false), |
| 89 | save: vi.fn().mockResolvedValue(undefined), |
| 90 | delete: vi.fn().mockResolvedValue(undefined), |
| 91 | ...overrides, |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // Usage in a test |
| 96 | const repo = createMockUserRepo({ |
| 97 | findByEmail: vi.fn().mockResolvedValue(existingUser), |
| 98 | }) |
| 99 | ``` |
| 100 | |
| 101 | ### Spying on Methods |
| 102 | ```typescript |
| 103 | // Spy on a real object's method without replacing implementation |
| 104 | it('should call findById with the correct id', async () => { |
| 105 | const repo = new UserTypeOrmRepository(dataSource) |
| 106 | const spy = vi.spyOn(repo, 'findById') |
| 107 | const service = new UserService(repo) |
| 108 | |
| 109 | await service.findOneOrFail(42) |
| 110 | |
| 111 | expect(spy).toHaveBeenCalledWith(42) |
| 112 | expect(spy).toHaveBeenCalledTimes(1) |
| 113 | }) |
| 114 | ``` |
| 115 | |
| 116 | ### Module Mocking |
| 117 | ```typescript |
| 118 | // Mock an entire module |
| 119 | vi.mock('../lib/email-client', () => ({ |
| 120 | sendEmail: vi.fn().mockResolvedValue({ messageId: 'mock-id' }), |
| 121 | })) |
| 122 | |
| 123 | // In test: |
| 124 | import { sendEmail } from '../lib/email-client' |
| 125 | expect(sendEmail).toHaveBeenCalledWith( |
| 126 | expect.objectContaining({ to: 'jane@example.com' }) |
| 127 | ) |
| 128 | ``` |
| 129 | |
| 130 | ## Testing Domain Logic |
| 131 | |
| 132 | ```typescript |
| 133 | // Pure domain logic — no mocks needed, just test the entity |
| 134 | describe('User entity', () => { |
| 135 | describe('rename', () => { |
| 136 | it('should return a new User with the updated name', () => { |
| 137 | const user = User.create({ id: UserId.generate(), email: Email.create('j@x.com'), name: 'Old Name' }) |
| 138 | |
| 139 | const updated = user.rename('New Name') |
| 140 | |
| 141 | expect(updated.name).toBe('New Name') |
| 142 | expect(user.name).toBe('Old Name') // original is unchanged — immutability |
| 143 | }) |
| 144 | |
| 145 | it('should throw DomainError when name is blank', () => { |
| 146 | const user = User.create({ id: UserId.generate(), email: Email.create('j@x.com'), name: 'Jane' }) |
| 147 | |
| 148 | expect(() => user.rename(' ')).toThrow(DomainError) |
| 149 | expect(() => user.rename(' ')).toThrow('Name cannot be empty') |
| 150 | }) |
| 151 | }) |
| 152 | |
| 153 | describe('promote', () => { |
| 154 | it('should throw DomainError when actor is not admin', () => { |
| 155 | const actor = makeUser({ role: UserRole.USER }) |
| 156 | const target = makeUser({ role: UserRole.USER }) |
| 157 | |
| 158 | expect(() => target.promote(UserRole.ADMIN, actor)).toThrow(DomainError) |
| 159 | }) |
| 160 | }) |
| 161 | }) |
| 162 | ``` |
| 163 | |
| 164 | ## Testing Services (Unit) |
| 165 | |
| 166 | ```typescript |
| 167 | describe('CreateUserHandl |