跳转到正文

Testing 辅助工具 ​

Testing 辅助工具提供让 Hono 应用测试更简单的函数。

导入 ​

ts
import { Hono } from 'hono'
import { testClient } from 'hono/testing'

testClient() ​

testClient() 函数接收 Hono 实例作为第一个参数,并返回根据应用路由生成类型的对象,类似于 Hono 客户端。这样就可以在测试中以类型安全的方式调用已定义的路由,并获得编辑器自动补全。

类型推断的重要说明:

为了让 testClient 正确推断路由类型并提供自动补全,必须直接在 Hono 实例上通过链式方法定义路由。

类型推断依赖于类型信息在链式 .get()、.post() 等调用中传递。如果在创建 Hono 实例后再单独定义路由(例如“Hello World”示例中的常见写法:const app = new Hono(); app.get(...)),testClient 将无法获取具体路由所需的类型信息,也就不能提供类型安全的客户端功能。

示例:

以下示例有效,因为 .get() 方法直接链接到 new Hono() 调用上:

ts
// index.ts
const app = new Hono().get('/search', (c) => {
  const query = c.req.query('q')
  return c.json({ query: query, results: ['result1', 'result2'] })
})

export default app
ts
// index.test.ts
import { Hono } from 'hono'
import { testClient } from 'hono/testing'
import { describe, it, expect } from 'vitest' // Or your preferred test runner
import app from './app'

describe('Search Endpoint', () => {
  // Create the test client from the app instance
  const client = testClient(app)

  it('should return search results', async () => {
    // Call the endpoint using the typed client
    // Notice the type safety for query parameters (if defined in the route)
    // and the direct access via .$get()
    const res = await client.search.$get({
      query: { q: 'hono' },
    })

    // Assertions
    expect(res.status).toBe(200)
    expect(await res.json()).toEqual({
      query: 'hono',
      results: ['result1', 'result2'],
    })
  })
})

要在测试中包含请求头,请通过调用的第二个参数传入。第二个参数也可以接收作为 RequestInit 对象的 init 属性,用于设置请求头、方法、请求体等。有关 init 属性的详情,请参阅此处。

ts
// index.test.ts
import { Hono } from 'hono'
import { testClient } from 'hono/testing'
import { describe, it, expect } from 'vitest' // Or your preferred test runner
import app from './app'

describe('Search Endpoint', () => {
  // Create the test client from the app instance
  const client = testClient(app)

  it('should return search results', async () => {
    // Include the token in the headers and set the content type
    const token = 'this-is-a-very-clean-token'
    const res = await client.search.$get(
      {
        query: { q: 'hono' },
      },
      {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': `application/json`,
        },
      }
    )

    // Assertions
    expect(res.status).toBe(200)
    expect(await res.json()).toEqual({
      query: 'hono',
      results: ['result1', 'result2'],
    })
  })
})

基于 MIT 许可证发布。