|
| 1 | +import { Blob as BlobPolyfill } from "buffer"; |
| 2 | + |
1 | 3 | import { streamCollector } from "./stream-collector"; |
2 | 4 |
|
3 | | -/** |
4 | | - * Have to mock the FileReader behavior in IE, where |
5 | | - * reader.result is null if reads an empty blob. |
6 | | - */ |
| 5 | +// jsdom inaccurate Blob https://github.com/jsdom/jsdom/issues/2555. |
| 6 | +global.Blob = BlobPolyfill as any; |
| 7 | + |
7 | 8 | describe("streamCollector", () => { |
8 | | - let originalFileReader = (global as any).FileReader; |
9 | | - let originalBlob = (global as any).Blob; |
10 | | - beforeAll(() => { |
11 | | - originalFileReader = (global as any).FileReader; |
12 | | - originalBlob = (global as any).Blob; |
13 | | - }); |
14 | | - afterAll(() => { |
15 | | - (global as any).FileReader = originalFileReader; |
16 | | - (global as any).Blob = originalBlob; |
| 9 | + const blobAvailable = typeof Blob === "function"; |
| 10 | + const readableStreamAvailable = typeof ReadableStream === "function"; |
| 11 | + |
| 12 | + (blobAvailable ? it : it.skip)("collects Blob into bytearray", async () => { |
| 13 | + const blobby = new Blob([new Uint8Array([1, 2]), new Uint8Array([3, 4])]); |
| 14 | + const collected = await streamCollector(blobby); |
| 15 | + expect(collected).toEqual(new Uint8Array([1, 2, 3, 4])); |
17 | 16 | }); |
18 | 17 |
|
19 | | - it("returns a Uint8Array when blob is empty and when FileReader data is null(in IE)", (done) => { |
20 | | - (global as any).FileReader = function FileReader() { |
21 | | - this.result = null; //In IE, FileReader.result is null after reading empty blob |
22 | | - this.readAsDataURL = jest.fn().mockImplementation(() => { |
23 | | - if (this.onloadend) { |
24 | | - this.readyState = 2; |
25 | | - this.onloadend(); |
26 | | - } |
27 | | - }); |
28 | | - }; |
29 | | - (global as any).Blob = function Blob() {}; |
30 | | - const dataPromise = streamCollector(new Blob()); |
31 | | - dataPromise.then((data: any) => { |
32 | | - expect(data).toEqual(Uint8Array.from([])); |
33 | | - done(); |
| 18 | + (readableStreamAvailable ? it : it.skip)("collects ReadableStream into bytearray", async () => { |
| 19 | + const stream = new ReadableStream({ |
| 20 | + start(controller) { |
| 21 | + controller.enqueue(new Uint8Array([1, 2])); |
| 22 | + controller.enqueue(new Uint8Array([3, 4])); |
| 23 | + controller.close(); |
| 24 | + }, |
34 | 25 | }); |
| 26 | + const collected = await streamCollector(stream); |
| 27 | + expect(collected).toEqual(new Uint8Array([1, 2, 3, 4])); |
35 | 28 | }); |
36 | 29 | }); |
0 commit comments