|
| 1 | +import { test, expect, beforeEach, afterEach } from "bun:test" |
| 2 | +import { createConsoleCollector } from "./console" |
| 3 | + |
| 4 | +let originalConsole: typeof console |
| 5 | + |
| 6 | +beforeEach(() => { |
| 7 | + originalConsole = { ...console } |
| 8 | +}) |
| 9 | + |
| 10 | +afterEach(() => { |
| 11 | + Object.assign(console, originalConsole) |
| 12 | +}) |
| 13 | + |
| 14 | +test("patches console.log and records the call", () => { |
| 15 | + const c = createConsoleCollector({ max: 10 }) |
| 16 | + c.start() |
| 17 | + console.log("hi", 1) |
| 18 | + const entries = c.snapshot() |
| 19 | + expect(entries).toHaveLength(1) |
| 20 | + expect(entries[0]?.level).toBe("log") |
| 21 | + expect(entries[0]?.args).toEqual(["hi", "1"]) |
| 22 | + c.stop() |
| 23 | +}) |
| 24 | + |
| 25 | +test("captures stack on warn + error only", () => { |
| 26 | + const c = createConsoleCollector({ max: 10 }) |
| 27 | + c.start() |
| 28 | + console.log("no stack") |
| 29 | + console.warn("with stack") |
| 30 | + console.error("with stack") |
| 31 | + const entries = c.snapshot() |
| 32 | + expect(entries.find((e) => e.level === "log")?.stack).toBeUndefined() |
| 33 | + expect(entries.find((e) => e.level === "warn")?.stack).toBeDefined() |
| 34 | + expect(entries.find((e) => e.level === "error")?.stack).toBeDefined() |
| 35 | + c.stop() |
| 36 | +}) |
| 37 | + |
| 38 | +test("stop restores the original console functions", () => { |
| 39 | + const original = console.log |
| 40 | + const c = createConsoleCollector({ max: 10 }) |
| 41 | + c.start() |
| 42 | + expect(console.log).not.toBe(original) |
| 43 | + c.stop() |
| 44 | + expect(console.log).toBe(original) |
| 45 | +}) |
| 46 | + |
| 47 | +test("fails open if host code throws inside patched log", () => { |
| 48 | + const c = createConsoleCollector({ max: 10 }) |
| 49 | + c.start() |
| 50 | + // Stub the ring push to throw — collector must still call through to the original. |
| 51 | + const originalPush = (c as unknown as { __buf: { push: (v: unknown) => void } }).__buf.push |
| 52 | + ;(c as unknown as { __buf: { push: (v: unknown) => void } }).__buf.push = () => { |
| 53 | + throw new Error("boom") |
| 54 | + } |
| 55 | + expect(() => console.log("x")).not.toThrow() |
| 56 | + ;(c as unknown as { __buf: { push: (v: unknown) => void } }).__buf.push = originalPush |
| 57 | + c.stop() |
| 58 | +}) |
0 commit comments