全书目录

第三十四篇:Hono 完全指南 —— 边缘轻骑哨站宇宙

第十一站:测试就是沙盘演练,Hono 的测试模型很干净

1 分钟 231 字 第 647 / 962 个阅读单元

因为 Hono 站在标准 Request/Response 上,所以它的测试心智也非常直接:

给它一个请求,看它回什么响应。

#最朴素的测法:app.request()

ts
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()

ts
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() 推断到具体路由类型,最好用链式定义路由。

也就是这种:

ts
const app = new Hono()
  .get('/a', ...)
  .post('/b', ...)

而不是:

ts
const app = new Hono()
app.get('/a', ...)
app.post('/b', ...)

两种运行都行,但在“类型沙盘”这件事上,前者更容易把图纸保留下来。