Files
HiveGrid-Wireframes/hivegrid-cloud/apps/web/app/locale/format.test.ts
T

65 lines
2.3 KiB
TypeScript

import { afterEach, describe, expect, test, vi } from "vitest";
import {
formatCurrency,
formatDate,
formatNumber,
formatRelativeDate,
formatRelativeTime,
} from "./format";
describe("locale formatters", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("reuses number formatters for repeated locale and option combinations", () => {
const constructorSpy = vi.spyOn(Intl, "NumberFormat");
expect(formatNumber(1_234.5, "en-US", { maximumFractionDigits: 1 })).toBe("1,234.5");
expect(formatNumber(9_876.5, "en-US", { maximumFractionDigits: 1 })).toBe("9,876.5");
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
test("keeps separate number formatters for different options", () => {
const constructorSpy = vi.spyOn(Intl, "NumberFormat");
expect(formatNumber(1_234.5, "en-US", { minimumFractionDigits: 3 })).toBe("1,234.500");
expect(formatNumber(1_234.5, "en-US", { minimumFractionDigits: 4 })).toBe("1,234.5000");
expect(constructorSpy).toHaveBeenCalledTimes(2);
});
test("reuses currency formatter instances", () => {
const constructorSpy = vi.spyOn(Intl, "NumberFormat");
expect(formatCurrency(42, "USD", "en-US")).toBe("$42.00");
expect(formatCurrency(99, "USD", "en-US")).toBe("$99.00");
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
test("reuses date-time formatters for repeated locale and options", () => {
const constructorSpy = vi.spyOn(Intl, "DateTimeFormat");
const options: Intl.DateTimeFormatOptions = { dateStyle: "medium", timeZone: "UTC" };
expect(formatDate("2026-05-27T10:30:00.000Z", "en-US", options)).toBe("May 27, 2026");
expect(formatDate("2026-05-28T10:30:00.000Z", "en-US", options)).toBe("May 28, 2026");
expect(constructorSpy).toHaveBeenCalledTimes(1);
});
test("preserves relative date output", () => {
const relativeTo = new Date("2026-05-27T10:00:00.000Z");
expect(formatRelativeDate("2026-05-26T10:00:00.000Z", "en-US", { relativeTo })).toBe("yesterday");
expect(formatRelativeDate("2026-05-28T10:00:00.000Z", "en-US", { relativeTo })).toBe("tomorrow");
});
test("preserves relative time output", () => {
expect(formatRelativeTime(-2, "day", "en-US")).toBe("2 days ago");
expect(formatRelativeTime(3, "hour", "en-US")).toBe("in 3 hours");
});
});