deadhead-space-freight-tycoon/apps/server/test/jobs.test.ts

54 lines
1.8 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { createPgBossQueue } from "../src/jobs/queue";
import { testConfig } from "./helpers";
/** Polls `check` until it returns true or the timeout passes. */
async function waitFor(check: () => Promise<boolean> | boolean, timeoutMs = 20_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (await check()) return;
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error("Timed out waiting");
}
describe("pg-boss job queue", () => {
it("runs an enqueued no-op job to completion", async () => {
const handled: unknown[] = [];
const queue = createPgBossQueue(testConfig().databaseUrl, {
workers: true,
jobs: [{ name: "test-noop", handler: async (data) => void handled.push(data) }],
});
await queue.start();
try {
const id = await queue.send("test-noop", { hello: "world" });
expect(id).not.toBeNull();
await waitFor(() => handled.length > 0);
expect(handled).toEqual([{ hello: "world" }]);
await waitFor(
async () => (await queue.boss.getJobById("test-noop", id!))?.state === "completed",
);
} finally {
await queue.stop();
}
}, 30_000);
it("only enqueues when workers are disabled", async () => {
const handled: unknown[] = [];
const queue = createPgBossQueue(testConfig().databaseUrl, {
workers: false,
jobs: [{ name: "test-idle", handler: async (data) => void handled.push(data) }],
});
await queue.start();
try {
const id = await queue.send("test-idle", {});
await new Promise((resolve) => setTimeout(resolve, 1500));
expect(handled).toEqual([]);
expect((await queue.boss.getJobById("test-idle", id!))?.state).toBe("created");
} finally {
await queue.stop();
}
}, 30_000);
});