--- title: HTTP Tests description: HTTP tests verify your API endpoints respond correctly to requests. Stacks provides a fluent testing API for making requests and asserting responses. --- # HTTP Tests HTTP tests verify your API endpoints respond correctly to requests. Stacks provides a fluent testing API for making requests and asserting responses. ## Overview HTTP tests allow you to: - **Test endpoints** - Verify routes return expected responses - **Test authentication** - Ensure protected routes require auth - **Test validation** - Confirm invalid input is rejected - **Test integrations** - Test full request/response cycles ## Making Requests ### Basic Requests ```typescript // tests/Feature/ApiTest.ts import { describe, expect, it } from 'bun:test' import { http } from '@stacksjs/testing' describe('API', () => { it('returns users list', async () => { const response = await http.get('/api/users') expect(response.status).toBe(200) expect(response.json()).resolves.toHaveProperty('data') }) it('creates a user', async () => { const response = await http.post('/api/users', { body: { name: 'John Doe', email: 'john@example.com', }, }) expect(response.status).toBe(201) const data = await response.json() expect(data.user.name).toBe('John Doe') }) it('updates a user', async () => { const response = await http.put('/api/users/1', { body: { name: 'Jane Doe' }, }) expect(response.status).toBe(200) }) it('deletes a user', async () => { const response = await http.delete('/api/users/1') expect(response.status).toBe(204) }) }) ``` ### Request Options ```typescript import { http } from '@stacksjs/testing' // With headers const response = await http.get('/api/protected', { headers: { 'Authorization': 'Bearer token123', 'Accept': 'application/json', }, }) // With query parameters const response = await http.get('/api/users', { query: { page: 1, limit: 10, sort: 'name', }, }) // With JSON body const response = await http.post('/api/users', { body: { name: 'John', email: 'john@example.com', }, }) // With form data const response = await http.post('/api/upload', { formData: { file: new File(['content'], 'test.txt'), description: 'Test file', }, }) ``` ## Response Assertions ### Status Assertions ```typescript import { describe, expect, it } from 'bun:test' import { http } from '@stacksjs/testing' describe('Status codes', () => { it('returns 200 for successful request', async () => { const response = await http.get('/api/health') expect(response.status).toBe(200) expect(response.ok).toBe(true) }) it('returns 201 for created resource', async () => { const response = await http.post('/api/posts', { body: { title: 'Test' }, }) expect(response.status).toBe(201) }) it('returns 204 for no content', async () => { const response = await http.delete('/api/posts/1') expect(response.status).toBe(204) }) it('returns 400 for bad request', async () => { const response = await http.post('/api/users', { body: {}, // Missing required fields }) expect(response.status).toBe(400) }) it('returns 401 for unauthorized', async () => { const response = await http.get('/api/admin') expect(response.status).toBe(401) }) it('returns 404 for not found', async () => { const response = await http.get('/api/users/999999') expect(response.status).toBe(404) }) }) ``` ### JSON Response Assertions ```typescript import { describe, expect, it } from 'bun:test' import { http } from '@stacksjs/testing' describe('JSON responses', () => { it('returns correct data structure', async () => { const response = await http.get('/api/users/1') const data = await response.json() expect(data).toHaveProperty('id') expect(data).toHaveProperty('name') expect(data).toHaveProperty('email') expect(data.id).toBe(1) }) it('returns paginated list', async () => { const response = await http.get('/api/users') const data = await response.json() expect(data).toHaveProperty('data') expect(data).toHaveProperty('meta') expect(data.meta).toHaveProperty('currentPage') expect(data.meta).toHaveProperty('totalPages') expect(data.meta).toHaveProperty('totalItems') expect(Array.isArray(data.data)).toBe(true) }) it('returns error format', async () => { const response = await http.post('/api/users', { body: {} }) const data = await response.json() expect(data).toHaveProperty('error') expect(data).toHaveProperty('message') }) }) ``` ### Header Assertions ```typescript import { describe, expect, it } from 'bun:test' import { http } from '@stacksjs/testing' describe('Response headers', () => { it('returns correct content type', async () => { const response = await http.get('/api/users') expect(response.headers.get('Content-Type')) .toContain('application/json') }) it('includes CORS headers', async () => { const response = await http.get('/api/users') expect(response.headers.get('Access-Control-Allow-Origin')) .toBeDefined() }) it('sets cache headers', async () => { const response = await http.get('/api/static-data') expect(response.headers.get('Cache-Control')) .toContain('max-age') }) }) ``` ## Authentication Testing ### Testing Protected Routes ```typescript import { describe, expect, it } from 'bun:test' import { http, actingAs } from '@stacksjs/testing' describe('Protected routes', () => { it('rejects unauthenticated requests', async () => { const response = await http.get('/api/profile') expect(response.status).toBe(401) }) it('accepts authenticated requests', async () => { const user = { id: 1, email: 'test@example.com' } const response = await actingAs(user).get('/api/profile') expect(response.status).toBe(200) }) it('tests with bearer token', async () => { const token = 'valid-jwt-token' const response = await http.get('/api/profile', { headers: { 'Authorization': `Bearer ${token}`, }, }) expect(response.status).toBe(200) }) }) ``` ### Testing Authorization ```typescript import { describe, expect, it } from 'bun:test' import { actingAs } from '@stacksjs/testing' describe('Authorization', () => { it('allows admin access', async () => { const admin = { id: 1, role: 'admin' } const response = await actingAs(admin).get('/api/admin/users') expect(response.status).toBe(200) }) it('denies regular user access', async () => { const user = { id: 2, role: 'user' } const response = await actingAs(user).get('/api/admin/users') expect(response.status).toBe(403) }) it('tests resource ownership', async () => { const owner = { id: 1 } const other = { id: 2 } // Owner can access their resource const ownerResponse = await actingAs(owner).get('/api/users/1/settings') expect(ownerResponse.status).toBe(200) // Others cannot const otherResponse = await actingAs(other).get('/api/users/1/settings') expect(otherResponse.status).toBe(403) }) }) ``` ## Validation Testing ### Testing Input Validation ```typescript import { describe, expect, it } from 'bun:test' import { http } from '@stacksjs/testing' describe('User validation', () => { it('requires email', async () => { const response = await http.post('/api/users', { body: { name: 'John' }, // Missing email }) expect(response.status).toBe(422) const data = await response.json() expect(data.errors.email).toContain('Email is required') }) it('validates email format', async () => { const response = await http.post('/api/users', { body: { name: 'John', email: 'not-an-email', }, }) expect(response.status).toBe(422) const data = await response.json() expect(data.errors.email).toContain('Invalid email format') }) it('requires password minimum length', async () => { const response = await http.post('/api/users', { body: { name: 'John', email: 'john@example.com', password: '123', // Too short }, }) expect(response.status).toBe(422) const data = await response.json() expect(data.errors.password).toContain('at least 8 characters') }) it('accepts valid input', async () => { const response = await http.post('/api/users', { body: { name: 'John Doe', email: 'john@example.com', password: 'securepassword123', }, }) expect(response.status).toBe(201) }) }) ``` ### Testing Edge Cases ```typescript import { describe, expect, it } from 'bun:test' import { http } from '@stacksjs/testing' describe('Edge cases', () => { it('handles empty body', async () => { const response = await http.post('/api/users', { body: null, }) expect(response.status).toBe(400) }) it('handles malformed JSON', async () => { const response = await fetch('http://localhost:3000/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{ invalid json }', }) expect(response.status).toBe(400) }) it('handles very long strings', async () => { const longString = 'a'.repeat(10000) const response = await http.post('/api/users', { body: { name: longString, email: 'test@example.com', }, }) expect(response.status).toBe(422) const data = await response.json() expect(data.errors.name).toContain('too long') }) it('handles special characters', async () => { const response = await http.post('/api/users', { body: { name: 'Test ', email: 'test@example.com', }, }) expect(response.status).toBe(201) const data = await response.json() // Should be sanitized expect(data.user.name).not.toContain('