All files / tests helpers.ts

100% Statements 17/17
100% Branches 0/0
100% Functions 5/5
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60              6x 6x 6x       30x 30x 30x 30x 30x         20x   20x             20x                 16x 16x         16x         1x 1x         1x    
import { type FastifyInstance } from "fastify";
import { buildApp } from "../src/app.js";
import { db } from "../src/db/index.js";
import { users, otpCodes, sessions, accounts, memberships } from "../src/db/schema.js";
import { sql } from "drizzle-orm";
 
export async function createTestApp(): Promise<FastifyInstance> {
  const app = buildApp();
  await app.ready();
  return app;
}
 
export async function cleanDb() {
  await db.delete(sessions);
  await db.delete(memberships);
  await db.delete(accounts);
  await db.delete(otpCodes);
  await db.delete(users);
}
 
/** Request an OTP and return the code from the DB */
export async function requestOtpCode(app: FastifyInstance, email: string): Promise<string> {
  await app.inject({ method: "POST", url: "/login", payload: { email } });
 
  const [otp] = await db
    .select()
    .from(otpCodes)
    .where(sql`${otpCodes.email} = ${email}`)
    .orderBy(sql`${otpCodes.createdAt} desc`)
    .limit(1);
 
  return otp.code;
}
 
/** Full signup flow: request OTP → signup → return response */
export async function signupUser(
  app: FastifyInstance,
  email: string,
  accountName: string,
) {
  const code = await requestOtpCode(app, email);
  const res = await app.inject({
    method: "POST",
    url: "/signup",
    payload: { email, code, accountName },
  });
  return res;
}
 
/** Full login flow for an existing user: request OTP → create session → return response */
export async function loginUser(app: FastifyInstance, email: string) {
  const code = await requestOtpCode(app, email);
  const res = await app.inject({
    method: "POST",
    url: "/sessions",
    payload: { email, code },
  });
  return res;
}