Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

6.6 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest';

import {
  confirm,
  formatCost,
  formatNumber,
  outputJson,
  printBoxTable,
  printTable,
  timeUntil,
} from './format';

describe('formatNumber', () => {
  it('should format numbers with commas', () => {
    expect(formatNumber(0)).toBe('0');
    expect(formatNumber(1234)).toBe('1,234');
    expect(formatNumber(1_234_567)).toBe('1,234,567');
  });
});

describe('formatCost', () => {
  it('should format cost with dollar sign', () => {
    expect(formatCost(0)).toBe('$0.00');
    expect(formatCost(1.5)).toBe('$1.50');
    expect(formatCost(123.456)).toBe('$123.46');
  });
});

describe('outputJson', () => {
  const capture = () => {
    const output: string[] = [];
    vi.spyOn(console, 'log').mockImplementation((...args: any[]) => {
      output.push(args.join(' '));
    });
    return output;
  };

  it('prints full JSON when --json is passed without a value (fields === true)', () => {
    const output = capture();

    expect(() => outputJson({ id: '1', name: 'a' }, true)).not.toThrow();
    expect(JSON.parse(output.join('\n'))).toEqual({ id: '1', name: 'a' });

    vi.restoreAllMocks();
  });

  it('filters fields when --json receives a field list', () => {
    const output = capture();

    outputJson({ extra: true, id: '1', name: 'a' }, 'id, name');
    expect(JSON.parse(output.join('\n'))).toEqual({ id: '1', name: 'a' });

    vi.restoreAllMocks();
  });

  it('prints full JSON when fields is undefined', () => {
    const output = capture();

    outputJson([{ id: '1' }]);
    expect(JSON.parse(output.join('\n'))).toEqual([{ id: '1' }]);

    vi.restoreAllMocks();
  });
});

describe('printBoxTable', () => {
  it('should render a basic table', () => {
    const output: string[] = [];
    vi.spyOn(console, 'log').mockImplementation((...args: any[]) => {
      output.push(args.join(' '));
    });

    const columns = [
      { align: 'left' as const, header: 'Name', key: 'name' },
      { align: 'right' as const, header: 'Count', key: 'count' },
    ];

    const rows = [
      { count: '100', name: 'Alice' },
      { count: '2,345', name: 'Bob' },
    ];

    printBoxTable(columns, rows);
    expect(output.join('\n')).toMatchSnapshot();

    vi.restoreAllMocks();
  });

  it('should render a table with title and multi-line cells', () => {
    const output: string[] = [];
    vi.spyOn(console, 'log').mockImplementation((...args: any[]) => {
      output.push(args.join(' '));
    });

    const columns = [
      { align: 'left' as const, header: 'Date', key: 'date' },
      { align: 'left' as const, header: 'Models', key: 'models' },
      { align: 'right' as const, header: ['Total', 'Tokens'], key: 'total' },
      { align: 'right' as const, header: ['Cost', '(USD)'], key: 'cost' },
    ];

    const rows = [
      {
        cost: '$1.23',
        date: '2026-03-01',
        models: ['- claude-opus-4-6', '- gpt-4o'],
        total: '19,134',
      },
      {
        cost: '$0.45',
        date: '2026-03-02',
        models: ['- claude-opus-4-6'],
        total: '5,678',
      },
    ];

    printBoxTable(columns, rows, 'Test Report');
    expect(output.join('\n')).toMatchSnapshot();

    vi.restoreAllMocks();
  });

  it('should render the usage table format', () => {
    const output: string[] = [];
    vi.spyOn(console, 'log').mockImplementation((...args: any[]) => {
      output.push(args.join(' '));
    });

    const columns = [
      { align: 'left' as const, header: 'Date', key: 'date' },
      { align: 'left' as const, header: 'Models', key: 'models' },
      { align: 'right' as const, header: 'Input', key: 'input' },
      { align: 'right' as const, header: 'Output', key: 'output' },
      { align: 'right' as const, header: ['Total', 'Tokens'], key: 'total' },
      { align: 'right' as const, header: 'Requests', key: 'requests' },
      { align: 'right' as const, header: ['Cost', '(USD)'], key: 'cost' },
    ];

    const rows = [
      {
        cost: '$3.56',
        date: '2026-03-01',
        input: '4,190,339',
        models: ['- claude-opus-4-6', '- gemini-3-pro-preview'],
        output: '121,035',
        requests: '69',
        total: '4,311,374',
      },
      {
        cost: '$4.75',
        date: '2026-03-02',
        input: '4,575,189',
        models: ['- claude-opus-4-6'],
        output: '34,885',
        requests: '62',
        total: '4,610,074',
      },
      {
        cost: '$8.31',
        date: 'Total',
        input: '8,765,528',
        models: '',
        output: '155,920',
        requests: '131',
        total: '8,921,448',
      },
    ];

    printBoxTable(columns, rows, 'LobeHub Token Usage Report - Monthly (2026-03)');
    expect(output.join('\n')).toMatchSnapshot();

    vi.restoreAllMocks();
  });
});

describe('printTable', () => {
  it('keeps a multi-line cell on its own row', () => {
    const lines: string[] = [];
    const spy = vi.spyOn(console, 'log').mockImplementation((line: string) => lines.push(line));

    printTable(
      [
        ['tpc_a', 'Check to verify\ncheckItemId: 2d8\r\n  done', '2'],
        ['tpc_b', 'Weekly', '1'],
      ],
      ['ID', 'TITLE', 'HITS'],
    );
    spy.mockRestore();

    expect(lines).toHaveLength(3);
    expect(lines.every((line) => !/[\r\n]/.test(line))).toBe(true);
    expect(lines[1]).toContain('Check to verify checkItemId: 2d8 done');
    // Column widths come from the flattened cell, so the last column stays aligned.
    expect(lines[1].trimEnd().endsWith('  2')).toBe(true);
    expect(lines[2].trimEnd().length).toBe(lines[1].trimEnd().length);
  });
});

describe('timeUntil', () => {
  // `timeAgo` only formats the past; an invitation expiry is in the future and
  // rendered "-604800s ago" through it.
  it('counts down to a future deadline', () => {
    expect(timeUntil(new Date(Date.now() + 3 * 86_400_000 + 60_000))).toBe('in 3d');
    expect(timeUntil(new Date(Date.now() + 90 * 60_000 + 1000))).toBe('in 1h');
  });

  it('reads a past deadline as expired', () => {
    expect(timeUntil(new Date(Date.now() - 1000))).toBe('expired');
  });

  it('degrades an unparseable date to a placeholder', () => {
    expect(timeUntil('not a date')).toBe('-');
  });
});

describe('confirm', () => {
  it('rejects instead of waiting on stdin when there is no terminal', async () => {
    const isTTY = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
    Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: undefined });

    try {
      await expect(confirm('Delete it?')).rejects.toThrow(/Re-run with --yes/);
    } finally {
      if (isTTY) Object.defineProperty(process.stdin, 'isTTY', isTTY);
      else delete (process.stdin as { isTTY?: boolean }).isTTY;
    }
  });
});