test(api): Auth & /me — fill gaps + lifecycle test

This commit is contained in:
Bas van Rossem
2026-07-22 11:50:32 +02:00
parent 2fa8aa9154
commit e6e4ca0a1e
5 changed files with 133 additions and 1 deletions

View File

@@ -0,0 +1,43 @@
import { describe, it, expect, afterEach, vi } from 'vitest';
import type { Context } from 'hono';
import { auth } from '../src/auth';
import { getSessionUser, isAdmin } from '../src/lib/require-user';
// getSessionUser/isAdmin are the auth gate's building blocks. The role/banned
// fallbacks can't be reached through a real sign-in (the admin plugin always sets
// a role), so exercise them by stubbing the one thing getSessionUser reads:
// auth.api.getSession. vi is already the suite's mocking tool (see env.test.ts).
const fakeCtx = { req: { raw: { headers: new Headers() } } } as unknown as Context;
function mockSession(sessionUser: Record<string, unknown> | null) {
vi.spyOn(auth.api, 'getSession').mockResolvedValue(
(sessionUser ? { user: sessionUser, session: {} } : null) as never,
);
}
describe('getSessionUser', () => {
afterEach(() => vi.restoreAllMocks());
it('returns null when there is no session', async () => {
mockSession(null);
expect(await getSessionUser(fakeCtx)).toBeNull();
});
it('maps id, role and banned from the session user', async () => {
mockSession({ id: 'u1', role: 'admin', banned: true });
expect(await getSessionUser(fakeCtx)).toEqual({ id: 'u1', role: 'admin', banned: true });
});
it("defaults role to 'worker' and banned to false when they are unset", async () => {
mockSession({ id: 'u2' });
expect(await getSessionUser(fakeCtx)).toEqual({ id: 'u2', role: 'worker', banned: false });
});
});
describe('isAdmin', () => {
it('is true only for the admin role', () => {
expect(isAdmin({ id: 'a', role: 'admin', banned: false })).toBe(true);
expect(isAdmin({ id: 'w', role: 'worker', banned: false })).toBe(false);
expect(isAdmin(null)).toBe(false);
});
});