|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @format |
| 8 | + * @emails oncall+react_native |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict'; |
| 12 | + |
| 13 | +const base64 = require('base64-js'); |
| 14 | +const {TextEncoder, TextDecoder} = require('util'); |
| 15 | + |
| 16 | +describe('binaryToBase64', () => { |
| 17 | + const binaryToBase64 = require('binaryToBase64'); |
| 18 | + |
| 19 | + it('should encode a Uint8Array', () => { |
| 20 | + const input = new TextEncoder().encode('Test string'); |
| 21 | + |
| 22 | + expect(base64ToString(binaryToBase64(input))).toEqual('Test string'); |
| 23 | + }); |
| 24 | + |
| 25 | + it('should encode an ArrayBuffer', () => { |
| 26 | + const input = new TextEncoder().encode('Test string').buffer; |
| 27 | + |
| 28 | + expect(base64ToString(binaryToBase64(input))).toEqual('Test string'); |
| 29 | + }); |
| 30 | + |
| 31 | + it('should encode a DataView', () => { |
| 32 | + const input = new DataView(new TextEncoder().encode('Test string').buffer); |
| 33 | + |
| 34 | + expect(base64ToString(binaryToBase64(input))).toEqual('Test string'); |
| 35 | + }); |
| 36 | + |
| 37 | + it('should not encode a non ArrayBuffer or non typed array', () => { |
| 38 | + const input = ['i', 'n', 'v', 'a', 'l', 'i', 'd']; |
| 39 | + |
| 40 | + expect(() => binaryToBase64(input)).toThrowError(); |
| 41 | + }); |
| 42 | +}); |
| 43 | + |
| 44 | +function base64ToString(base64String) { |
| 45 | + const byteArray = base64.toByteArray(base64String); |
| 46 | + |
| 47 | + return new TextDecoder().decode(byteArray); |
| 48 | +} |
0 commit comments