improve date order detection tests with real Intl calls

This commit is contained in:
Horizontal42 2026-08-09 15:57:15 +03:00 • committed by GitHub
parent dcac3ae425
commit 460a12e695
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 6 additions and 32 deletions

View file

@ -13,38 +13,12 @@ describe("datetime", () => {
vi.restoreAllMocks(); vi.restoreAllMocks();
}); });
it("should detect dmy", () => { it("should detect dmy (e.g. en-GB)", () => {
const mockFormatToParts = vi.fn().mockReturnValue([ expect(detectDateOrder("en-GB")).toBe("dmy");
{ type: "day", value: "31" },
{ type: "literal", value: "/" },
{ type: "month", value: "12" },
{ type: "literal", value: "/" },
{ type: "year", value: "2000" },
]);
const mockDateTimeFormat = vi.spyOn(Intl, "DateTimeFormat").mockImplementation(() => ({
formatToParts: mockFormatToParts,
}) as any);
expect(detectDateOrder()).toBe("dmy");
mockDateTimeFormat.mockRestore();
}); });
it("should detect mdy", () => { it("should detect mdy (e.g. en-US)", () => {
const mockFormatToParts = vi.fn().mockReturnValue([ expect(detectDateOrder("en-US")).toBe("mdy");
{ type: "month", value: "12" },
{ type: "literal", value: "/" },
{ type: "day", value: "31" },
{ type: "literal", value: "/" },
{ type: "year", value: "2000" },
]);
const mockDateTimeFormat = vi.spyOn(Intl, "DateTimeFormat").mockImplementation(() => ({
formatToParts: mockFormatToParts,
}) as any);
expect(detectDateOrder()).toBe("mdy");
mockDateTimeFormat.mockRestore();
}); });
it("should default to dmy if neither is found", () => { it("should default to dmy if neither is found", () => {

View file

@ -2,8 +2,8 @@
import { DateOrder } from "./types"; import { DateOrder } from "./types";
/** Does the OS locale write the day or the month first? (31.12 vs 12/31) */ /** Does the OS locale write the day or the month first? (31.12 vs 12/31) */
export function detectDateOrder(): DateOrder { export function detectDateOrder(locale?: string): DateOrder {
const parts = new Intl.DateTimeFormat(undefined, { day: "numeric", month: "numeric", year: "numeric" }) const parts = new Intl.DateTimeFormat(locale, { day: "numeric", month: "numeric", year: "numeric" })
.formatToParts(new Date(2000, 11, 31)); .formatToParts(new Date(2000, 11, 31));
for (const p of parts) { for (const p of parts) {
if (p.type === "day") return "dmy"; if (p.type === "day") return "dmy";