|
1 | 1 | import { describe, expect, it } from 'vitest'; |
2 | 2 |
|
3 | | -import { isNumberLike, parseNumber } from '../number.js'; |
| 3 | +import { formatByteSize, isNumberLike, parseNumber } from '../number.js'; |
4 | 4 |
|
5 | 5 | const NUMBER_LIKE_VALUES = [ |
6 | 6 | 5e3, |
@@ -72,3 +72,54 @@ describe('parseNumber', () => { |
72 | 72 | }); |
73 | 73 | }); |
74 | 74 | }); |
| 75 | + |
| 76 | +describe('formatByteSize', () => { |
| 77 | + it('should return bytes for values less than threshold (SI)', () => { |
| 78 | + expect(formatByteSize(999, true)).toBe('999 B'); |
| 79 | + }); |
| 80 | + it('should return bytes for values less than threshold (Binary)', () => { |
| 81 | + expect(formatByteSize(1023)).toBe('1023 B'); |
| 82 | + }); |
| 83 | + |
| 84 | + it('should format 1 KB correctly (SI)', () => { |
| 85 | + expect(formatByteSize(1000, true)).toBe('1.0 KB'); |
| 86 | + }); |
| 87 | + |
| 88 | + it('should format 1 KiB correctly (Binary)', () => { |
| 89 | + expect(formatByteSize(1024)).toBe('1.0 KiB'); |
| 90 | + }); |
| 91 | + |
| 92 | + it('should format MB correctly with default dp (SI)', () => { |
| 93 | + expect(formatByteSize(1_500_000, true)).toBe('1.5 MB'); |
| 94 | + }); |
| 95 | + |
| 96 | + it('should format MiB correctly with default dp (Binary)', () => { |
| 97 | + expect(formatByteSize(1_572_864)).toBe('1.5 MiB'); // 1024 * 1024 * 1.5 |
| 98 | + }); |
| 99 | + |
| 100 | + it('should format GB correctly with custom dp (SI)', () => { |
| 101 | + expect(formatByteSize(3_000_000_000, true, 2)).toBe('3.00 GB'); |
| 102 | + }); |
| 103 | + |
| 104 | + it('should format GiB correctly with custom dp (Binary)', () => { |
| 105 | + expect(formatByteSize(3_221_225_472, false, 3)).toBe('3.000 GiB'); // 1024^3 * 3 |
| 106 | + }); |
| 107 | + |
| 108 | + it('should handle zero bytes', () => { |
| 109 | + expect(formatByteSize(0)).toBe('0 B'); |
| 110 | + }); |
| 111 | + |
| 112 | + it('should handle negative values', () => { |
| 113 | + expect(formatByteSize(-1024)).toBe('-1.0 KiB'); |
| 114 | + }); |
| 115 | + |
| 116 | + it('should not exceed the unit array length', () => { |
| 117 | + const large = 10 ** 30; // Very large number |
| 118 | + const result = formatByteSize(large, true); |
| 119 | + expect(result.endsWith('YB')).toBe(true); // YB is the last SI unit |
| 120 | + }); |
| 121 | + |
| 122 | + it('should round correctly with dp = 0', () => { |
| 123 | + expect(formatByteSize(1536, false, 0)).toBe('2 KiB'); // 1536 / 1024 = 1.5 → rounded to 2 |
| 124 | + }); |
| 125 | +}); |
0 commit comments