テスト
テストは重要です。実際、Hono アプリケーションをテストするのは簡単です。テスト環境を作成する方法はランタイムごとに異なりますが、基本的な手順は同じです。このセクションでは、Cloudflare Workers と Jest でテストを行います。
リクエストとレスポンス
必要なのはリクエストを作成し、それを Hono アプリケーションに渡してレスポンスを検証することだけです。そして、便利なメソッドである 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
を設定するには、それを第 3 パラメーターとして app.request
に渡すことができます。これは、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)
})