57 lines
2.1 KiB
JavaScript
57 lines
2.1 KiB
JavaScript
// 用 node:test 验证 core.js 的纯逻辑函数
|
|
import { test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { createRequire } from 'node:module';
|
|
|
|
const require = createRequire(import.meta.url);
|
|
const Core = require('./core.js');
|
|
|
|
test('decodeText: UTF-8 正常解码', () => {
|
|
const buf = Buffer.from('春江潮水连海平', 'utf8');
|
|
assert.equal(Core.decodeText(buf), '春江潮水连海平');
|
|
});
|
|
|
|
test('decodeText: GBK 编码回退不乱码', () => {
|
|
// "山中何所有" 的 GBK 字节序列(Node Buffer 不支持 gbk 编码,手工构造)
|
|
const buf = new Uint8Array([0xc9, 0xbd, 0xd6, 0xd0, 0xba, 0xce, 0xcb, 0xf9, 0xd3, 0xd0]);
|
|
const text = Core.decodeText(buf);
|
|
assert.equal(text, '山中何所有');
|
|
});
|
|
|
|
test('splitParagraphs: 过滤空行并按换行分段', () => {
|
|
const ps = Core.splitParagraphs('第一段\n\n 第二段 \r\n\r\n第三段');
|
|
assert.deepEqual(ps, ['第一段', '第二段', '第三段']);
|
|
});
|
|
|
|
test('buildChunks: 按字符数分块且偏移连续', () => {
|
|
const ps = Core.splitParagraphs('aaa\nbbbb\ncc\nddddd');
|
|
const chunks = Core.buildChunks(ps, 5);
|
|
// 段落偏移: 0, 3, 7, 9; 总长 14
|
|
let covered = 0;
|
|
for (const c of chunks) {
|
|
assert.ok(c.items.length > 0);
|
|
assert.equal(c.startOffset, c.items[0].offset);
|
|
for (const it of c.items) covered += it.text.length;
|
|
}
|
|
assert.equal(covered, 14);
|
|
});
|
|
|
|
test('offsetFromViewport: 二分查找返回视口内段落偏移', () => {
|
|
const offsets = [0, 10, 20, 30];
|
|
const tops = [0, 100, 200, 300];
|
|
assert.equal(Core.offsetFromViewport(offsets, 0, tops), 0);
|
|
assert.equal(Core.offsetFromViewport(offsets, 150, tops), 10);
|
|
assert.equal(Core.offsetFromViewport(offsets, 999, tops), 30);
|
|
});
|
|
|
|
test('progressPercent: 边界处理', () => {
|
|
assert.equal(Core.progressPercent(0, 100), 0);
|
|
assert.equal(Core.progressPercent(50, 100), 50);
|
|
assert.equal(Core.progressPercent(200, 100), 100);
|
|
assert.equal(Core.progressPercent(0, 0), 0);
|
|
});
|
|
|
|
test('formatTime: 格式化为 YYYY-MM-DD HH:mm', () => {
|
|
assert.equal(Core.formatTime(new Date(2026, 8, 12, 9, 5).getTime()), '2026-09-12 09:05');
|
|
});
|