formatters.test.ts 2.08 KB
import { describe, expect, it } from 'vitest';
import { dictionaryLabel, formatDateTime, formatMoney, formatPolicyValue } from './formatters';

// Contract fixtures, not production amount samples: the API currently has no store records.
describe('store numeric display', () => {
  it.each([
    [0, '¥0.00'],
    ['0.00', '¥0.00'],
    ['-12.5', '¥-12.50'],
    ['12345678901234567890.123456', '¥12,345,678,901,234,567,890.123456'],
    ['1,234.50', '¥1,234.50'],
    ['1.234567890123456789e5', '¥123,456.7890123456789'],
    ['1e-7', '¥0.0000001'],
    ['1.2300e2', '¥123.00'],
    ['-0', '¥0.00'],
  ])('preserves exact amount %s instead of rounding or coercing it', (value, expected) => {
    expect(formatMoney(value)).toBe(expected);
  });

  it.each([
    undefined,
    null,
    '',
    '  ',
    'abc',
    '1,23',
    'NaN',
    'Infinity',
    Infinity,
    NaN,
    {},
    '1e999999999',
  ])('does not turn missing or invalid %s into zero', (value) => {
    expect(formatMoney(value)).toBe('—');
  });

  it('uses the authoritative policy unit, preserving zero and unknown units', () => {
    expect(formatPolicyValue('5', 'RATIO')).toBe('5%');
    expect(formatPolicyValue('0', 'RATIO')).toBe('0%');
    expect(formatPolicyValue('12.34', 'AMOUNT')).toBe('¥12.34');
    expect(formatPolicyValue('5', 'FUTURE_UNIT')).toBe('5');
    expect(formatPolicyValue('0.333333333333333333', 'RATIO')).toBe('0.333333333333333333%');
    expect(formatPolicyValue('', 'RATIO')).toBe('—');
  });
});

describe('store labels', () => {
  it('resolves known dictionaries without hiding unknown or zero values', () => {
    expect(dictionaryLabel([{ value: '0', label: '关闭' }], 0)).toBe('关闭');
    expect(dictionaryLabel([], 'NEW_SCENE')).toBe('NEW_SCENE');
    expect(dictionaryLabel(undefined, '')).toBe('—');
  });

  it('formats server date strings without changing their timezone', () => {
    expect(formatDateTime('2026-10-09T12:30:45')).toBe('2026-10-09 12:30:45');
    expect(formatDateTime('2026-10-09 12:30:45')).toBe('2026-10-09 12:30:45');
    expect(formatDateTime(null)).toBe('—');
  });
});