today-plan-date.test.mjs 2.83 KB
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'

const require = createRequire(import.meta.url)
const {
	formatPlanStoreDateLabel,
	canShiftPlanStoreDate,
	shiftPlanStoreDate,
	maskCustomerPhone,
	isPlanStoreDateInRange,
	diffPlanStoreDaysFromToday,
	diffPlanStoreDaysFromAnchor,
	getPlanStoreDateTips,
	PLAN_STORE_DATE_OFFSET_DAYS
} = require('../services/today-plan-date.js')
const timeUtil = require('../../utils/timeFormat/time-utils.js')

describe('today-plan-date', () => {
	const today = timeUtil.getTodayDateStr()

	function shiftDays(offset, base = new Date()) {
		const d = new Date(base)
		d.setDate(d.getDate() + offset)
		return timeUtil.formatDateStr(d)
	}

	it('IT-PLAN-DATE-001: formatPlanStoreDateLabel uses YY-MM-DD and tips', () => {
		const label = formatPlanStoreDateLabel(today, today)
		assert.match(label, /今天/)
		assert.match(label, /\d{2}-\d{2}-\d{2}/)
		assert.match(label, /周/)
	})

	it('IT-PLAN-DATE-002: isPlanStoreDateInRange ±30 days from anchor', () => {
		const anchor = today
		assert.equal(isPlanStoreDateInRange(shiftDays(30, new Date(anchor)), anchor), true)
		assert.equal(isPlanStoreDateInRange(shiftDays(-30, new Date(anchor)), anchor), true)
		assert.equal(isPlanStoreDateInRange(shiftDays(31, new Date(anchor)), anchor), false)
		assert.equal(isPlanStoreDateInRange(shiftDays(-31, new Date(anchor)), anchor), false)
	})

	it('IT-PLAN-DATE-003: shiftPlanStoreDate respects anchor boundary', () => {
		const anchor = today
		const next = shiftPlanStoreDate(today, 1, anchor)
		assert.ok(next)
		assert.equal(canShiftPlanStoreDate(today, 1, anchor), true)
		const plus30 = shiftDays(30, new Date(anchor))
		assert.equal(canShiftPlanStoreDate(plus30, 1, anchor), false)
	})

	it('IT-PLAN-DATE-004: maskCustomerPhone masks 11-digit phone', () => {
		assert.equal(maskCustomerPhone('15712342929'), '157****2929')
		assert.equal(maskCustomerPhone('157****2929'), '157****2929')
	})

	it('IT-PLAN-DATE-005: diffPlanStoreDaysFromToday is 0 for today', () => {
		assert.equal(diffPlanStoreDaysFromToday(today), 0)
	})

	it('IT-PLAN-DATE-006: tips relative to anchorDate not real today', () => {
		const anchor = shiftDays(-15)
		const dayBefore = shiftDays(-1, new Date(anchor))
		const dayAfter = shiftDays(1, new Date(anchor))
		assert.equal(getPlanStoreDateTips(anchor, anchor), '今天')
		assert.equal(getPlanStoreDateTips(dayBefore, anchor), '昨天')
		assert.equal(getPlanStoreDateTips(dayAfter, anchor), '明天')
		assert.equal(getPlanStoreDateTips(shiftDays(-5, new Date(anchor)), anchor), '5天前')
		// 锚点非今天时,相对真实今天可能不是「今天」
		if (anchor !== today) {
			assert.notEqual(getPlanStoreDateTips(anchor), '今天')
		}
	})

	it('IT-PLAN-DATE-007: offset constant is 30', () => {
		assert.equal(PLAN_STORE_DATE_OFFSET_DAYS, 30)
	})
})