import { describe, expect, it, vi } from "vitest";
import { formatSafely, getValueOrFallback } from "./utils.js";
describe("formatSafely", () => {
it("should return fallback when data is null", () => {
const formatter = (data: string) => `Formatted: ${data}`;
const result = formatSafely(null, formatter);
expect(result).toBe("—");
});
it("should return fallback when data is undefined", () => {
const formatter = (data: string) => `Formatted: ${data}`;
const result = formatSafely(undefined, formatter);
expect(result).toBe("—");
});
it("should return custom fallback when provided", () => {
const formatter = (data: string) => `Formatted: ${data}`;
const result = formatSafely(null, formatter, "N/A");
expect(result).toBe("N/A");
});
it("should call formatter and return result with valid data", () => {
const formatter = (data: string) => `Formatted: ${data}`;
const result = formatSafely("test", formatter);
expect(result).toBe("Formatted: test");
});
it("should handle formatter that throws error", () => {
const errorFormatter = () => {
throw new Error("Formatter failed");
};
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const result = formatSafely("data", errorFormatter);
expect(result).toBe("✗ Format error");
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("[Operation: safeFormat]"));
consoleSpy.mockRestore();
});
it("should work with complex data types", () => {
interface TestData {
name: string;
count: number;
}
const formatter = (data: TestData) => `${data.name}: ${data.count}`;
const result = formatSafely({ name: "test", count: 42 }, formatter);
expect(result).toBe("test: 42");
});
});
describe("getValueOrFallback", () => {
it("should return fallback when value is null", () => {
const result = getValueOrFallback(null);
expect(result).toBe("—");
});
it("should return fallback when value is undefined", () => {
const result = getValueOrFallback(undefined);
expect(result).toBe("—");
});
it("should return custom fallback when provided", () => {
const result = getValueOrFallback(null, "N/A");
expect(result).toBe("N/A");
});
it("should return value when not null or undefined", () => {
const result = getValueOrFallback("test value");
expect(result).toBe("test value");
});
it("should return zero when value is zero", () => {
const result = getValueOrFallback(0);
expect(result).toBe(0);
});
it("should return false when value is false", () => {
const result = getValueOrFallback(false);
expect(result).toBe(false);
});
it("should return empty string when value is empty string", () => {
const result = getValueOrFallback("");
expect(result).toBe("");
});
it("should work with complex data types", () => {
const obj = { name: "test", count: 42 };
const result = getValueOrFallback(obj);
expect(result).toBe(obj);
});
});