also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,599 +0,0 @@ | ||
| 1 | # Testing | |
| 2 | ||
| 3 | This guide covers testing strategies and patterns for your Stacks application, including unit tests, integration tests, and test-driven development (TDD). | |
| 4 | ||
| 5 | ## Getting Started | |
| 6 | ||
| 7 | Stacks uses Bun's built-in test runner for fast and efficient testing. | |
| 8 | ||
| 9 | ```bash | |
| 10 | # Run all tests | |
| 11 | bun test | |
| 12 | ||
| 13 | # Run tests in watch mode | |
| 14 | bun test --watch | |
| 15 | ||
| 16 | # Run specific test file | |
| 17 | bun test tests/user.test.ts | |
| 18 | ||
| 19 | # Run tests matching pattern | |
| 20 | bun test --grep "user" | |
| 21 | ``` | |
| 22 | ||
| 23 | ## Test Structure | |
| 24 | ||
| 25 | ### Basic Test | |
| 26 | ||
| 27 | ```ts | |
| 28 | // tests/unit/utils.test.ts | |
| 29 | import { describe, it, expect } from 'bun:test' | |
| 30 | import { formatCurrency, formatDate } from '@/utils/formatters' | |
| 31 | ||
| 32 | describe('formatCurrency', () => { | |
| 33 | it('formats USD correctly', () => { | |
| 34 | expect(formatCurrency(1000, 'USD')).toBe('$10.00') | |
| 35 | }) | |
| 36 | ||
| 37 | it('formats EUR correctly', () => { | |
| 38 | expect(formatCurrency(1000, 'EUR')).toBe('€10.00') | |
| 39 | }) | |
| 40 | ||
| 41 | it('handles zero', () => { | |
| 42 | expect(formatCurrency(0, 'USD')).toBe('$0.00') | |
| 43 | }) | |
| 44 | ||
| 45 | it('handles negative values', () => { | |
| 46 | expect(formatCurrency(-1000, 'USD')).toBe('-$10.00') | |
| 47 | }) | |
| 48 | }) | |
| 49 | ||
| 50 | describe('formatDate', () => { | |
| 51 | it('formats dates correctly', () => { | |
| 52 | const date = new Date('2024-01-15') | |
| 53 | expect(formatDate(date)).toBe('January 15, 2024') | |
| 54 | }) | |
| 55 | ||
| 56 | it('formats with custom format', () => { | |
| 57 | const date = new Date('2024-01-15') | |
| 58 | expect(formatDate(date, 'MM/DD/YYYY')).toBe('01/15/2024') | |
| 59 | }) | |
| 60 | }) | |
| 61 | ``` | |
| 62 | ||
| 63 | ### Test Hooks | |
| 64 | ||
| 65 | ```ts | |
| 66 | import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test' | |
| 67 | ||
| 68 | describe('Database Tests', () => { | |
| 69 | beforeAll(async () => { | |
| 70 | // Run once before all tests | |
| 71 | await setupTestDatabase() | |
| 72 | }) | |
| 73 | ||
| 74 | afterAll(async () => { | |
| 75 | // Run once after all tests | |
| 76 | await teardownTestDatabase() | |
| 77 | }) | |
| 78 | ||
| 79 | beforeEach(async () => { | |
| 80 | // Run before each test | |
| 81 | await beginTransaction() | |
| 82 | }) | |
| 83 | ||
| 84 | afterEach(async () => { | |
| 85 | // Run after each test | |
| 86 | await rollbackTransaction() | |
| 87 | }) | |
| 88 | ||
| 89 | it('creates a user', async () => { | |
| 90 | const user = await User.create({ name: 'Test', email: 'test@example.com' }) | |
| 91 | expect(user.id).toBeDefined() | |
| 92 | }) | |
| 93 | }) | |
| 94 | ``` | |
| 95 | ||
| 96 | ## Unit Testing | |
| 97 | ||
| 98 | ### Testing Functions | |
| 99 | ||
| 100 | ```ts | |
| 101 | // tests/unit/validators.test.ts | |
| 102 | import { describe, it, expect } from 'bun:test' | |
| 103 | import { validateEmail, validatePassword, validatePhone } from '@/utils/validators' | |
| 104 | ||
| 105 | describe('validateEmail', () => { | |
| 106 | it('returns true for valid emails', () => { | |
| 107 | expect(validateEmail('user@example.com')).toBe(true) | |
| 108 | expect(validateEmail('user.name@example.co.uk')).toBe(true) | |
| 109 | }) | |
| 110 | ||
| 111 | it('returns false for invalid emails', () => { | |
| 112 | expect(validateEmail('invalid')).toBe(false) | |
| 113 | expect(validateEmail('missing@domain')).toBe(false) | |
| 114 | expect(validateEmail('@nodomain.com')).toBe(false) | |
| 115 | }) | |
| 116 | }) | |
| 117 | ||
| 118 | describe('validatePassword', () => { | |
| 119 | it('validates minimum length', () => { | |
| 120 | expect(validatePassword('short')).toEqual({ | |
| 121 | valid: false, | |
| 122 | errors: ['Password must be at least 8 characters'], | |
| 123 | }) | |
| 124 | }) | |
| 125 | ||
| 126 | it('validates complexity requirements', () => { | |
| 127 | expect(validatePassword('password123')).toEqual({ | |
| 128 | valid: false, | |
| 129 | errors: ['Password must contain an uppercase letter'], | |
| 130 | }) | |
| 131 | }) | |
| 132 | ||
| 133 | it('accepts valid passwords', () => { | |
| 134 | expect(validatePassword('SecurePass123!')).toEqual({ | |
| 135 | valid: true, | |
| 136 | errors: [], | |
| 137 | }) | |
| 138 | }) | |
| 139 | }) | |
| 140 | ``` | |
| 141 | ||
| 142 | ### Testing Classes | |
| 143 | ||
| 144 | ```ts | |
| 145 | // tests/unit/cart.test.ts | |
| 146 | import { describe, it, expect, beforeEach } from 'bun:test' | |
| 147 | import { Cart } from '@/services/Cart' | |
| 148 | ||
| 149 | describe('Cart', () => { | |
| 150 | let cart: Cart | |
| 151 | ||
| 152 | beforeEach(() => { | |
| 153 | cart = new Cart() | |
| 154 | }) | |
| 155 | ||
| 156 | describe('addItem', () => { | |
| 157 | it('adds item to empty cart', () => { | |
| 158 | cart.addItem({ id: 1, name: 'Product', price: 1000 }) | |
| 159 | expect(cart.items).toHaveLength(1) | |
| 160 | expect(cart.items[0].id).toBe(1) | |
| 161 | }) | |
| 162 | ||
| 163 | it('increases quantity for existing item', () => { | |
| 164 | cart.addItem({ id: 1, name: 'Product', price: 1000 }) | |
| 165 | cart.addItem({ id: 1, name: 'Product', price: 1000 }) | |
| 166 | expect(cart.items).toHaveLength(1) | |
| 167 | expect(cart.items[0].quantity).toBe(2) | |
| 168 | }) | |
| 169 | }) | |
| 170 | ||
| 171 | describe('removeItem', () => { | |
| 172 | it('removes item from cart', () => { | |
| 173 | cart.addItem({ id: 1, name: 'Product', price: 1000 }) | |
| 174 | cart.removeItem(1) | |
| 175 | expect(cart.items).toHaveLength(0) | |
| 176 | }) | |
| 177 | ||
| 178 | it('does nothing for non-existent item', () => { | |
| 179 | cart.addItem({ id: 1, name: 'Product', price: 1000 }) | |
| 180 | cart.removeItem(999) | |
| 181 | expect(cart.items).toHaveLength(1) | |
| 182 | }) | |
| 183 | }) | |
| 184 | ||
| 185 | describe('total', () => { | |
| 186 | it('calculates total correctly', () => { | |
| 187 | cart.addItem({ id: 1, name: 'Product A', price: 1000 }) | |
| 188 | cart.addItem({ id: 2, name: 'Product B', price: 2000 }) | |
| 189 | expect(cart.total).toBe(3000) | |
| 190 | }) | |
| 191 | ||
| 192 | it('returns 0 for empty cart', () => { | |
| 193 | expect(cart.total).toBe(0) | |
| 194 | }) | |
| 195 | }) | |
| 196 | }) | |
| 197 | ``` | |
| 198 | ||
| 199 | ## Integration Testing | |
| 200 | ||
| 201 | ### Testing API Endpoints | |
| 202 | ||
| 203 | ```ts | |
| 204 | // tests/integration/api/users.test.ts | |
| 205 | import { describe, it, expect, beforeAll, afterAll } from 'bun:test' | |
| 206 | import { app } from '@/app' | |
| 207 | ||
| 208 | describe('Users API', () => { | |
| 209 | let testUser: any | |
| 210 | let authToken: string | |
| 211 | ||
| 212 | beforeAll(async () => { | |
| 213 | // Create test user and get token | |
| 214 | const response = await app.request('/api/register', { | |
| 215 | method: 'POST', | |
| 216 | headers: { 'Content-Type': 'application/json' }, | |
| 217 | body: JSON.stringify({ | |
| 218 | name: 'Test User', | |
| 219 | email: 'test@example.com', | |
| 220 | password: 'password123', | |
| 221 | }), | |
| 222 | }) | |
| 223 | const data = await response.json() | |
| 224 | testUser = data.user | |
| 225 | authToken = data.token | |
| 226 | }) | |
| 227 | ||
| 228 | afterAll(async () => { | |
| 229 | // Cleanup | |
| 230 | await User.where('email', '=', 'test@example.com').delete() | |
| 231 | }) | |
| 232 | ||
| 233 | describe('GET /api/users', () => { | |
| 234 | it('returns users list with authentication', async () => { | |
| 235 | const response = await app.request('/api/users', { | |
| 236 | headers: { | |
| 237 | 'Authorization': `Bearer ${authToken}`, | |
| 238 | }, | |
| 239 | }) | |
| 240 | ||
| 241 | expect(response.status).toBe(200) | |
| 242 | const data = await response.json() | |
| 243 | expect(Array.isArray(data.users)).toBe(true) | |
| 244 | }) | |
| 245 | ||
| 246 | it('returns 401 without authentication', async () => { | |
| 247 | const response = await app.request('/api/users') | |
| 248 | expect(response.status).toBe(401) | |
| 249 | }) | |
| 250 | }) | |
| 251 | ||
| 252 | describe('GET /api/users/:id', () => { | |
| 253 | it('returns user details', async () => { | |
| 254 | const response = await app.request(`/api/users/${testUser.id}`, { | |
| 255 | headers: { | |
| 256 | 'Authorization': `Bearer ${authToken}`, | |
| 257 | }, | |
| 258 | }) | |
| 259 | ||
| 260 | expect(response.status).toBe(200) | |
| 261 | const data = await response.json() | |
| 262 | expect(data.user.email).toBe('test@example.com') | |
| 263 | }) | |
| 264 | ||
| 265 | it('returns 404 for non-existent user', async () => { | |
| 266 | const response = await app.request('/api/users/99999', { | |
| 267 | headers: { | |
| 268 | 'Authorization': `Bearer ${authToken}`, | |
| 269 | }, | |
| 270 | }) | |
| 271 | ||
| 272 | expect(response.status).toBe(404) | |
| 273 | }) | |
| 274 | }) | |
| 275 | ||
| 276 | describe('PATCH /api/users/:id', () => { | |
| 277 | it('updates user profile', async () => { | |
| 278 | const response = await app.request(`/api/users/${testUser.id}`, { | |
| 279 | method: 'PATCH', | |
| 280 | headers: { | |
| 281 | 'Content-Type': 'application/json', | |
| 282 | 'Authorization': `Bearer ${authToken}`, | |
| 283 | }, | |
| 284 | body: JSON.stringify({ | |
| 285 | name: 'Updated Name', | |
| 286 | }), | |
| 287 | }) | |
| 288 | ||
| 289 | expect(response.status).toBe(200) | |
| 290 | const data = await response.json() | |
| 291 | expect(data.user.name).toBe('Updated Name') | |
| 292 | }) | |
| 293 | }) | |
| 294 | }) | |
| 295 | ``` | |
| 296 | ||
| 297 | ### Testing Database Operations | |
| 298 | ||
| 299 | ```ts | |
| 300 | // tests/integration/database/user.test.ts | |
| 301 | import { describe, it, expect, beforeEach, afterEach } from 'bun:test' | |
| 302 | import { db } from '@stacksjs/database' | |
| 303 | import { User } from '@stacksjs/orm' | |
| 304 | ||
| 305 | describe('User Model', () => { | |
| 306 | beforeEach(async () => { | |
| 307 | await db.transaction().execute(async (trx) => { | |
| 308 | // Tests will run in this transaction | |
| 309 | }) | |
| 310 | }) | |
| 311 | ||
| 312 | afterEach(async () => { | |
| 313 | // Cleanup test data | |
| 314 | await User.where('email', 'like', '%@test.com').delete() | |
| 315 | }) | |
| 316 | ||
| 317 | describe('create', () => { | |
| 318 | it('creates user with valid data', async () => { | |
| 319 | const user = await User.create({ | |
| 320 | name: 'Test User', | |
| 321 | email: 'create@test.com', | |
| 322 | password: 'hashedpassword', | |
| 323 | }) | |
| 324 | ||
| 325 | expect(user.id).toBeDefined() | |
| 326 | expect(user.name).toBe('Test User') | |
| 327 | expect(user.email).toBe('create@test.com') | |
| 328 | }) | |
| 329 | ||
| 330 | it('throws on duplicate email', async () => { | |
| 331 | await User.create({ | |
| 332 | name: 'First User', | |
| 333 | email: 'duplicate@test.com', | |
| 334 | password: 'password', | |
| 335 | }) | |
| 336 | ||
| 337 | await expect( | |
| 338 | User.create({ | |
| 339 | name: 'Second User', | |
| 340 | email: 'duplicate@test.com', | |
| 341 | password: 'password', | |
| 342 | }) | |
| 343 | ).rejects.toThrow() | |
| 344 | }) | |
| 345 | }) | |
| 346 | ||
| 347 | describe('relationships', () => { | |
| 348 | it('loads user orders', async () => { | |
| 349 | const user = await User.create({ | |
| 350 | name: 'Order User', | |
| 351 | email: 'orders@test.com', | |
| 352 | password: 'password', | |
| 353 | }) | |
| 354 | ||
| 355 | await Order.create({ user_id: user.id, total: 1000 }) | |
| 356 | await Order.create({ user_id: user.id, total: 2000 }) | |
| 357 | ||
| 358 | const userWithOrders = await User.with(['orders']).find(user.id) | |
| 359 | expect(userWithOrders?.orders).toHaveLength(2) | |
| 360 | }) | |
| 361 | }) | |
| 362 | }) | |
| 363 | ``` | |
| 364 | ||
| 365 | ## Mocking | |
| 366 | ||
| 367 | ### Mocking Functions | |
| 368 | ||
| 369 | ```ts | |
| 370 | import { describe, it, expect, mock, spyOn } from 'bun:test' | |
| 371 | import { sendEmail } from '@/services/email' | |
| 372 | import { UserService } from '@/services/UserService' | |
| 373 | ||
| 374 | describe('UserService', () => { | |
| 375 | it('sends welcome email on registration', async () => { | |
| 376 | const mockSendEmail = mock(() => Promise.resolve()) | |
| 377 | ||
| 378 | // Replace the actual function | |
| 379 | const originalSendEmail = sendEmail | |
| 380 | global.sendEmail = mockSendEmail | |
| 381 | ||
| 382 | const userService = new UserService() | |
| 383 | await userService.register({ | |
| 384 | name: 'Test', | |
| 385 | email: 'test@example.com', | |
| 386 | password: 'password', | |
| 387 | }) | |
| 388 | ||
| 389 | expect(mockSendEmail).toHaveBeenCalled() | |
| 390 | expect(mockSendEmail).toHaveBeenCalledWith( | |
| 391 | expect.objectContaining({ | |
| 392 | to: 'test@example.com', | |
| 393 | template: 'welcome', | |
| 394 | }) | |
| 395 | ) | |
| 396 | ||
| 397 | // Restore | |
| 398 | global.sendEmail = originalSendEmail | |
| 399 | }) | |
| 400 | }) | |
| 401 | ``` | |
| 402 | ||
| 403 | ### Mocking HTTP Requests | |
| 404 | ||
| 405 | ```ts | |
| 406 | import { describe, it, expect, mock } from 'bun:test' | |
| 407 | import { PaymentService } from '@/services/PaymentService' | |
| 408 | ||
| 409 | describe('PaymentService', () => { | |
| 410 | it('processes payment successfully', async () => { | |
| 411 | // Mock fetch | |
| 412 | const mockFetch = mock(() => | |
| 413 | Promise.resolve({ | |
| 414 | ok: true, | |
| 415 | json: () => Promise.resolve({ | |
| 416 | id: 'ch_123', | |
| 417 | status: 'succeeded', | |
| 418 | }), | |
| 419 | }) | |
| 420 | ) | |
| 421 | global.fetch = mockFetch | |
| 422 | ||
| 423 | const paymentService = new PaymentService() | |
| 424 | const result = await paymentService.charge(1000, 'tok_visa') | |
| 425 | ||
| 426 | expect(result.status).toBe('succeeded') | |
| 427 | expect(mockFetch).toHaveBeenCalled() | |
| 428 | }) | |
| 429 | ||
| 430 | it('handles payment failure', async () => { | |
| 431 | const mockFetch = mock(() => | |
| 432 | Promise.resolve({ | |
| 433 | ok: false, | |
| 434 | status: 402, | |
| 435 | json: () => Promise.resolve({ | |
| 436 | error: { message: 'Card declined' }, | |
| 437 | }), | |
| 438 | }) | |
| 439 | ) | |
| 440 | global.fetch = mockFetch | |
| 441 | ||
| 442 | const paymentService = new PaymentService() | |
| 443 | ||
| 444 | await expect( | |
| 445 | paymentService.charge(1000, 'tok_declined') | |
| 446 | ).rejects.toThrow('Card declined') | |
| 447 | }) | |
| 448 | }) | |
| 449 | ``` | |
| 450 | ||
| 451 | ## Test-Driven Development (TDD) | |
| 452 | ||
| 453 | ### TDD Workflow | |
| 454 | ||
| 455 | 1. **Write a failing test** | |
| 456 | 2. **Write minimal code to pass** | |
| 457 | 3. **Refactor** | |
| 458 | ||
| 459 | ### Example: Building a Feature with TDD | |
| 460 | ||
| 461 | ```ts | |
| 462 | // Step 1: Write failing test | |
| 463 | // tests/unit/discount.test.ts | |
| 464 | import { describe, it, expect } from 'bun:test' | |
| 465 | import { calculateDiscount } from '@/services/discount' | |
| 466 | ||
| 467 | describe('calculateDiscount', () => { | |
| 468 | it('applies percentage discount', () => { | |
| 469 | expect(calculateDiscount(10000, { type: 'percentage', value: 10 })).toBe(9000) | |
| 470 | }) | |
| 471 | ||
| 472 | it('applies fixed discount', () => { | |
| 473 | expect(calculateDiscount(10000, { type: 'fixed', value: 1500 })).toBe(8500) | |
| 474 | }) | |
| 475 | ||
| 476 | it('does not go below zero', () => { | |
| 477 | expect(calculateDiscount(1000, { type: 'fixed', value: 2000 })).toBe(0) | |
| 478 | }) | |
| 479 | ||
| 480 | it('handles no discount', () => { | |
| 481 | expect(calculateDiscount(10000, null)).toBe(10000) | |
| 482 | }) | |
| 483 | }) | |
| 484 | ``` | |
| 485 | ||
| 486 | ```ts | |
| 487 | // Step 2: Write minimal code | |
| 488 | // src/services/discount.ts | |
| 489 | interface Discount { | |
| 490 | type: 'percentage' | 'fixed' | |
| 491 | value: number | |
| 492 | } | |
| 493 | ||
| 494 | export function calculateDiscount( | |
| 495 | amount: number, | |
| 496 | discount: Discount | null | |
| 497 | ): number { | |
| 498 | if (!discount) return amount | |
| 499 | ||
| 500 | let discountAmount = 0 | |
| 501 | ||
| 502 | if (discount.type === 'percentage') { | |
| 503 | discountAmount = Math.floor(amount * (discount.value / 100)) | |
| 504 | } else { | |
| 505 | discountAmount = discount.value | |
| 506 | } | |
| 507 | ||
| 508 | return Math.max(0, amount - discountAmount) | |
| 509 | } | |
| 510 | ``` | |
| 511 | ||
| 512 | ```ts | |
| 513 | // Step 3: Refactor and add more tests | |
| 514 | describe('calculateDiscount - edge cases', () => { | |
| 515 | it('handles zero amount', () => { | |
| 516 | expect(calculateDiscount(0, { type: 'percentage', value: 10 })).toBe(0) | |
| 517 | }) | |
| 518 | ||
| 519 | it('handles 100% discount', () => { | |
| 520 | expect(calculateDiscount(10000, { type: 'percentage', value: 100 })).toBe(0) | |
| 521 | }) | |
| 522 | }) | |
| 523 | ``` | |
| 524 | ||
| 525 | ## Test Configuration | |
| 526 | ||
| 527 | ### bun.test.ts | |
| 528 | ||
| 529 | ```ts | |
| 530 | // bun.test.ts | |
| 531 | import { beforeAll, afterAll } from 'bun:test' | |
| 532 | ||
| 533 | // Global setup | |
| 534 | beforeAll(async () => { | |
| 535 | // Set test environment | |
| 536 | process.env.APP_ENV = 'testing' | |
| 537 | ||
| 538 | // Initialize test database | |
| 539 | await setupTestDatabase() | |
| 540 | }) | |
| 541 | ||
| 542 | // Global teardown | |
| 543 | afterAll(async () => { | |
| 544 | await cleanupTestDatabase() | |
| 545 | }) | |
| 546 | ``` | |
| 547 | ||
| 548 | ### Test Environment | |
| 549 | ||
| 550 | ```env | |
| 551 | # .env.testing | |
| 552 | APP_ENV=testing | |
| 553 | APP_DEBUG=true | |
| 554 | ||
| 555 | DB_CONNECTION=sqlite | |
| 556 | DB_DATABASE=:memory: | |
| 557 | ||
| 558 | MAIL_MAILER=log | |
| 559 | CACHE_DRIVER=array | |
| 560 | ``` | |
| 561 | ||
| 562 | ## Coverage Reports | |
| 563 | ||
| 564 | ```bash | |
| 565 | # Generate coverage report | |
| 566 | bun test --coverage | |
| 567 | ||
| 568 | # Output coverage to specific directory | |
| 569 | bun test --coverage --coverage-dir=./coverage | |
| 570 | ``` | |
| 571 | ||
| 572 | ## Best Practices | |
| 573 | ||
| 574 | 1. **Keep tests focused** - One assertion per test when possible | |
| 575 | 2. **Use descriptive names** - Test names should describe behavior | |
| 576 | 3. **Arrange-Act-Assert** - Structure tests clearly | |
| 577 | 4. **Isolate tests** - Tests should not depend on each other | |
| 578 | 5. **Test edge cases** - Include boundary conditions | |
| 579 | 6. **Mock external services** - Don't make real API calls | |
| 580 | 7. **Use factories** - Create test data consistently | |
| 581 | ||
| 582 | ```ts | |
| 583 | // Good: Descriptive, focused test | |
| 584 | describe('User Registration', () => { | |
| 585 | it('creates user with hashed password', async () => { | |
| 586 | // Arrange | |
| 587 | const userData = { email: 'test@example.com', password: 'plain123' } | |
| 588 | ||
| 589 | // Act | |
| 590 | const user = await registerUser(userData) | |
| 591 | ||
| 592 | // Assert | |
| 593 | expect(user.password).not.toBe('plain123') | |
| 594 | expect(await verifyPassword('plain123', user.password)).toBe(true) | |
| 595 | }) | |
| 596 | }) | |
| 597 | ``` | |
| 598 | ||
| 599 | This documentation covers testing strategies and patterns for Stacks applications. Each example is designed for reliable and maintainable tests. | |