238 lines · 10.9 KB
import { beforeEach, describe, expect, mock, test } from "bun:test";
import { Database } from "bun:sqlite";
import { applyCombinedSchema } from "./test-schema.test-helper";

mock.module("cloudflare:workers", () => ({ env: { PUBLIC_URL: "https://forge.example.com" } }));
mock.module("@tanstack/react-start/server", () => ({ getRequestHeader: () => undefined }));

const db = new Database(":memory:");
applyCombinedSchema(db);

mock.module("./db", () => ({
  first: async (sql: string, ...params: unknown[]) => db.query(sql).get(...(params as never[])) ?? null,
  all: async (sql: string, ...params: unknown[]) => db.query(sql).all(...(params as never[])),
  run: async (sql: string, ...params: unknown[]) => {
    const result = db.query(sql).run(...(params as never[]));
    return { meta: { changes: result.changes } };
  },
  batch: async (statements: { sql: string; params: unknown[] }[]) => {
    for (const statement of statements) db.query(statement.sql).run(...(statement.params as never[]));
    return [];
  },
  stmt: (sql: string, ...params: unknown[]) => ({ sql, params }),
  placeholders: (count: number) => Array(count).fill("?").join(", "),
  chunks: <T>(items: T[]) => [items],
  MAX_IN_LIST: 90,
}));

const invalidated: string[] = [];
mock.module("./user-inbox", () => ({
  invalidateUnread: async (ids: Iterable<string>) => {
    invalidated.push(...ids);
  },
}));

const counterDeltas: { repoId: string; key: string; delta: number }[] = [];
mock.module("./counters", () => ({
  addCounter: async (_kind: string, repoId: string, key: string, delta: number[]) => {
    counterDeltas.push({ repoId, key, delta: delta[0] });
    return [0, 0, 0];
  },