Cloudflare 테스트 구현
@cloudflare/vitest-pool-workers를 사용하면 Cloudflare 테스트를 쉽게 구현할 수 있다. 이 라이브러리를 사용하려면 몇 가지 설정이 필요하며, 자세한 내용은 Cloudflare 테스트 문서에서 확인할 수 있다.
Cloudflare 테스트는 vitest pool workers를 통해 cloudflare:test 모듈을 런타임에 제공한다. 이 모듈은 테스트 중 두 번째 인자로 전달된 환경 변수를 노출한다. 더 자세한 내용은 Cloudflare 테스트 API 섹션에서 확인할 수 있다.
아래는 설정 예제다:
ts
import { defineWorkersProject } from '@cloudflare/vitest-pool-workers/config'
export default defineWorkersProject(() => {
return {
test: {
globals: true,
poolOptions: {
workers: { wrangler: { configPath: './wrangler.toml' } },
},
},
}
})toml
compatibility_date = "2024-09-09"
compatibility_flags = [ "nodejs_compat" ]
[vars]
MY_VAR = "my variable"다음과 같은 애플리케이션을 가정해 보자:
ts
// src/index.ts
import { Hono } from 'hono'
type Bindings = {
MY_VAR: string
}
const app = new Hono<{ Bindings: Bindings }>()
app.get('/hello', (c) => {
return c.json({ hello: 'world', var: c.env.MY_VAR })
})
export default appcloudflare:test 모듈에서 노출된 env를 app.request()에 전달하여 Cloudflare 바인딩을 사용해 애플리케이션을 테스트할 수 있다:
ts
// src/index.test.ts
import { env } from 'cloudflare:test'
import app from './index'
describe('Example', () => {
it('Should return 200 response', async () => {
const res = await app.request('/hello', {}, env)
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
hello: 'world',
var: 'my variable',
})
})
})관련 자료
@cloudflare/vitest-pool-workers Github 저장소 예제
기존 테스트 시스템에서 마이그레이션