/** * highlight.ts 单元测试 * 覆盖内置轻量语法高亮器的安全性与标记输出 */ import { highlight, normalizeLanguage, registerLanguage, getSupportedLanguages } from '../src/highlight'; describe('highlight - 基础', () => { test('未知语言返回转义纯文本', () => { const out = highlight('const x = 1;', 'nonexistent'); expect(out).toBe('const x = 1;'); }); test('支持的语言别名归一化', () => { expect(normalizeLanguage('js')).toBe('javascript'); expect(normalizeLanguage('ts')).toBe('typescript'); expect(normalizeLanguage('py')).toBe('python'); expect(normalizeLanguage('sh')).toBe('bash'); expect(normalizeLanguage('yml')).toBe('yaml'); expect(normalizeLanguage('Java')).toBe('java'); expect(normalizeLanguage('unknown')).toBe(''); expect(normalizeLanguage('')).toBe(''); }); test('关键词被标记', () => { const out = highlight('const x = 1', 'js'); expect(out).toContain('const'); }); test('字符串被标记', () => { const out = highlight('const s = "hello"', 'js'); expect(out).toContain('"hello"'); }); test('注释被标记', () => { const out = highlight('// comment\nconst x = 1', 'js'); expect(out).toContain('// comment'); }); test('数字被标记', () => { const out = highlight('const n = 42', 'js'); expect(out).toContain('42'); }); test('函数调用被标记', () => { const out = highlight('foo(bar)', 'js'); expect(out).toContain('foo'); }); test('python 井号注释与 def 关键词', () => { const out = highlight('# note\ndef main():', 'python'); expect(out).toContain('# note'); expect(out).toContain('def'); }); test('内置全局对象被标记', () => { const out = highlight('console.log("x")', 'js'); expect(out).toContain('console'); }); }); describe('highlight - 安全性', () => { test('HTML 特殊字符被转义,不产生裸标签', () => { const out = highlight('', 'js'); expect(out).not.toContain('"', 'js'); // 所有 span 配对(每开一个 ) const opens = (out.match(//g) || []).length; expect(opens).toBe(closes); expect(out).not.toContain(' { test('注册自定义语言', () => { registerLanguage('foo', { keywords: ['frobnicate'], builtins: [] }); expect(normalizeLanguage('foo')).toBe('foo'); const out = highlight('frobnicate the widget', 'foo'); expect(out).toContain('frobnicate'); }); test('getSupportedLanguages 返回语言列表', () => { const langs = getSupportedLanguages(); expect(Array.isArray(langs)).toBe(true); expect(langs).toContain('javascript'); expect(langs).toContain('typescript'); expect(langs).toContain('python'); }); }); describe('highlight - 环境一致性', () => { test('字符串高亮与引号转义环境无关(jsdom 断言)', () => { const out = highlight('const s = "hi"', 'js'); expect(out).toContain('"hi"'); }); test('引号不被实体化,span 文本保持原样', () => { const out = highlight('"a" + \'b\'', 'js'); expect(out).not.toContain('"'); // 双引号字符串应被完整标记 expect(out).toContain('"a"'); expect(out).toContain("'b'"); }); });