import { fileSizeFormatter, findIndex, formatTime, generateUUID, getUrlValue, humpToUnderline, jsonParse, setCssVar, subString, trim } from '@/utils' import { dateFormatter, formatDate, formatPast2 } from '@/utils/formatTime' describe('utils/index', () => { it('字符串工具', () => { expect(humpToUnderline('leftMenuWidth')).toBe('left-menu-width') expect(trim(' a b ')).toBe('a b') expect(subString('abcdef', 0, 3)).toBe('abc') expect(subString('ab', 0, 3)).toBe('ab') }) it('findIndex 返回首个命中下标', () => { expect(findIndex([1, 2, 3], (v: number) => v > 1)).toBe(1) expect(findIndex([1], (v: number) => v > 5)).toBe(-1) }) it('formatTime 支持年月日时分秒', () => { const date = new Date(2026, 9, 27, 8, 5, 9) expect(formatTime(date, 'yyyy-MM-dd HH:mm:ss')).toBe('2026-10-27 08:05:09') expect(formatTime(date.getTime(), 'yy/M/d')).toBe('26/10/27') expect(formatTime('', 'yyyy')).toBe('') }) it('generateUUID 生成 v4 格式', () => { const id = generateUUID() expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) expect(generateUUID()).not.toBe(id) }) it('fileSizeFormatter 以 1024 进位', () => { expect(fileSizeFormatter(null, null, 1024)).toBe('1.00 KB') expect(fileSizeFormatter(null, null, '1572864')).toBe('1.50 MB') expect(fileSizeFormatter(null, null, 10)).toBe('10.00 Bytes') }) it('getUrlValue 读取查询参数', () => { expect(getUrlValue('id', 'https://a.com/x?id=12&b=2')).toBe('12') expect(getUrlValue('none', 'https://a.com/x?id=12')).toBe('') expect(getUrlValue('', 'https://a.com')).toBe('') }) it('jsonParse 失败时原样返回', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) expect(jsonParse('{"a":1}')).toEqual({ a: 1 }) expect(jsonParse('not json')).toBe('not json') expect(warn).toHaveBeenCalledOnce() }) it('setCssVar 写入样式变量', () => { const el = document.createElement('div') setCssVar('--x', '10px', el) expect(el.style.getPropertyValue('--x')).toBe('10px') }) }) describe('utils/formatTime', () => { it('formatDate 默认格式与自定义格式', () => { const d = new Date(2026, 0, 2, 3, 4, 5) expect(formatDate(d)).toBe('2026-01-02 03:04:05') expect(formatDate(d, 'YYYY/MM/DD')).toBe('2026/01/02') expect(formatDate(null)).toBe('') }) it('formatPast2 把毫秒转成中文时长', () => { expect(formatPast2(0)).toBe('0 秒') expect(formatPast2(5_000)).toBe('5 秒') expect(formatPast2(3 * 60_000)).toBe('3 分钟') expect(formatPast2(2 * 3_600_000 + 60_000)).toBe('2 小时 1 分钟') expect(formatPast2(26 * 3_600_000)).toBe('1 天2 小时 0 分钟') }) it('dateFormatter 用于表格列', () => { expect(dateFormatter({}, {}, new Date(2026, 9, 1))).toBe('2026-10-01 00:00:00') expect(dateFormatter({}, {}, undefined)).toBe('') }) })