74 lines
2.5 KiB
JavaScript
74 lines
2.5 KiB
JavaScript
import { describe, expect, test } from 'vitest'
|
||
import { formatDate, toDateParam } from './datetime'
|
||
|
||
describe('时间展示格式化', () => {
|
||
test('空值显示为 -', () => {
|
||
expect(formatDate(null)).toBe('-')
|
||
expect(formatDate(undefined)).toBe('-')
|
||
expect(formatDate('')).toBe('-')
|
||
})
|
||
|
||
test('Go 的零值时间显示为 -', () => {
|
||
// 后端 time.Time 零值序列化后的形态,不能落成 0001/1/1
|
||
expect(formatDate('0001-01-01T00:00:00Z')).toBe('-')
|
||
expect(formatDate('0001-01-01 00:00:00')).toBe('-')
|
||
})
|
||
|
||
test('MySQL 的零日期显示为 -', () => {
|
||
expect(formatDate('0000-00-00 00:00:00')).toBe('-')
|
||
expect(formatDate('0000-00-00')).toBe('-')
|
||
})
|
||
|
||
test('无法解析的值显示为 -', () => {
|
||
expect(formatDate('not-a-date')).toBe('-')
|
||
})
|
||
|
||
test('正常值按本地时区展示', () => {
|
||
const value = '2026-09-21T10:30:00Z'
|
||
expect(formatDate(value)).toBe(new Date(value).toLocaleString('zh-CN'))
|
||
})
|
||
|
||
test('传入自定义格式选项时按选项展示', () => {
|
||
const value = '2026-09-21T10:30:00Z'
|
||
const options = { year: 'numeric', month: '2-digit', day: '2-digit' }
|
||
expect(formatDate(value, options)).toBe(new Date(value).toLocaleString('zh-CN', options))
|
||
})
|
||
|
||
test('接受 Date 对象', () => {
|
||
const value = new Date('2026-09-21T10:30:00Z')
|
||
expect(formatDate(value)).toBe(value.toLocaleString('zh-CN'))
|
||
})
|
||
|
||
test('时间戳为 0 时仍按正常时间展示,不当作空值', () => {
|
||
// 0 是合法时间戳(1970-01-01),只有 falsy 才兜底会误伤它
|
||
const value = new Date(0)
|
||
expect(formatDate(0)).toBe(value.toLocaleString('zh-CN'))
|
||
})
|
||
})
|
||
|
||
describe('查询参数日期格式化', () => {
|
||
test('空值返回空串', () => {
|
||
expect(toDateParam(null)).toBe('')
|
||
expect(toDateParam(undefined)).toBe('')
|
||
expect(toDateParam('')).toBe('')
|
||
})
|
||
|
||
test('无法解析的值返回空串', () => {
|
||
expect(toDateParam('not-a-date')).toBe('')
|
||
})
|
||
|
||
test('按本地时区取日期,不因 UTC 换算偏一天', () => {
|
||
// 本地时间当天 00:00。东八区这一刻的 UTC 还是前一天 16:00,
|
||
// 若改用 toISOString() 裁前 10 位会得到 9/20,查询范围整整偏一天。
|
||
expect(toDateParam(new Date(2026, 8, 21))).toBe('2026-09-21')
|
||
})
|
||
|
||
test('月日补零成两位', () => {
|
||
expect(toDateParam(new Date(2026, 0, 5))).toBe('2026-01-05')
|
||
})
|
||
|
||
test('接受日期字符串', () => {
|
||
expect(toDateParam(new Date(2026, 8, 21).toISOString())).toBe('2026-09-21')
|
||
})
|
||
})
|