Skip to content

Commit

Permalink
Make test deterministic
Browse files Browse the repository at this point in the history
  • Loading branch information
garronej authored and ddecrulle committed Nov 25, 2024
1 parent cd1e73a commit e31b827
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions web/src/ui/shared/formattedDate/getFormattedDate.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});

0 comments on commit e31b827

Please sign in to comment.