本文へ移動

テスト ​

テストは重要です。 Hono のアプリケーションは簡単にテストできます。 テスト環境の作成方法はランタイムによって異なりますが、基本的な手順は同じです。 このセクションでは、Cloudflare Workers と Vitest を使ってテストします。

ヒント

Cloudflare は、Vitest と @cloudflare/vitest-pool-workers の併用を推奨しています。詳しくは、Cloudflare Workers ドキュメントの Vitest との連携を参照してください。

リクエストとレスポンス ​

Request を作成して Hono アプリケーションに渡すだけで、Response を検証できます。便利な app.request メソッドを使えます。

ヒント

型付きのテストクライアントについては、テストヘルパーを参照してください。

たとえば、次の REST API を提供するアプリケーションを考えます。

ts
app.get('/posts', (c) => {
  return c.text('Many posts')
})

app.post('/posts', (c) => {
  return c.json(
    {
      message: 'Created',
    },
    201,
    {
      'X-Custom': 'Thank you',
    }
  )
})

GET /posts にリクエストを送り、レスポンスをテストします。

ts
describe('Example', () => {
  test('GET /posts', async () => {
    const res = await app.request('/posts')
    expect(res.status).toBe(200)
    expect(await res.text()).toBe('Many posts')
  })
})

POST /posts にリクエストを送るには、次のようにします。

ts
test('POST /posts', async () => {
  const res = await app.request('/posts', {
    method: 'POST',
  })
  expect(res.status).toBe(201)
  expect(res.headers.get('X-Custom')).toBe('Thank you')
  expect(await res.json()).toEqual({
    message: 'Created',
  })
})

JSON データを含むリクエストを POST /posts に送るには、次のようにします。

ts
test('POST /posts', async () => {
  const res = await app.request('/posts', {
    method: 'POST',
    body: JSON.stringify({ message: 'hello hono' }),
    headers: new Headers({ 'Content-Type': 'application/json' }),
  })
  expect(res.status).toBe(201)
  expect(res.headers.get('X-Custom')).toBe('Thank you')
  expect(await res.json()).toEqual({
    message: 'Created',
  })
})

multipart/form-data のデータを含むリクエストを POST /posts に送るには、次のようにします。

ts
test('POST /posts', async () => {
  const formData = new FormData()
  formData.append('message', 'hello')
  const res = await app.request('/posts', {
    method: 'POST',
    body: formData,
  })
  expect(res.status).toBe(201)
  expect(res.headers.get('X-Custom')).toBe('Thank you')
  expect(await res.json()).toEqual({
    message: 'Created',
  })
})

Request クラスのインスタンスを渡すこともできます。

ts
test('POST /posts', async () => {
  const req = new Request('http://localhost/posts', {
    method: 'POST',
  })
  const res = await app.request(req)
  expect(res.status).toBe(201)
  expect(res.headers.get('X-Custom')).toBe('Thank you')
  expect(await res.json()).toEqual({
    message: 'Created',
  })
})

このように、エンドツーエンドテストに近い形でテストできます。

環境 ​

テスト用に c.env を設定するには、app.request の第 3 引数として渡します。Cloudflare Workers のバインディングなどの値をモックするのに便利です。

ts
const MOCK_ENV = {
  API_HOST: 'example.com',
  DB: {
    prepare: () => {
      /* mocked D1 */
    },
  },
}

test('GET /posts', async () => {
  const res = await app.request('/posts', {}, MOCK_ENV)
})

MIT ライセンスで公開されています。