测试
测试很重要。 实际上,测试 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',
})
})向 POST /posts 发送包含 JSON 数据的请求,可以这样做。
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',
})
})向 POST /posts 发送包含 multipart/form-data 数据的请求,可以这样做。
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。这对于模拟 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)
})