示例工程 20-network-storage-fetch
20-network-storage-fetch/02-streaming/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readChunks, streamFromParts } from './main.js';
test('逐块读取并拼接文本', async () => {
const result = await readChunks(streamFromParts(['hello ', 'world']));
assert.equal(result.text, 'hello world');
assert.equal(result.count, 2);
assert.deepEqual(result.chunks, ['hello ', 'world']);
});
test('空流返回空文本', async () => {
const result = await readChunks(streamFromParts([]));
assert.equal(result.text, '');
assert.equal(result.count, 0);
});
test('多字节字符被切到两个块时仍能正确解码', async () => {
const bytes = new TextEncoder().encode('a😀b');
const first = bytes.slice(0, 2);
const second = bytes.slice(2);
const result = await readChunks(streamFromParts([first, second]));
assert.equal(result.text, 'a😀b');
assert.equal(result.count, 2);
});
test('单块正常读取', async () => {
const result = await readChunks(streamFromParts(['only']));
assert.equal(result.text, 'only');
assert.equal(result.bytes, 4);
});