-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathgetStreamIterator.test.ts
77 lines (57 loc) · 1.87 KB
/
getStreamIterator.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import test from "ava"
import {ReadableStream} from "web-streams-polyfill"
import {stub} from "sinon"
import {getStreamIterator} from "./getStreamIterator.js"
import {isAsyncIterable} from "./isAsyncIterable.js"
test("Returns async iterable for streams w/ Symbol.asyncIterator", t => {
const stream = new ReadableStream()
t.true(isAsyncIterable(getStreamIterator(stream)))
})
test("Iterates over given stream", async t => {
const expected = "Some text"
const stream = new ReadableStream({
pull(controller) {
controller.enqueue(new TextEncoder().encode(expected))
controller.close()
}
})
let actual = ""
const decoder = new TextDecoder()
for await (const chunk of getStreamIterator(stream)) {
actual += decoder.decode(chunk, {stream: true})
}
actual += decoder.decode()
t.is(actual, expected)
})
test("Returns async iterable for streams w/o Symbol.asyncIterator", t => {
const stream = new ReadableStream()
stub(stream, Symbol.asyncIterator).get(() => undefined)
t.false(getStreamIterator(stream) instanceof ReadableStream)
})
test("Iterates over the stream using fallback", async t => {
const expected = "Some text"
const stream = new ReadableStream({
pull(controller) {
controller.enqueue(new TextEncoder().encode(expected))
controller.close()
}
})
stub(stream, Symbol.asyncIterator).get(() => undefined)
let actual = ""
const decoder = new TextDecoder()
for await (const chunk of getStreamIterator(stream)) {
actual += decoder.decode(chunk, {stream: true})
}
actual += decoder.decode()
t.is(actual, expected)
})
test("Throws TypeError for unsupported data sources", t => {
// @ts-expect-error
const trap = () => getStreamIterator({})
t.throws(trap, {
instanceOf: TypeError,
message:
"Unsupported data source: Expected either " +
"ReadableStream or async iterable."
})
})