smartstream/test/test.ts_web.both.ts

67 lines
1.9 KiB
TypeScript
Raw Normal View History

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