summaryrefslogtreecommitdiff
path: root/js/text_encoding_test.ts
blob: efb841fc672a921d411334f9ae8a388ce2c085f0 (plain)
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
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2018 the Deno authors. All rights reserved. MIT license.
import { test, assert, assertEqual } from "./test_util.ts";

test(function atobSuccess() {
  const text = "hello world";
  const encoded = btoa(text);
  assertEqual(encoded, "aGVsbG8gd29ybGQ=");
});

test(function btoaSuccess() {
  const encoded = "aGVsbG8gd29ybGQ=";
  const decoded = atob(encoded);
  assertEqual(decoded, "hello world");
});

test(function btoaFailed() {
  const text = "你好";
  let err;
  try {
    btoa(text);
  } catch (e) {
    err = e;
  }
  assert(!!err);
  assertEqual(err.name, "InvalidInput");
});

test(function textDecoder() {
  // prettier-ignore
  const fixture = new Uint8Array([
    0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd,
    0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd,
    0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd
  ]);
  const decoder = new TextDecoder();
  assertEqual(decoder.decode(fixture), "������");
});

test(function textDecoder2() {
  // prettier-ignore
  const fixture = new Uint8Array([
    0xf0, 0x9d, 0x93, 0xbd,
    0xf0, 0x9d, 0x93, 0xae,
    0xf0, 0x9d, 0x94, 0x81,
    0xf0, 0x9d, 0x93, 0xbd
  ]);
  const decoder = new TextDecoder();
  assertEqual(decoder.decode(fixture), "𝓽𝓮𝔁𝓽");
});

test(function textDecoderASCII() {
  const fixture = new Uint8Array([0x89, 0x95, 0x9f, 0xbf]);
  const decoder = new TextDecoder("ascii");
  assertEqual(decoder.decode(fixture), "‰•Ÿ¿");
});

test(function textDecoderErrorEncoding() {
  let didThrow = false;
  try {
    const decoder = new TextDecoder("foo");
  } catch (e) {
    didThrow = true;
    assertEqual(e.message, "The encoding label provided ('foo') is invalid.");
  }
  assert(didThrow);
});

test(function textEncoder() {
  const fixture = "������";
  const encoder = new TextEncoder();
  // prettier-ignore
  assertEqual(Array.from(encoder.encode(fixture)), [
    0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd,
    0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd,
    0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd
  ]);
});

test(function textEncoder2() {
  const fixture = "𝓽𝓮𝔁𝓽";
  const encoder = new TextEncoder();
  // prettier-ignore
  assertEqual(Array.from(encoder.encode(fixture)), [
    0xf0, 0x9d, 0x93, 0xbd,
    0xf0, 0x9d, 0x93, 0xae,
    0xf0, 0x9d, 0x94, 0x81,
    0xf0, 0x9d, 0x93, 0xbd
  ]);
});