Files
QueryByHumming/tests/chunker.test.ts
T
836061373 24373e298a feat: implement TXT reader MVP per product/tech design
- Vite + Vue 3 + TS scaffold with hash router (bookshelf / reader)
- core/: encoding detection (UTF-8 strict, GBK fallback, gb18030 last resort),
  paragraph chunker with original-text offsets, offset utils, IndexedDB wrapper
- Reader: windowed paragraph rendering with estimated spacers (constant ~240 DOM
  paragraphs), font-size/line-height settings via CSS vars persisted to localStorage
- Progress: character-offset based, debounced save + flush on back/unload, exact
  restore via binary search; shelf shows percent
- 21 vitest unit tests for core modules
2026-09-13 00:28:06 +08:00

54 lines
2.1 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { splitParagraphs } from '../src/core/chunker'
describe('splitParagraphs', () => {
it('按 \\n 切分并去除首尾空白', () => {
const { paragraphs } = splitParagraphs(' 第一段 \n第二段\n\n 第三段 ')
expect(paragraphs).toEqual(['第一段', '第二段', '第三段'])
})
it('处理 \\r\\n 换行', () => {
const { paragraphs } = splitParagraphs('甲\r\n乙\r\n丙')
expect(paragraphs).toEqual(['甲', '乙', '丙'])
})
it('空行不产生段落,连续空行只算段间距', () => {
const { paragraphs } = splitParagraphs('a\n\n\n\nb')
expect(paragraphs).toEqual(['a', 'b'])
})
it('offsets 与原文对齐:slice 反向校验', () => {
const text = '第一段落内容\n\n第二段落:很长一点。\r\n第三段'
const { paragraphs, offsets } = splitParagraphs(text)
for (let i = 0; i < paragraphs.length; i++) {
const end = i + 1 < offsets.length ? offsets[i + 1] : text.length
// 该段文本必然出现在 text.slice(offsets[i], end) 中
expect(text.slice(offsets[i], end)).toContain(paragraphs[i])
}
expect(text.slice(offsets[0], offsets[0] + paragraphs[0].length)).toBe(paragraphs[0])
expect(text.slice(offsets[1], offsets[1] + paragraphs[1].length)).toBe(paragraphs[1])
})
it('totalChars 等于各段长度之和', () => {
const { paragraphs, offsets, totalChars } = splitParagraphs('hello\nworld!')
expect(totalChars).toBe(paragraphs.reduce((n, p) => n + p.length, 0))
expect(totalChars).toBe(11)
expect(offsets).toEqual([0, 6])
})
it('空文本返回空结果', () => {
const r = splitParagraphs('')
expect(r.paragraphs).toEqual([])
expect(r.offsets).toEqual([])
expect(r.totalChars).toBe(0)
})
it('大文本性能与正确性:10 万段', () => {
const text = Array.from({ length: 100000 }, (_, i) => `第${i}段内容`).join('\n')
const r = splitParagraphs(text)
expect(r.paragraphs.length).toBe(100000)
expect(r.offsets.length).toBe(100000)
expect(text.slice(r.offsets[99999], r.offsets[99999] + 10)).toBe(r.paragraphs[99999])
})
})