Tofu/tests/dates/parseWeekId.test.js

55 lines
2 KiB
JavaScript

import test from 'node:test'
import assert from 'node:assert/strict'
import { getWeekId } from '#tofu/tools/dates/getWeekId.js'
import { getWeekStart } from '#tofu/tools/dates/getWeekStart.js'
import { parseWeekId } from '#tofu/tools/dates/parseWeekId.js'
test('returns the Monday of the requested week at local midnight', () => {
const monday = parseWeekId('2026-W39')
assert.equal(monday.getFullYear(), 2026)
assert.equal(monday.getMonth(), 8)
assert.equal(monday.getDate(), 21)
assert.equal(monday.getHours(), 0)
})
test('returns the Monday of a week that starts in the previous calendar year', () => {
const monday = parseWeekId('2026-W01')
assert.equal(monday.getFullYear(), 2025)
assert.equal(monday.getMonth(), 11)
assert.equal(monday.getDate(), 29)
})
test('returns the Monday of the 53rd week of a long ISO year', () => {
const monday = parseWeekId('2020-W53')
assert.equal(monday.getFullYear(), 2020)
assert.equal(monday.getMonth(), 11)
assert.equal(monday.getDate(), 28)
})
test('returns null on a malformed identifier', () => {
assert.equal(parseWeekId('2026-39'), null)
assert.equal(parseWeekId('2026-W3'), null)
assert.equal(parseWeekId('2026-W391'), null)
assert.equal(parseWeekId('semaine 39'), null)
assert.equal(parseWeekId(''), null)
assert.equal(parseWeekId(null), null)
assert.equal(parseWeekId(undefined), null)
assert.equal(parseWeekId(20263), null)
})
test('returns null on a week number the year does not have', () => {
assert.equal(parseWeekId('2026-W00'), null)
assert.equal(parseWeekId('2026-W54'), null)
// 2025 is a 52-week ISO year.
assert.equal(parseWeekId('2025-W53'), null)
})
test('is the exact inverse of getWeekId over a long series of dates', () => {
const date = new Date(2024, 0, 1)
for (let step = 0; step < 400; step += 1) {
const expected = getWeekStart(date)
const parsed = parseWeekId(getWeekId(date))
assert.equal(parsed.getTime(), expected.getTime(), `round trip failed for ${date.toDateString()}`)
date.setDate(date.getDate() + 3)
}
})