E2E Testing
Honoの組み込みrequest helperまたは型安全なclientを使って、アプリケーションのHTTPエンドポイントをend-to-endでテストします。
HTTP Testing
describe('Hello API', () => {
it('should return greeting', async () => {
const res = await readyApp.http.request('/hello/world');
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toEqual({ message: 'Hello, world!' });
});
});
型安全なClientでのテスト
生成された AppType をHonoのclientとともに使うと、完全に型付けされたテストが書けます。AppType の生成方法については OpenAPI & Type Generation を参照してください。
describe('Hello API', () => {
const client = hc<AppType>('http://localhost', {
fetch: (input: RequestInfo | URL, init?: RequestInit) => readyApp.http.fetch(new Request(input, init)),
});
it('should return greeting with type safety', async () => {
const res = await client.hello[':name'].$get({
param: { name: 'world' }
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.message).toBe('Hello, world!');
});
});
Full Application Testing
実際の依存関係を使った完全なE2Eテストには、onTest() を使って本番用アプリにtest configのoverrideを適用します。
// 本番用app - 実際のアプリケーションと同じ
const app = createApp([http({ controllers: [UserController] })], { configs: [RedisConfig] });
describe('API E2E', () => {
let testApp: Awaited<ReturnType<typeof app.createRuntime>>;
let client: AppType;
beforeAll(async () => {
// onTest()はRedisConfigをRedisTestContainerConfigでoverrideする
testApp = await onTest(app, {
configs: [RedisTestContainerConfig],
});
client = hc<AppType>('http://localhost', {
fetch: (input: RequestInfo | URL, init?: RequestInit) =>
testApp.http.fetch(new Request(input, init)),
});
});
it('should create and retrieve user', async () => {
const createRes = await client.users.$post({
json: { name: 'Alice', email: 'alice@example.com' },
});
expect(createRes.status).toBe(201);
const { id } = await createRes.json();
const getRes = await client.users[':id'].$get({
param: { id },
});
expect(getRes.status).toBe(200);
const user = await getRes.json();
expect(user.name).toBe('Alice');
});
});