Skip to content

Commit

Permalink
fix: support native TextDecoderStream and TextEncoderStream (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
jiri-prokop-pb authored Oct 21, 2024
1 parent 35dc6e8 commit 51f7354
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ This project "fixes" the following global APIs, overriding whichever polyfills t
- `ReadableStream`
- `TextEncoder`
- `TextDecoder`
- `TextEncoderStream`
- `TextDecoderStream`
- `structuredClone()`
- `URL`

Expand Down
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 51f7354

Please sign in to comment.