Files
EpicNext-Cms/src/lib/services/news-archive.test.ts
T
Simo 5d18af932d
CI / check (push) Failing after 53s
CI / deploy (push) Skipped
CI / publish-container (push) Skipped
feat(news): add searchable paginated publication archive
2026-09-11 00:19:12 +02:00

66 lines
2.1 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
total: 55,
fail: false,
queries: [] as { sql: string; params: unknown[] }[],
}));
vi.mock("@/lib/db", async () => {
const schema = await import("@/db/schema");
const { drizzle } = await import("drizzle-orm/mysql-proxy");
return {
...schema,
db: drizzle(async (sql, params) => {
if (state.fail) throw new Error("unavailable");
state.queries.push({ sql, params });
return { rows: sql.includes("count(*)") ? [[state.total]] : [] };
}),
};
});
import { loadNewsArchive } from "./news-archive";
describe("public news archive", () => {
beforeEach(() => {
state.total = 55;
state.fail = false;
state.queries = [];
});
it("filters unpublished and future articles before counting and paginating", async () => {
const result = await loadNewsArchive({ search: "needle'", page: 2 });
expect(result).toMatchObject({ total: 55, page: 2, lastPage: 3 });
for (const query of state.queries) {
expect(query.sql).toContain("`status` = ?");
expect(query.sql).toContain("<= NOW()");
expect(query.params.slice(0, 3)).toEqual([
"published",
"%needle'%",
"%needle'%",
]);
}
expect(state.queries[1].params.slice(-2)).toEqual([24, 24]);
expect(state.queries[1].sql).toMatch(
/order by COALESCE.* desc, .*`id` desc/,
);
});
it("orders oldest first by publication time and bounds the last page", async () => {
expect(await loadNewsArchive({ page: 999, order: "oldest" })).toMatchObject(
{ page: 3, order: "oldest" },
);
expect(state.queries[1].sql).toMatch(/order by COALESCE.* asc, .*`id` asc/);
expect(state.queries[1].params.slice(-2)).toEqual([24, 48]);
});
it("handles empty results and invalid pagination", async () => {
state.total = 0;
expect(await loadNewsArchive({ page: NaN, order: "bad" })).toMatchObject({
page: 1,
lastPage: 1,
order: "newest",
});
});
it("propagates failures instead of presenting them as an empty archive", async () => {
state.fail = true;
await expect(loadNewsArchive()).rejects.toThrow();
});
});