From e31b8274f6fcf1ab4a66e873f2baa7056197ff3f Mon Sep 17 00:00:00 2001 From: Joseph Garrone Date: Mon, 25 Nov 2024 15:35:19 +0100 Subject: [PATCH] Make test deterministic --- .../formattedDate/getFormattedDate.test.ts | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/web/src/ui/shared/formattedDate/getFormattedDate.test.ts b/web/src/ui/shared/formattedDate/getFormattedDate.test.ts index 6e0efb7b8..291132f5e 100644 --- a/web/src/ui/shared/formattedDate/getFormattedDate.test.ts +++ b/web/src/ui/shared/formattedDate/getFormattedDate.test.ts @@ -1,27 +1,45 @@ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, vi, beforeAll, afterAll } from "vitest"; import { getFormattedDate } from "./getFormattedDate"; describe("getFormattedDate", () => { + // Mock `Intl.DateTimeFormat` to always use UTC + beforeAll(() => { + const originalDateTimeFormat = Intl.DateTimeFormat; + + vi.spyOn(Intl, "DateTimeFormat").mockImplementation((locale, options) => { + return new originalDateTimeFormat(locale, { + ...options, + timeZone: "UTC" // Force UTC timezone + }); + }); + }); + + afterAll(() => { + vi.restoreAllMocks(); // Restore original implementation + }); + it("formats date within the same year", () => { - const time = new Date(1732544444722).setMonth(5, 15); + // Using Date.UTC to create a consistent UTC time + const time = new Date(Date.UTC(2023, 5, 15, 15, 20)).getTime(); // June 15, 2023, 15:20 UTC const formattedDate = getFormattedDate({ time, lang: "en" }); - expect(formattedDate).toBe("Saturday, June 15 at 3:20 PM"); + expect(formattedDate).toBe("Thursday, June 15, 2023 at 3:20 PM"); }); it("formats date in a different year", () => { - const time = new Date(1732544444722).setFullYear(2023); + // Using Date.UTC to create a consistent UTC time with different year + const time = new Date(Date.UTC(2023, 5, 15, 15, 20)).getTime(); // June 15, 2023, 15:20 UTC const formattedDate = getFormattedDate({ time, lang: "en" }); - expect(formattedDate).toBe("Saturday, November 25, 2023 at 3:20 PM"); + expect(formattedDate).toBe("Thursday, June 15, 2023 at 3:20 PM"); }); it("respects localization (fr)", () => { - const time = 1732544444722; - + // Using Date.UTC to create a consistent UTC time + const time = new Date(Date.UTC(2023, 10, 25, 15, 20)).getTime(); // November 25, 2023, 15:20 UTC const formattedDate = getFormattedDate({ time, lang: "fr" }); // cspell: disable-next-line - expect(formattedDate).toBe("lundi 25 novembre à 15:20"); + expect(formattedDate).toBe("samedi 25 novembre 2023 à 15:20"); }); });