Skip to content

Commit

Permalink
feat: [#1500] Adds support for Blob.stream() (#1500)
Browse files Browse the repository at this point in the history
Co-authored-by: David Ortner <david@ortner.se>
  • Loading branch information
PlopAndRun and capricorn86 authored Aug 29, 2024
1 parent 6aa044d commit fec1c01
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/happy-dom/src/file/Blob.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Buffer } from 'buffer';
import { ReadableStream } from 'stream/web';
import * as PropertySymbol from '../PropertySymbol.js';

/**
Expand Down Expand Up @@ -136,6 +137,21 @@ export default class Blob {
return this[PropertySymbol.buffer].toString();
}

/**
* Returns returns a ReadableStream which upon reading returns the data contained within the Blob.
*
* @returns ReadableStream
*/
public stream(): ReadableStream {
const buffer = this[PropertySymbol.buffer];
return new ReadableStream({
start(controller) {
controller.enqueue(buffer);
controller.close();
}
});
}

/**
* Returns the object converted to string.
*
Expand Down
18 changes: 18 additions & 0 deletions packages/happy-dom/test/file/Blob.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ describe('Blob', () => {
});
});

describe('stream()', () => {
it('Returns all data in a ReadableStream.', async () => {
const data = 'Test1Test2';
const blob = new Blob(['Test1', 'Test2']);
const stream = blob.stream();

let i = 0;
for await (const chunk of stream.values()) {
for (const value of chunk) {
expect(i).toBeLessThan(data.length);
expect(value).toBe(data[i].charCodeAt(0));
++i;
}
}
expect(i).toBe(data.length);
});
});

describe('toString()', () => {
it('Returns "[object Blob]".', () => {
const blob = new Blob(['TEST']);
Expand Down

0 comments on commit fec1c01

Please sign in to comment.