All files / apps/web/src/pages/api/utils cleanup.test.ts

0% Statements 0/21
0% Branches 0/2
0% Functions 0/7
0% Lines 0/20

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                                                                                                                                                                 
import { faker } from "@faker-js/faker";
import { TRPCError } from "@trpc/server";
import { describe, expect, vi } from "vitest";
 
import { test } from "~tests/backend/utils/test";
import type { router as appRouter } from "~web/handlers/index";
import { t } from "~web/handlers/trpc";
import { getServerRouteMethod } from "~web/pages/api/utils.test";
 
import { Route } from "./cleanup";
 
const postMethod = getServerRouteMethod(Route, "POST");
 
const removedSessions = faker.number.int({ min: 3000, max: 10_000 });
const removedResetPasswordIntentions = faker.number.int({
	min: 3000,
	max: 10_000,
});
 
// oxlint-disable-next-line typescript/require-await
vi.mock(import("~web/handlers/index"), async () => ({
	router: t.router({
		sessions: t.router({
			cleanup: t.procedure.mutation(({ ctx }) => {
				const errorMessage = ctx.reqHeaders.get("x-error");
				if (errorMessage !== null) {
					throw new TRPCError({
						code: "BAD_REQUEST",
						message: errorMessage,
					});
				}
				return { count: removedSessions };
			}),
		}),
		resetPasswordIntentions: t.router({
			cleanup: t.procedure.mutation(() => ({
				count: removedResetPasswordIntentions,
			})),
		}),
	}) as typeof appRouter,
}));
 
describe("cleanup API handler", () => {
	describe("failure", () => {
		test("one of the procedures failed", async () => {
			const errorMessage = faker.lorem.sentence();
			const response = await postMethod({
				pathname: "/api/utils/cleanup",
				request: new Request("http://example.com/", {
					headers: { "x-error": errorMessage },
				}),
				params: {},
			});
			const result = {
				status: response.status,
				data: await response.text(),
			};
			expect(result).toStrictEqual<typeof result>({
				status: 500,
				data: `Error on cleanup: TRPCClientError: ${errorMessage}`,
			});
		});
	});
 
	test("success", async () => {
		const response = await postMethod({
			pathname: "/api/utils/cleanup",
			request: new Request("http://example.com/"),
			params: {},
		});
		const result = {
			status: response.status,
			data: await response.text(),
		};
		expect(result).toStrictEqual<typeof result>({
			status: 200,
			data: `Removed ${removedSessions} sessions and ${removedResetPasswordIntentions} reset password intentions`,
		});
	});
});