Tofu/tests/dates/formatDateKey.test.js

34 lines
1.2 KiB
JavaScript

// A time zone behind UTC turns a late evening into the next day in UTC, which is
// exactly the trap toISOString() falls into. node --test runs each test file in its
// own process, so this affects nothing else.
process.env.TZ = 'America/New_York'
import test from 'node:test'
import assert from 'node:assert/strict'
import { formatDateKey } from '#tofu/tools/dates/formatDateKey.js'
test('formats a date as year-month-day', () => {
assert.equal(formatDateKey(new Date(2026, 8, 21)), '2026-09-21')
})
test('pads the month and the day to two digits', () => {
assert.equal(formatDateKey(new Date(2026, 0, 4)), '2026-01-04')
})
test('keeps the local day for a late evening date', () => {
const date = new Date(2026, 8, 21, 23, 0)
assert.equal(formatDateKey(date), '2026-09-21')
// The UTC day is already the 22nd: toISOString() would produce the wrong key.
assert.equal(date.toISOString().slice(0, 10), '2026-09-22')
})
test('keeps the local day just after midnight', () => {
assert.equal(formatDateKey(new Date(2026, 8, 21, 0, 1)), '2026-09-21')
})
test('does not mutate the received date', () => {
const date = new Date(2026, 8, 21, 23, 0)
const before = date.getTime()
formatDateKey(date)
assert.equal(date.getTime(), before)
})