跳到主要内容

测试

hono 如何测试一个端口?​

  • 使用 app.request 测试路由:;
  • 方式: 直接构造 Request 走完整链路, 再断言标准 Response;
  • 特点: 不走网络, 不起端口, 与测试框架无关;

测试能在哪些框架里跑?​

  • 可选: Vitest、Jest、node:test;
const app = new Hono()
.get("/posts", (c) => c.text("Many posts"))
.post("/posts", async (c) => c.json({ body: await c.req.json() }, 201, { "X-Custom": "ok" }));

const res = await app.request("/posts", {
method: "POST",
body: JSON.stringify({ title: "hi" }),
headers: new Headers({ "Content-Type": "application/json" }),
});
expect(res.status).toBe(201);
  • 注入 c.env: 第三个参数传 mock 环境 app.request(path, init, MOCK_ENV);
  • 鉴权头: 放 init.headers;

testClient 与 hc 差在哪?​

  • testClient(app): 来自 hono/testing, 进程内直连;
  • 写法: 与 hc 一致, 但不经过网络;
  • 硬性前提: 路由必须链式定义在 new Hono() 上, 否则推不出方法;
const client = testClient(app);
const res = await client.search.$get({ query: { q: "hono" } });

测试里怎么注入依赖?​

  • 依赖注入: 数据库、fetch 与时间在 createFactory({ initApp }) 里注入;
  • 测试: 换成内存实现;
  • Handler: 只读 c.var;