Testing
Test each feature through the real app, and keep the layout honest with hono-bento check.
Feature tests
A feature's tests live in its folder and call the real app with
app.request(). One test then covers routing, authentication, validation and
the handler, with no server and no network.
import { beforeEach, describe, expect, it } from 'bun:test';
import { todoSchema } from '@todos/schemas/todos';
import { createApp } from '../../app';
import { testDb } from '../../test-db';
const app = createApp({ db: testDb, log: false });
// Each test run has its own Postgres schema, so a test can clear a table freely.
beforeEach(async () => {
await testDb.todo.deleteMany();
});
describe('todos', () => {
it('creates a todo', async () => {
const res = await app.request('/v1/todos', {
method: 'POST',
headers: { 'x-api-key': 'sk_editor', 'content-type': 'application/json' },
body: JSON.stringify({ title: 'Write tests' }),
});
expect(res.status).toBe(201);
// Parse with the shared schema: the test fails if the response breaks the contract.
expect(todoSchema.parse(await res.json())).toMatchObject({ title: 'Write tests', done: false });
});
it('rejects writes from a viewer', async () => {
const res = await app.request('/v1/todos', {
method: 'POST',
headers: { 'x-api-key': 'sk_viewer', 'content-type': 'application/json' },
body: JSON.stringify({ title: 'Nope' }),
});
expect(res.status).toBe(403);
});
});Wrap your app in a createApp() function that takes its database, so tests
pass their own, and an option to turn the logger off, so expected 4xx
responses don't fill the test output. See
Database for how each run gets its own
schema.
Check every response
Turn on validateResponses outside production. Then every response in every
test is checked against the route's documented responses: a handler that
returns an undocumented status, a body that doesn't match its schema, or an
undeclared field at any depth gets a 500, so the test fails.
export function createApp({
db,
log = true,
validateResponses = process.env.NODE_ENV !== 'production',
}: {
db: Database;
log?: boolean;
validateResponses?: boolean;
}) {
const deps: Deps = { db, todoChanges: createChangeFeed() };
const app = new Hono();
mountSpecs(app, specs, {
strategies,
authorizer: roleAuthorizer,
logger: log ? console : undefined,
validateResponses,
deps: () => deps,
});
return app;
}bun test sets NODE_ENV to test, so it's on in tests by default. The
reason for a failure goes to the logger, so pass log: true while debugging
one.
Unit-testing a handler
Handlers are plain functions. To test one without the auth and validation
stack, mount a single spec with createRouter and a stub strategy that returns
a fixed identity:
import { Hono } from 'hono';
import { createRouter } from 'hono-bento';
import { spec } from './spec';
const app = new Hono().route(
spec.basePath,
createRouter(spec, {
strategies: [{ name: 'test', authenticate: () => ({ userId: 'u_1', role: 'admin' }) }],
authorizer: { authorize: () => true },
})
);If any route names its strategies (auth: { strategies: ['jwt'] }), give the
stub that name: createRouter throws at startup when a route names a strategy
that isn't registered.
The structure test
The example's structure.test.ts runs
hono-bento check: the
layout, contract and data-access rules. Run it with the rest of your tests.
When it fails, each finding says what to move or add.