import { afterEach, describe, expect, it, vi } from 'vitest' import { ago, watch } from './ago' /** * Where the unit steps, and the one reading that is not a duration. * * The boundaries matter because a list is read down: 59 seconds and 1 minute * are next to each other in a column, and a rule that rounds 90 seconds to * "2m" reports a trade as older than it is. The negative case matters because * a venue's clock and a reader's are two clocks — one a little ahead of the * other is ordinary, and "in -3 seconds" is not a thing that happened. */ const now = Date.UTC(2026, 0, 1, 12, 0, 0) const back = (ms: number) => ago(now - ms, now) describe('ago', () => { it('counts seconds up to the minute', () => { expect(back(0)).toStrictEqual([0, 'second']) expect(back(1_000)).toStrictEqual([1, 'second']) expect(back(59_000)).toStrictEqual([59, 'second']) }) it('steps to minutes at the minute, and truncates rather than rounds', () => { expect(back(60_000)).toStrictEqual([1, 'minute']) expect(back(90_000)).toStrictEqual([1, 'minute']) expect(back(59 * 60_000)).toStrictEqual([59, 'minute']) }) it('steps to hours at the hour and to days at the day', () => { expect(back(3_600_000)).toStrictEqual([1, 'hour']) expect(back(23 * 3_600_000)).toStrictEqual([23, 'hour']) expect(back(86_400_000)).toStrictEqual([1, 'day']) expect(back(9 * 86_400_000)).toStrictEqual([9, 'day']) }) it('reads a clock that is ahead as just now', () => { expect(ago(now + 3_000, now)).toStrictEqual([0, 'second']) }) it('takes a Date wherever it takes a moment', () => { expect(ago(new Date(now - 120_000), new Date(now))).toStrictEqual([2, 'minute']) }) }) /** * One clock, whatever is drawing a moment. * * A list of activity is fifty of these, and a timer inside each is fifty timers * on fifty phases — the column steps raggedly, one cell at a time, and the page * pays for fifty of them. Nothing on the screen reports either, so it is * checked here. */ describe('watch', () => { afterEach(() => vi.useRealTimers()) it('runs one timer for everything drawing a moment', () => { vi.useFakeTimers() const stop = Array.from({ length: 50 }, () => watch(() => {})) expect(vi.getTimerCount()).toBe(1) stop.forEach((s) => s()) }) it('tells everything the same moment', () => { vi.useFakeTimers() const said: number[] = [] const stop = [ watch((at) => said.push(at)), watch((at) => said.push(at)) ] vi.advanceTimersByTime(15_000) expect(said).toHaveLength(2) expect(said[0]).toBe(said[1]) stop.forEach((s) => s()) }) it('runs nothing while nothing is watching', () => { vi.useFakeTimers() expect(vi.getTimerCount()).toBe(0) const stop = watch(() => {}) expect(vi.getTimerCount()).toBe(1) stop() expect(vi.getTimerCount()).toBe(0) }) })