hono-testing
Hono testing patterns - app.request(), test client, mocking environment, and integration testing strategies
What this skill does
# Hono Testing Patterns
## Overview
Hono provides a simple testing approach: create a Request, pass it to your app, and validate the Response. The framework includes a typed test client for even better DX.
**Key Features**:
- Simple `app.request()` API
- Typed test client with full inference
- Environment mocking for Workers
- Works with Vitest, Jest, or any test runner
## When to Use This Skill
Use Hono testing when:
- Writing unit tests for route handlers
- Integration testing API endpoints
- Testing middleware behavior
- Mocking Cloudflare Workers bindings
- Validating request/response cycles
## Basic Testing
### Using app.request()
```typescript
import { Hono } from 'hono'
import { describe, it, expect } from 'vitest'
const app = new Hono()
app.get('/hello', (c) => c.text('Hello!'))
app.get('/json', (c) => c.json({ message: 'Hello' }))
describe('Basic routes', () => {
it('should return text', async () => {
const res = await app.request('/hello')
expect(res.status).toBe(200)
expect(await res.text()).toBe('Hello!')
})
it('should return JSON', async () => {
const res = await app.request('/json')
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toContain('application/json')
expect(await res.json()).toEqual({ message: 'Hello' })
})
})
```
### Request Options
```typescript
// GET with query params
const res = await app.request('/search?q=hono&page=1')
// POST with JSON body
const res = await app.request('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'Alice', email: '[email protected]' })
})
// POST with form data
const formData = new FormData()
formData.append('name', 'Alice')
formData.append('email', '[email protected]')
const res = await app.request('/users', {
method: 'POST',
body: formData
})
// With custom headers
const res = await app.request('/protected', {
headers: {
'Authorization': 'Bearer token123',
'X-Custom-Header': 'value'
}
})
// DELETE request
const res = await app.request('/users/123', {
method: 'DELETE'
})
```
## Typed Test Client
The test client provides full type inference:
```typescript
import { Hono } from 'hono'
import { testClient } from 'hono/testing'
import { describe, it, expect } from 'vitest'
const app = new Hono()
.get('/users', (c) => c.json({ users: [] }))
.post('/users', async (c) => {
const body = await c.req.json()
return c.json({ id: '1', ...body }, 201)
})
.get('/users/:id', (c) => {
return c.json({ id: c.req.param('id'), name: 'Alice' })
})
describe('Users API', () => {
const client = testClient(app)
it('should list users', async () => {
const res = await client.users.$get()
expect(res.status).toBe(200)
const data = await res.json()
expect(data.users).toEqual([])
})
it('should create user', async () => {
const res = await client.users.$post({
json: { name: 'Alice', email: '[email protected]' }
})
expect(res.status).toBe(201)
const data = await res.json()
expect(data.name).toBe('Alice')
})
it('should get user by id', async () => {
const res = await client.users[':id'].$get({
param: { id: '123' }
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.id).toBe('123')
})
})
```
## Testing with Validation
```typescript
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const app = new Hono()
const createUserSchema = z.object({
name: z.string().min(1),
email: z.string().email()
})
app.post('/users', zValidator('json', createUserSchema), async (c) => {
const data = c.req.valid('json')
return c.json({ id: '1', ...data }, 201)
})
describe('Validation', () => {
it('should accept valid data', async () => {
const res = await app.request('/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Alice',
email: '[email protected]'
})
})
expect(res.status).toBe(201)
})
it('should reject invalid email', async () => {
const res = await app.request('/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'Alice',
email: 'invalid-email'
})
})
expect(res.status).toBe(400)
})
it('should reject missing name', async () => {
const res = await app.request('/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: '[email protected]'
})
})
expect(res.status).toBe(400)
})
})
```
## Mocking Environment (Cloudflare Workers)
### Mock Bindings
```typescript
import { Hono } from 'hono'
type Bindings = {
DB: D1Database
KV: KVNamespace
API_KEY: string
}
const app = new Hono<{ Bindings: Bindings }>()
app.get('/data', async (c) => {
const result = await c.env.DB.prepare('SELECT * FROM users').all()
return c.json(result)
})
app.get('/config', (c) => {
return c.json({ apiKey: c.env.API_KEY.slice(0, 4) + '...' })
})
describe('With mocked bindings', () => {
// Mock D1 database
const mockDB = {
prepare: () => ({
all: async () => ({ results: [{ id: 1, name: 'Alice' }] }),
first: async () => ({ id: 1, name: 'Alice' }),
run: async () => ({ success: true })
})
}
// Mock KV namespace
const mockKV = {
get: async (key: string) => 'cached-value',
put: async (key: string, value: string) => {},
delete: async (key: string) => {}
}
const mockEnv: Bindings = {
DB: mockDB as unknown as D1Database,
KV: mockKV as unknown as KVNamespace,
API_KEY: 'test-api-key-12345' // pragma: allowlist secret
}
it('should use mocked database', async () => {
const res = await app.request('/data', {}, mockEnv)
expect(res.status).toBe(200)
const data = await res.json()
expect(data.results).toHaveLength(1)
})
it('should use mocked API key', async () => {
const res = await app.request('/config', {}, mockEnv)
const data = await res.json()
expect(data.apiKey).toBe('test...')
})
})
```
### Using Miniflare
For more realistic Cloudflare Workers testing:
```typescript
import { Miniflare } from 'miniflare'
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
describe('With Miniflare', () => {
let mf: Miniflare
beforeAll(async () => {
mf = new Miniflare({
script: `
import app from './src/index'
export default app
`,
modules: true,
d1Databases: ['DB'],
kvNamespaces: ['KV']
})
})
afterAll(async () => {
await mf.dispose()
})
it('should work with real bindings', async () => {
const res = await mf.dispatchFetch('http://localhost/data')
expect(res.status).toBe(200)
})
})
```
## Testing Middleware
```typescript
import { Hono } from 'hono'
import { createMiddleware } from 'hono/factory'
// Middleware to test
const authMiddleware = createMiddleware(async (c, next) => {
const token = c.req.header('Authorization')?.replace('Bearer ', '')
if (!token) {
return c.json({ error: 'Unauthorized' }, 401)
}
if (token !== 'valid-token') {
return c.json({ error: 'Invalid token' }, 403)
}
c.set('userId', 'user-123')
await next()
})
const app = new Hono()
app.use('/protected/*', authMiddleware)
app.get('/protected/data', (c) => {
const userId = c.get('userId')
return c.json({ userId, data: 'secret' })
})
describe('Auth middleware', () => {
it('should reject request without token', async () => {
const res = await app.request('/protected/data')
expect(res.status).toBe(401)
expect(await res.json()).toEqual({ error: 'Unauthorized' })
})
it('should reject invalid token', async () => {
const res = await app.request('/protected/data', {
headers: { 'Authorization': 'Bearer invRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.