|
| 1 | +import { afterEach, expect, test, vi } from "vite-plus/test"; |
| 2 | +import { runToExit } from "../src/index.ts"; |
| 3 | + |
| 4 | +const originalExitCode = process.exitCode; |
| 5 | + |
| 6 | +afterEach(() => { |
| 7 | + process.exitCode = originalExitCode; |
| 8 | + vi.restoreAllMocks(); |
| 9 | +}); |
| 10 | + |
| 11 | +function stubExit() { |
| 12 | + return vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); |
| 13 | +} |
| 14 | + |
| 15 | +test("runToExit exits with code 0 once run() resolves", async () => { |
| 16 | + const exit = stubExit(); |
| 17 | + process.exitCode = undefined; |
| 18 | + const events: string[] = []; |
| 19 | + const run = vi.fn(async () => { |
| 20 | + events.push("run"); |
| 21 | + }); |
| 22 | + exit.mockImplementation((() => { |
| 23 | + events.push("exit"); |
| 24 | + }) as never); |
| 25 | + |
| 26 | + await runToExit({ run }, ["x"]); |
| 27 | + |
| 28 | + expect(run).toHaveBeenCalledWith(["x"]); |
| 29 | + expect(events).toEqual(["run", "exit"]); |
| 30 | + expect(exit).toHaveBeenCalledWith(0); |
| 31 | +}); |
| 32 | + |
| 33 | +test("runToExit keeps the exit code the run set", async () => { |
| 34 | + const exit = stubExit(); |
| 35 | + await runToExit({ |
| 36 | + async run() { |
| 37 | + process.exitCode = 3; |
| 38 | + }, |
| 39 | + }); |
| 40 | + |
| 41 | + expect(exit).toHaveBeenCalledWith(3); |
| 42 | +}); |
| 43 | + |
| 44 | +test("runToExit does not exit while run() is still pending", async () => { |
| 45 | + const exit = stubExit(); |
| 46 | + let finish!: () => void; |
| 47 | + const pending = runToExit({ run: () => new Promise<void>((resolve) => (finish = resolve)) }); |
| 48 | + |
| 49 | + await new Promise((resolve) => setTimeout(resolve, 20)); |
| 50 | + expect(exit).not.toHaveBeenCalled(); |
| 51 | + |
| 52 | + finish(); |
| 53 | + await pending; |
| 54 | + expect(exit).toHaveBeenCalledTimes(1); |
| 55 | +}); |
0 commit comments