smartstream/test/test.ts_web.both.ts

67 lines
1.9 KiB
TypeScript

import { expect, tap } from '@push.rocks/tapbundle';
import * as webstream from '../ts_web/index.js';
tap.test('WebDuplexStream fromUInt8Array should read back the same Uint8Array', async () => {
const inputUint8Array = new Uint8Array([1, 2, 3, 4, 5]);
const stream = webstream.WebDuplexStream.fromUInt8Array(inputUint8Array);
const reader = stream.readable.getReader();
let readUint8Array = new Uint8Array();
// Read from the stream
while (true) {
const { value, done } = await reader.read();
if (done) break;
if (value) {
// Concatenate value to readUint8Array
const tempArray = new Uint8Array(readUint8Array.length + value.length);
tempArray.set(readUint8Array, 0);
tempArray.set(value, readUint8Array.length);
readUint8Array = tempArray;
}
}
expect(readUint8Array).toEqual(inputUint8Array);
});
tap.test('WebDuplexStream should handle transform with a write function', async () => {
const input = [1, 2, 3, 4, 5];
const expectedOutput = [2, 4, 6, 8, 10];
const transformStream = new webstream.WebDuplexStream<number, number>({
writeFunction: async (chunk, { push }) => {
// Push the doubled number into the stream
push(chunk * 2);
},
});
const writableStream = transformStream.writable.getWriter();
const readableStream = transformStream.readable.getReader();
const output: number[] = [];
// Read from the stream asynchronously
const readPromise = (async () => {
while (true) {
const { value, done } = await readableStream.read();
if (done) break;
if (value !== undefined) {
output.push(value);
}
}
})();
// Write to the stream
for (const num of input) {
await writableStream.write(num);
}
await writableStream.close();
// Wait for the reading to complete
await readPromise;
// Assert that the output matches the expected transformed data
expect(output).toEqual(expectedOutput);
});
tap.start();