本文へ移動

Testing ヘルパー ​

Testing ヘルパーは、Hono アプリケーションのテストを簡単にする関数を提供します。

インポート ​

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

testClient() ​

testClient() 関数は、第 1 引数に 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'],
    })
  })
})

テストでヘッダーを指定するには、呼び出しの第 2 引数に渡します。第 2 引数では、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 ライセンスで公開されています。