|
| 1 | +import { describe, it, expect, vi, beforeEach } from "vitest"; |
| 2 | +import { scheduleBackground } from "../schedule-background"; |
| 3 | +import * as nextServer from "next/server"; |
| 4 | + |
| 5 | +vi.mock("next/server", () => ({ |
| 6 | + after: vi.fn(), |
| 7 | +})); |
| 8 | + |
| 9 | +describe("scheduleBackground", () => { |
| 10 | + beforeEach(() => { |
| 11 | + vi.clearAllMocks(); |
| 12 | + }); |
| 13 | + |
| 14 | + it("delegates to Next.js after() when inside a request context", () => { |
| 15 | + const afterMock = vi.mocked(nextServer.after); |
| 16 | + afterMock.mockImplementation((task) => { |
| 17 | + // Mock successful scheduling |
| 18 | + return task as unknown as void; |
| 19 | + }); |
| 20 | + |
| 21 | + const task = vi.fn(); |
| 22 | + scheduleBackground(task); |
| 23 | + |
| 24 | + expect(afterMock).toHaveBeenCalledTimes(1); |
| 25 | + expect(afterMock).toHaveBeenCalledWith(task); |
| 26 | + // Task itself is deferred, not immediately called by scheduleBackground |
| 27 | + expect(task).not.toHaveBeenCalled(); |
| 28 | + }); |
| 29 | + |
| 30 | + it("gracefully runs the task immediately when after() throws outside a request scope", () => { |
| 31 | + const afterMock = vi.mocked(nextServer.after); |
| 32 | + afterMock.mockImplementation(() => { |
| 33 | + throw new Error("`after` was called outside a request scope."); |
| 34 | + }); |
| 35 | + |
| 36 | + const task = vi.fn(); |
| 37 | + scheduleBackground(task); |
| 38 | + |
| 39 | + expect(afterMock).toHaveBeenCalledTimes(1); |
| 40 | + expect(task).toHaveBeenCalledTimes(1); |
| 41 | + }); |
| 42 | + |
| 43 | + it("gracefully runs async tasks when outside a request scope", async () => { |
| 44 | + const afterMock = vi.mocked(nextServer.after); |
| 45 | + afterMock.mockImplementation(() => { |
| 46 | + throw new Error("`after` was called outside a request scope."); |
| 47 | + }); |
| 48 | + |
| 49 | + let asyncDone = false; |
| 50 | + const asyncTask = async () => { |
| 51 | + await Promise.resolve(); |
| 52 | + asyncDone = true; |
| 53 | + }; |
| 54 | + |
| 55 | + scheduleBackground(asyncTask); |
| 56 | + |
| 57 | + await Promise.resolve(); |
| 58 | + expect(asyncDone).toBe(true); |
| 59 | + }); |
| 60 | +}); |
0 commit comments