-
Notifications
You must be signed in to change notification settings - Fork 654
Expand file tree
/
Copy pathbase64.test.ts
More file actions
77 lines (62 loc) · 1.94 KB
/
Copy pathbase64.test.ts
File metadata and controls
77 lines (62 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { bytesToBase64, stringToBytes } from '@metamask/utils';
import type { File } from 'buffer';
import { decodeBase64, encodeBase64 } from './base64';
import { VirtualFile } from './virtual-file';
// Very basic mock that mimics the base64 encoding logic of the browser
class MockFileReader {
onload?: () => any;
onerror?: () => any;
result?: any;
error?: any;
readAsDataURL(file: File) {
file
.arrayBuffer()
.then((buffer) => {
const u8 = new Uint8Array(buffer);
this.result = `data:application/octet-stream;base64,${bytesToBase64(
u8,
)}`;
this.onload?.();
})
.catch((error) => {
this.error = error;
this.onerror?.();
});
}
}
describe('encodeBase64', () => {
it('encodes vfile to base64', async () => {
const vfile = new VirtualFile(
stringToBytes(JSON.stringify({ foo: 'bar' })),
);
expect(await encodeBase64(vfile)).toBe('eyJmb28iOiJiYXIifQ==');
});
it('uses FileReader API when available', async () => {
Object.defineProperty(globalThis, 'FileReader', {
value: MockFileReader,
});
const vfile = new VirtualFile(
stringToBytes(JSON.stringify({ foo: 'bar' })),
);
expect(await encodeBase64(vfile)).toBe('eyJmb28iOiJiYXIifQ==');
});
it('does not use optimization when running in React Native', async () => {
Object.defineProperty(globalThis, 'FileReader', {
value: MockFileReader,
});
Object.defineProperty(globalThis, 'navigator', {
value: { product: 'ReactNative' },
});
const vfile = new VirtualFile(
stringToBytes(JSON.stringify({ foo: 'bar' })),
);
expect(await encodeBase64(vfile)).toBe('eyJmb28iOiJiYXIifQ==');
});
});
describe('decodeBase64', () => {
it('decodes base64 string to bytes', async () => {
expect(await decodeBase64('eyJmb28iOiJiYXIifQ==')).toStrictEqual(
stringToBytes(JSON.stringify({ foo: 'bar' })),
);
});
});