|
| 1 | +import { decodeBase64url, encodeBase64url } from './base64url' |
| 2 | + |
| 3 | +describe('encodeBase64url / decodeBase64url', () => { |
| 4 | + it('should encode and decode Uint8Array correctly', () => { |
| 5 | + const original = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]) |
| 6 | + const encoded = encodeBase64url(original) |
| 7 | + const decoded = decodeBase64url(encoded) |
| 8 | + |
| 9 | + expect(decoded).toEqual(original) |
| 10 | + }) |
| 11 | + |
| 12 | + it('should produce URL-safe output without padding', () => { |
| 13 | + const data = new Uint8Array([255, 254, 253]) // Will produce +/= characters in regular base64 |
| 14 | + const encoded = encodeBase64url(data) |
| 15 | + |
| 16 | + expect(encoded).not.toMatch(/[+/=]/) |
| 17 | + expect(encoded).toMatch(/^[\w-]+$/) |
| 18 | + }) |
| 19 | + |
| 20 | + it('should handle empty data', () => { |
| 21 | + const empty = new Uint8Array([]) |
| 22 | + const encoded = encodeBase64url(empty) |
| 23 | + const decoded = decodeBase64url(encoded) |
| 24 | + |
| 25 | + expect(encoded).toBe('') |
| 26 | + expect(decoded).toEqual(empty) |
| 27 | + }) |
| 28 | + |
| 29 | + it('should work with TextEncoder/TextDecoder', () => { |
| 30 | + const text = 'Hello World' |
| 31 | + const encoded = encodeBase64url(new TextEncoder().encode(text)) |
| 32 | + const decoded = decodeBase64url(encoded) |
| 33 | + |
| 34 | + expect(new TextDecoder().decode(decoded)).toEqual(text) |
| 35 | + }) |
| 36 | + |
| 37 | + it('should handle large data without call stack overflow', () => { |
| 38 | + // Create a large Uint8Array (100KB) |
| 39 | + const largeData = new Uint8Array(100 * 1024) |
| 40 | + for (let i = 0; i < largeData.length; i++) { |
| 41 | + largeData[i] = i % 256 |
| 42 | + } |
| 43 | + |
| 44 | + const encoded = encodeBase64url(largeData) |
| 45 | + const decoded = decodeBase64url(encoded) |
| 46 | + |
| 47 | + expect(decoded).toEqual(largeData) |
| 48 | + expect(encoded).not.toMatch(/[+/=]/) // Should still be URL-safe |
| 49 | + }) |
| 50 | + |
| 51 | + it('should handle invalid input gracefully', () => { |
| 52 | + expect(decodeBase64url(null)).toBeUndefined() |
| 53 | + expect(decodeBase64url(undefined)).toBeUndefined() |
| 54 | + expect(decodeBase64url('invalid base64!')).toBeUndefined() |
| 55 | + }) |
| 56 | +}) |
0 commit comments