From 51f73541f5ee4f7d338b2c017b2611647102dcf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ji=C5=99=C3=AD=20Prokop?= Date: Mon, 21 Oct 2024 16:02:51 +0200 Subject: [PATCH] fix: support native `TextDecoderStream` and `TextEncoderStream` (#16) --- README.md | 2 ++ index.js | 2 ++ index.test.js | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/README.md b/README.md index cd469ed..8b882f4 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ This project "fixes" the following global APIs, overriding whichever polyfills t - `ReadableStream` - `TextEncoder` - `TextDecoder` +- `TextEncoderStream` +- `TextDecoderStream` - `structuredClone()` - `URL` diff --git a/index.js b/index.js index a3a0883..f0a0e75 100644 --- a/index.js +++ b/index.js @@ -6,6 +6,8 @@ class FixedJSDOMEnvironment extends JSDOMEnvironment { this.global.TextDecoder = TextDecoder this.global.TextEncoder = TextEncoder + this.global.TextDecoderStream = TextDecoderStream + this.global.TextEncoderStream = TextEncoderStream this.global.ReadableStream = ReadableStream this.global.Blob = Blob diff --git a/index.test.js b/index.test.js index 0b36ed0..c7a6bfe 100644 --- a/index.test.js +++ b/index.test.js @@ -22,6 +22,44 @@ test('exposes "TextDecoder"', () => { ).toBe('hello') }) +test('exposes "TextEncoderStream"', async () => { + expect(globalThis).toHaveProperty('TextEncoderStream') + expect(() => new TextEncoderStream()).not.toThrow() + + const stream = new TextEncoderStream() + const writer = stream.writable.getWriter() + writer.write('hello') + writer.close() + + const reader = stream.readable.getReader() + const chunks = [] + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(...value) + } + expect(Buffer.from(chunks)).toEqual(Buffer.from(new Uint8Array([104, 101, 108, 108, 111]))) +}) + +test('exposes "TextDecoderStream"', async () => { + expect(globalThis).toHaveProperty('TextDecoderStream') + expect(() => new TextDecoderStream()).not.toThrow() + + const stream = new TextDecoderStream() + const writer = stream.writable.getWriter() + writer.write(new Uint8Array([104, 101, 108, 108, 111])) + writer.close() + + const reader = stream.readable.getReader() + const chunks = [] + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(value) + } + expect(chunks.join('')).toBe('hello') +}) + test('exposes "ReadableStream"', () => { expect(globalThis).toHaveProperty('ReadableStream') expect(() => new ReadableStream()).not.toThrow()