diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts new file mode 100644 index 0000000..6cabae1 --- /dev/null +++ b/frontend/src/lib/utils.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' + +import { formatBytes } from './utils' + +describe('formatBytes', () => { + it('formats zero and whole-byte values', () => { + expect(formatBytes(0)).toBe('0 B') + expect(formatBytes(512)).toBe('512.0 B') + }) + + it('keeps fractional bytes in the byte unit', () => { + expect(formatBytes(0.5)).toBe('0.5 B') + }) + + it('handles invalid sizes without rendering undefined units', () => { + expect(formatBytes(-1)).toBe('0 B') + expect(formatBytes(Number.NaN)).toBe('0 B') + expect(formatBytes(Number.POSITIVE_INFINITY)).toBe('0 B') + }) +}) diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 502c33a..8c2ca65 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -20,10 +20,10 @@ export function formatDuration(seconds: number): string { } export function formatBytes(bytes: number): string { - if (bytes === 0) return '0 B' + if (!Number.isFinite(bytes) || bytes <= 0) return '0 B' const k = 1024 const sizes = ['B', 'KB', 'MB', 'GB', 'TB'] - const i = Math.floor(Math.log(bytes) / Math.log(k)) + const i = Math.min(Math.max(Math.floor(Math.log(bytes) / Math.log(k)), 0), sizes.length - 1) return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}` } diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts new file mode 100644 index 0000000..c44951a --- /dev/null +++ b/frontend/src/test/setup.ts @@ -0,0 +1 @@ +import '@testing-library/jest-dom'