測試
測試很重要。實際上,測試 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('https://127.0.0.1/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
。這對於模擬值(如 Cloudflare Workers Bindings)非常有用
ts
const MOCK_ENV = {
API_HOST: 'example.com',
DB: {
prepare: () => {
/* mocked D1 */
},
},
}
test('GET /posts', async () => {
const res = await app.request('/posts', {}, MOCK_ENV)
})