|
| 1 | +import dayjs from "dayjs"; |
| 2 | +import { mount, unmount } from "svelte"; |
| 3 | +import SvelteTimeAdvanced from "./SvelteTimeAdvanced.test.svelte"; |
| 4 | + |
| 5 | +describe("svelte-time-advanced", () => { |
| 6 | + let instance: null | Record<string, any> = null; |
| 7 | + const FIXED_DATE = new Date("2024-01-01T00:00:00.000Z"); |
| 8 | + |
| 9 | + beforeEach(() => { |
| 10 | + vi.useFakeTimers(); |
| 11 | + vi.setSystemTime(FIXED_DATE); |
| 12 | + }); |
| 13 | + |
| 14 | + afterEach(() => { |
| 15 | + vi.restoreAllMocks(); |
| 16 | + if (instance) { |
| 17 | + unmount(instance); |
| 18 | + } |
| 19 | + instance = null; |
| 20 | + document.body.innerHTML = ""; |
| 21 | + }); |
| 22 | + |
| 23 | + const getElement = (selector: string) => { |
| 24 | + return document.querySelector(selector) as HTMLElement; |
| 25 | + }; |
| 26 | + |
| 27 | + test("handles edge cases gracefully", async () => { |
| 28 | + const target = document.body; |
| 29 | + instance = mount(SvelteTimeAdvanced, { target }); |
| 30 | + |
| 31 | + // Invalid date should show original value |
| 32 | + const invalidDate = getElement('[data-test="invalid-date"]'); |
| 33 | + expect(invalidDate.innerHTML).toEqual("Invalid Date"); |
| 34 | + |
| 35 | + // Future date relative format |
| 36 | + const futureDate = getElement('[data-test="future-date"]'); |
| 37 | + expect(futureDate.innerHTML).toEqual("in 2 days"); |
| 38 | + |
| 39 | + // Far past date relative format |
| 40 | + const farPastDate = getElement('[data-test="far-past-date"]'); |
| 41 | + expect(farPastDate.innerHTML).toEqual("5 years ago"); |
| 42 | + |
| 43 | + // Empty timestamp |
| 44 | + const emptyTimestamp = getElement('[data-test="empty-timestamp"]'); |
| 45 | + expect(emptyTimestamp.innerHTML).toBeTruthy(); |
| 46 | + }); |
| 47 | + |
| 48 | + test("handles custom formatting", async () => { |
| 49 | + const target = document.body; |
| 50 | + instance = mount(SvelteTimeAdvanced, { target }); |
| 51 | + |
| 52 | + const customFormat = getElement('[data-test="custom-format-function"]'); |
| 53 | + expect(customFormat.innerHTML).toMatch(/^\d{4}-\d{2}-\d{2}$/); |
| 54 | + }); |
| 55 | + |
| 56 | + test("handles different time formats", async () => { |
| 57 | + const target = document.body; |
| 58 | + instance = mount(SvelteTimeAdvanced, { target }); |
| 59 | + |
| 60 | + const differentFormat = getElement('[data-test="different-locale"]'); |
| 61 | + const formattedDate = differentFormat.innerHTML; |
| 62 | + expect(formattedDate).toMatch(/\d{2} de \w+ de \d{4}/); |
| 63 | + }); |
| 64 | + |
| 65 | + test("handles standard format", async () => { |
| 66 | + const target = document.body; |
| 67 | + instance = mount(SvelteTimeAdvanced, { target }); |
| 68 | + |
| 69 | + const standardFormat = getElement('[data-test="multiple-formats"]'); |
| 70 | + expect(standardFormat.innerHTML).toEqual( |
| 71 | + dayjs(FIXED_DATE).format("MMM DD, YYYY"), |
| 72 | + ); |
| 73 | + }); |
| 74 | +}); |
0 commit comments