因为 Hono 站在标准 Request/Response 上,所以它的测试心智也非常直接:
给它一个请求,看它回什么响应。
#最朴素的测法:app.request()
import { describe, expect, test } from 'vitest'
import { app } from './server'
describe('dispatch api', () => {
test('GET /dispatches/:id', async () => {
const res = await app.request('/dispatches/dispatch-001')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
id: 'dispatch-001',
status: 'queued',
})
})
})这很像沙盘里直接派一个信使过去,看回执。
#更类型安全的测法:testClient()
import { testClient } from 'hono/testing'
import { app } from './server'
const client = testClient(app)
const res = await client.dispatches[':id'].$get({
param: { id: 'dispatch-001' },
})但这里有个官方文档也反复强调的细节:
如果你想让 testClient() 推断到具体路由类型,最好用链式定义路由。
也就是这种:
const app = new Hono()
.get('/a', ...)
.post('/b', ...)而不是:
const app = new Hono()
app.get('/a', ...)
app.post('/b', ...)两种运行都行,但在“类型沙盘”这件事上,前者更容易把图纸保留下来。