|
| 1 | +import { describe, expect, it } from "vitest"; |
| 2 | +import { safeStringifyError } from "./error-utils.js"; |
| 3 | + |
| 4 | +describe("safeStringifyError", () => { |
| 5 | + it("returns error.message for Error instances", () => { |
| 6 | + const error = new Error("something went wrong"); |
| 7 | + expect(safeStringifyError(error)).toBe("something went wrong"); |
| 8 | + }); |
| 9 | + |
| 10 | + it("returns error.message for subclassed errors", () => { |
| 11 | + const error = new TypeError("type mismatch"); |
| 12 | + expect(safeStringifyError(error)).toBe("type mismatch"); |
| 13 | + }); |
| 14 | + |
| 15 | + it("stringifies plain objects", () => { |
| 16 | + expect(safeStringifyError({ code: 42 })).toBe('{"code":42}'); |
| 17 | + }); |
| 18 | + |
| 19 | + it("stringifies primitives", () => { |
| 20 | + expect(safeStringifyError("hello")).toBe('"hello"'); |
| 21 | + expect(safeStringifyError(123)).toBe("123"); |
| 22 | + expect(safeStringifyError(true)).toBe("true"); |
| 23 | + expect(safeStringifyError(null)).toBe("null"); |
| 24 | + }); |
| 25 | + |
| 26 | + it("falls back to String() for circular references", () => { |
| 27 | + const obj: Record<string, unknown> = { name: "circular" }; |
| 28 | + obj.self = obj; |
| 29 | + const result = safeStringifyError(obj); |
| 30 | + expect(result).toBe("[object Object]"); |
| 31 | + }); |
| 32 | + |
| 33 | + it("falls back to String() for objects that throw on stringify", () => { |
| 34 | + const obj = { |
| 35 | + get toJSON() { |
| 36 | + throw new Error("nope"); |
| 37 | + }, |
| 38 | + }; |
| 39 | + const result = safeStringifyError(obj); |
| 40 | + expect(typeof result).toBe("string"); |
| 41 | + expect(result.length).toBeGreaterThan(0); |
| 42 | + }); |
| 43 | +}); |
0 commit comments