테스트
테스트는 중요하다.
실제로 Hono 애플리케이션을 테스트하는 것은 쉽다.
각 런타임마다 테스트 환경을 구성하는 방법은 다르지만, 기본적인 단계는 동일하다.
이 섹션에서는 Cloudflare Workers와 Jest를 사용해 테스트를 진행해 본다.
요청과 응답
Hono 애플리케이션에서 요청(Request)을 생성하고 이를 전달해 응답(Response)을 검증한다. 이때 app.request라는 유용한 메서드를 사용할 수 있다.
TIP
타입이 지정된 테스트 클라이언트를 사용하려면 테스트 헬퍼를 참고한다.
예를 들어, 다음과 같은 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',
})
})이렇게 하면 End-to-End 테스트를 수행할 수 있다.
환경 설정
테스트를 위해 c.env를 설정하려면 app.request의 세 번째 인자로 전달한다. Cloudflare Workers Bindings와 같은 값을 모킹할 때 유용하다:
ts
const MOCK_ENV = {
API_HOST: 'example.com',
DB: {
prepare: () => {
/* 모킹된 D1 */
},
},
}
test('GET /posts', async () => {
const res = await app.request('/posts', {}, MOCK_ENV)
})