/
readable_stream_from_iterable_test.ts
54 lines (46 loc) · 1.7 KB
/
readable_stream_from_iterable_test.ts
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
import { assertEquals } from "../testing/asserts.ts";
import { readableStreamFromIterable } from "./readable_stream_from_iterable.ts";
Deno.test("[streams] readableStreamFromIterable() array", async function () {
const strings: string[] = ["hello", "deno", "land"];
const encoder = new TextEncoder();
const readableStream = readableStreamFromIterable(
strings.map((s) => encoder.encode(s)),
);
const readStrings = [];
const decoder = new TextDecoder();
for await (const chunk of readableStream) {
readStrings.push(decoder.decode(chunk));
}
assertEquals(readStrings, strings);
});
Deno.test("[streams] readableStreamFromIterable() generator", async function () {
const strings: string[] = ["hello", "deno", "land"];
const readableStream = readableStreamFromIterable((function* () {
const encoder = new TextEncoder();
for (const string of strings) {
yield encoder.encode(string);
}
})());
const readStrings = [];
const decoder = new TextDecoder();
for await (const chunk of readableStream) {
readStrings.push(decoder.decode(chunk));
}
assertEquals(readStrings, strings);
});
Deno.test("[streams] readableStreamFromIterable() cancel", async function () {
let generatorError = null;
const readable = readableStreamFromIterable(async function* () {
try {
yield "foo";
} catch (error) {
generatorError = error;
}
}());
const reader = readable.getReader();
assertEquals(await reader.read(), { value: "foo", done: false });
const cancelReason = new Error("Cancelled by consumer.");
await reader.cancel(cancelReason);
assertEquals(generatorError, cancelReason);
});