Files
testing-tool/utils/__tests__/htmlToMarkdown.test.ts
T
LingandRX 689c3faf16 chore: upgrade dependencies (WXT v0.20.26 + low/medium risk deps) (#41)
* feat: 添加 contextMenus 权限和消息类型定义

* feat: 实现右键菜单注册与点击分流逻辑

- 新增 utils/contextMenu.ts 封装菜单配置和解析函数
- 在 background.ts 监听 onInstalled 初始化菜单
- 实现 contextMenus.onClicked 点击事件处理
- 分流逻辑:优先发送到侧边栏,否则打开 options 页面
- 添加 contextMenu 单元测试(15个测试用例)
- 更新 vitest.setup.ts 添加 contextMenus mock

* feat: 实现 Content Script 原位轻量提示 UI

- 新增 uiPopover.ts 实现原位弹窗组件(深色主题、自动定位、自动隐藏)
- 新增 contextMenuHandler.ts 处理右键菜单消息
- 时间戳转换:在点击位置显示转换结果
- 文本统计:显示字符/单词/行数/字节统计
- 更新 messageHandler.ts 挂载右键菜单消息监听

* feat: 实现 React 页面层右键菜单数据联动

- 新增 useContextMenuData Hook 处理右键菜单数据传递
- 重构 Jwt/Base64Converter/TextStatistics/QrCode 页面接收右键数据
- RouterProvider 支持从 URL 参数解析右键菜单数据
- 添加 contextMenu/pendingData 存储键到 StorageSchema
- 添加 useContextMenuData 单元测试(12个测试用例)

* test: 添加 background 单元测试与边界情况处理

- 新增 entrypoints/__tests__/background.test.ts (12个测试用例)
- 超长文本截断限制 (>10000字符)
- Base64 内联图片拦截并返回错误提示
- 更新 parseContextMenuClick 返回 ParseResult 格式
- 更新测试匹配新的返回格式
- lint/typecheck/test 全部通过 (579个测试)

* fix: 修复右键菜单跳转到错误页面的问题

- 将 options 页面路径从 '/entrypoints/options/index.html' 修正为 '/options.html'
- WXT 构建后 entrypoints/options/index.html 会输出为根目录的 options.html

* fix: 修复右键菜单跳转目标为 popup 页面

- 将 fallback 页面从 options.html 改为 popup.html
- popup 页面使用 RouterProvider,可以正确处理 URL 参数并跳转到对应功能页面
- options 页面是独立设置页,不支持 URL 参数路由

* fix: 使用 openPopup() 替代 tabs.create() 打开弹窗

- background.ts: 使用 browser.action.openPopup() 打开 popup 弹窗
- 先保存数据到 storage,然后打开 popup
- RouterProvider.tsx: 初始化时检查 storage 中的 pendingData 并跳转到对应页面
- 移除之前错误的 tabs.create() 方式

* fix: 修复右键菜单数据未传递到目标页面的问题

- RouterProvider 不再提前清除 pendingData
- 让目标页面的 useContextMenuData 来消费和清除数据
- 这样确保 TextStatistics 等页面能正确接收选中的文本

* fix: 修复 popup 已打开时右键菜单不生效的问题

- 在 RouterProvider 中添加对 contextMenu/pendingData 的 storage 变化监听
- 当 pendingData 变化时,自动跳转到对应功能页面
- 解决了 openPopup() 只聚焦已有窗口而不触发重新挂载的问题

* feat: 支持右键菜单图片二维码识别

- 在 qrCodeParser.ts 中添加 parseQrCodeFromUrl 函数,支持从图片 URL 解析二维码
- 在 QrCodeToUrlSection 中使用 useContextMenuData 接收右键菜单传递的图片 URL
- 自动下载图片并解析二维码,显示解析结果

* refactor: 暂时移除图片二维码识别功能

- 删除 qrCode-image 右键菜单配置
- 删除 parseQrCodeFromUrl 函数
- 删除 QrCodeToUrlSection 中的 useContextMenuData 相关代码
- 更新相关测试用例

* feat: 支持右键菜单时间戳转换

- 在 useTimestampConverter 中添加 useContextMenuData hook
- 智能识别输入是时间戳还是日期时间字符串
- 自动切换到对应模式并执行转换
- 时间戳自动识别秒/毫秒单位

* fix: 修复右键菜单功能的多个逻辑漏洞

1. 修复时区硬编码问题 - 使用用户选择的时区而非固定 Asia/Shanghai
2. 修复 openPopup() 失败后数据残留 - 失败时清除 storage 中的待处理数据
3. 统一数据过期时间常量 - 导出 CONTEXT_MENU_DATA_EXPIRY_MS 并统一使用
4. 修复 featureKey 类型断言不安全 - 使用映射表处理非常规菜单 ID

* refactor(qrcode): 提取独立组件并添加单元测试

- 创建 pages/QrCode/types.ts 定义状态类型接口
- 提取 QrCodePreview 组件用于二维码预览和操作
- 提取 ImageUploader 组件封装图片上传、拖拽、粘贴逻辑
- 重构 UrlToQrCodeSection 状态提升到父组件
- 重构 QrCodeToUrlSection 通过回调传递解析结果
- 更新主页面 index.tsx 集中管理所有状态
- 为 QrCodePreview 和 ImageUploader 添加单元测试 (23 个用例)

* refactor(qrcode): 引入通用组件并重构双栏布局

- 引入 SwitchButtonGroup 用于模式切换
- 引入 TextInputArea 用于文本输入和结果展示
- 使用 MUI Grid 构建响应式双栏布局
- 实现 generate/parse 模式下的左右面板内容切换
- 修复 iconColor 颜色格式错误,使用 qrCodePageStyles.primaryColor

* refactor(qrcode): 国际化补充、质量保障与错误处理优化

- 补充 i18n 翻译键(generateMode, parseMode, pasteHint 等)
- 创建 useDebounce Hook 实现输入防抖 (200ms)
- 使用 useRef 解决 useEffect 无限循环问题
- 编写 pages/QrCode 单元测试 (7 个用例)
- 优化右键菜单错误处理,改进用户提示
- 运行 603 个测试全部通过

* refactor(qrcode): 组件化重构,采用 Context + Hook 模式

- 创建 QrCodeContext 和 QrCodeProvider 管理共享状态
- 提取 useQrCode Hook 封装所有状态和业务逻辑
- 创建 GeneratePanel 组件处理二维码生成模式
- 创建 ParsePanel 组件处理二维码解析模式
- 简化 index.tsx 为容器组件 (340行 → 47行)
- 删除未使用的旧组件文件 (QrCodeToUrlSection, UrlToQrCodeSection)
- 清理 types.ts 中未使用的类型定义
- 603 个测试全部通过

* fix(qrcode): 固定二维码预览图片尺寸,避免布局抖动

- 设置 QR_PREVIEW_IMAGE 固定尺寸 250x250
- 与 QRious 生成的二维码大小保持一致
- 解决输入内容变化时预览窗口大小跳动问题

* fix(qrcode): 修复切换 tab 后二维码图片失效问题

- 移除 ImageUploader 组件卸载时的预览 URL 释放逻辑
- 在 useQrCode hook 中统一管理预览 URL 生命周期
- 创建新预览 URL 前释放旧的,避免内存泄漏

* fix(qrcode): 固定图片上传区域高度,避免布局抖动

- 将 DROPZONE 的 minHeight: 200 改为 height: 250
- 与二维码预览图片高度保持一致
- 解决上传图片时 div 高度变化问题

* refactor(qrCode): 优化二维码解析功能

- 将'二维码转 URL'改为'二维码转文本'
- 将解析结果的文本预览框的 placeholder 置为空
- 去除手动解析二维码功能,只保留自动解析

* fix(pageHeader): 使用 MUI 主题色替代硬编码颜色,支持暗色模式

* feat(pageHeader): popup 模式下隐藏 PageHeader 组件

* fix(i18n): 统一使用 useLazyTranslation 避免翻译 key 闪烁

* perf: 配置 manualChunks 拆分 vendor chunk,优化打包体积

- 使用 Vite 插件 manualChunksForHtmlOnly 仅对 HTML 多入口构建生效
- 跳过 background/content-script 的 IIFE 构建(不支持 manualChunks)
- 拆分 vendor-react (193KB)、vendor-mui (326KB)、vendor-i18n (55KB)
- 按需加载 vendor-qr (78KB)、vendor-dnd (45KB)、vendor-markdown (41KB)
- PageErrorBoundary chunk 从 454KB 降至 36KB

* chore: upgrade wxt to v0.20.26 and @wxt-dev/module-react to v1.2.2

* chore: upgrade low-risk dependencies

- react: 19.2.3 → 19.2.6
- react-dom: 19.2.3 → 19.2.6
- dayjs: 1.11.19 → 1.11.20
- marked: 18.0.3 → 18.0.4
- prettier: 3.8.1 → 3.8.3
- terser: 5.46.0 → 5.47.1
- i18next: 26.0.8 → 26.2.0
- react-i18next: 17.0.6 → 17.0.8
- globals: 17.2.0 → 17.6.0
- eslint-plugin-react-hooks: 7.0.1 → 7.1.1
- @typescript-eslint/*: 8.54.0 → 8.59.4
- typescript-eslint: 8.54.0 → 8.59.4
- @testing-library/jest-dom: 6.6.0 → 6.9.1
- @testing-library/react: 16.0.0 → 16.3.2
- @testing-library/user-event: 14.5.2 → 14.6.1
- @testing-library/dom: added as peer dependency
- @types/react: 19.2.7 → 19.2.15
- @types/chrome: 0.1.36 → 0.1.42
- @types/webextension-polyfill: 0.12.4 → 0.12.5

* chore: upgrade medium-risk dependencies

- lint-staged: 16.2.7 → 17.0.5
- jsdom: 25.0.0 → 29.1.1
- @vitejs/plugin-react: 4.3.4 → 6.0.2
- vitest: 2.0.0 → 4.1.7
- @vitest/coverage-v8: upgraded to match vitest
- @webext-core/messaging: 2.3.0 → 3.0.1
- eslint: 9.39.2 → 10.4.0
- @eslint/js: added as new dependency
- @types/marked: removed (marked now provides its own types)

Fixes:
- Fix ref update during render in useQrCode.ts
- Fix ref update during render in useStorageCleaner.ts
- Add error cause in jwt.ts decode function
- Add type assertion for mock functions in htmlToMarkdown.test.ts

* chore(deps): 降级 eslint 版本并移除 @eslint/js

* docs: 精简 AGENTS.md,聚焦高信号信息

* test: 修复测试中的 act() 警告和 clipboard mock 问题

- TextInputArea: 使用 userEvent 替代 fireEvent,用 vi.spyOn 替代 Object.assign mock clipboard
- ImageMode/FileMode: 添加 waitForStorageReady() 等待 useStorageState 异步初始化
2026-05-21 22:12:11 +08:00

266 lines
9.3 KiB
TypeScript

import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { htmlToMarkdown, downloadMarkdownFile, SAMPLE_HTML } from '../htmlToMarkdown';
describe('htmlToMarkdown', () => {
it('returns empty result for empty string', () => {
const result = htmlToMarkdown('');
expect(result.markdown).toBe('');
expect(result.originalLength).toBe(0);
expect(result.markdownLength).toBe(0);
expect(result.hasError).toBe(false);
});
it('returns empty result for whitespace-only string', () => {
const result = htmlToMarkdown(' \n ');
expect(result.markdown).toBe('');
expect(result.hasError).toBe(false);
});
it('converts h1 heading', () => {
const result = htmlToMarkdown('<h1>Hello World</h1>');
expect(result.markdown).toContain('# Hello World');
});
it('converts h2-h6 headings', () => {
const result = htmlToMarkdown(
'<h2>Two</h2><h3>Three</h3><h4>Four</h4><h5>Five</h5><h6>Six</h6>',
);
expect(result.markdown).toContain('## Two');
expect(result.markdown).toContain('### Three');
expect(result.markdown).toContain('#### Four');
expect(result.markdown).toContain('##### Five');
expect(result.markdown).toContain('###### Six');
});
it('converts paragraph', () => {
const result = htmlToMarkdown('<p>This is a paragraph.</p>');
expect(result.markdown).toContain('This is a paragraph.');
});
it('converts strong and b tags', () => {
const result = htmlToMarkdown('<strong>bold</strong> and <b>also bold</b>');
expect(result.markdown).toContain('**bold**');
expect(result.markdown).toContain('**also bold**');
});
it('converts em and i tags', () => {
const result = htmlToMarkdown('<em>italic</em> and <i>also italic</i>');
expect(result.markdown).toContain('*italic*');
expect(result.markdown).toContain('*also italic*');
});
it('converts del and s tags', () => {
const result = htmlToMarkdown('<del>deleted</del> and <s>strikethrough</s>');
expect(result.markdown).toContain('~~deleted~~');
expect(result.markdown).toContain('~~strikethrough~~');
});
it('converts inline code', () => {
const result = htmlToMarkdown('<code>const x = 1;</code>');
expect(result.markdown).toContain('`const x = 1;`');
});
it('converts pre code block', () => {
const result = htmlToMarkdown('<pre><code>line1\nline2</code></pre>');
expect(result.markdown).toContain('```');
expect(result.markdown).toContain('line1');
expect(result.markdown).toContain('line2');
});
it('converts pre code block with language', () => {
const result = htmlToMarkdown(
'<pre><code class="language-javascript">const x = 1;</code></pre>',
);
expect(result.markdown).toContain('```javascript');
expect(result.markdown).toContain('const x = 1;');
});
it('converts anchor links', () => {
const result = htmlToMarkdown('<a href="https://example.com">Link text</a>');
expect(result.markdown).toContain('[Link text](https://example.com)');
});
it('converts anchor links with title', () => {
const result = htmlToMarkdown('<a href="https://example.com" title="Title">Link</a>');
expect(result.markdown).toContain('[Link](https://example.com "Title")');
});
it('converts images', () => {
const result = htmlToMarkdown('<img src="image.png" alt="desc" />');
expect(result.markdown).toContain('![desc](image.png)');
});
it('converts images with title', () => {
const result = htmlToMarkdown('<img src="image.png" alt="desc" title="Title" />');
expect(result.markdown).toContain('![desc](image.png "Title")');
});
it('converts unordered list', () => {
const result = htmlToMarkdown('<ul><li>Item 1</li><li>Item 2</li></ul>');
expect(result.markdown).toContain('- Item 1');
expect(result.markdown).toContain('- Item 2');
});
it('converts ordered list', () => {
const result = htmlToMarkdown('<ol><li>First</li><li>Second</li></ol>');
expect(result.markdown).toContain('1. First');
expect(result.markdown).toContain('2. Second');
});
it('converts ordered list with start attribute', () => {
const result = htmlToMarkdown('<ol start="5"><li>Item</li></ol>');
expect(result.markdown).toContain('5. Item');
});
it('converts blockquote', () => {
const result = htmlToMarkdown('<blockquote><p>Quote text</p></blockquote>');
expect(result.markdown).toContain('> Quote text');
});
it('converts horizontal rule', () => {
const result = htmlToMarkdown('<hr />');
expect(result.markdown).toContain('---');
});
it('converts line break', () => {
const result = htmlToMarkdown('Line 1<br />Line 2');
expect(result.markdown).toContain('\n');
});
it('converts table', () => {
const html =
'<table><tr><th>Name</th><th>Type</th></tr><tr><td>John</td><td>User</td></tr></table>';
const result = htmlToMarkdown(html);
expect(result.markdown).toContain('| Name | Type |');
expect(result.markdown).toContain('| --- | --- |');
expect(result.markdown).toContain('| John | User |');
});
it('ignores script and style tags', () => {
const result = htmlToMarkdown('<script>alert(1)</script><style>.x{}</style><p>text</p>');
expect(result.markdown).not.toContain('alert');
expect(result.markdown).not.toContain('.x{}');
expect(result.markdown).toContain('text');
});
it('handles nested elements', () => {
const result = htmlToMarkdown('<p><strong>bold</strong> and <em>italic</em></p>');
expect(result.markdown).toContain('**bold**');
expect(result.markdown).toContain('*italic*');
});
it('returns hasError false for valid HTML', () => {
const result = htmlToMarkdown('<p>Valid</p>');
expect(result.hasError).toBe(false);
expect(result.error).toBeUndefined();
});
it('returns correct length stats', () => {
const html = '<p>Hello</p>';
const result = htmlToMarkdown(html);
expect(result.originalLength).toBe(html.length);
expect(result.markdownLength).toBe(result.markdown.length);
});
it('handles full HTML document', () => {
const result = htmlToMarkdown(SAMPLE_HTML);
expect(result.hasError).toBe(false);
expect(result.markdown).toContain('# 欢迎使用 HTML 转 Markdown');
expect(result.markdown).toContain('**HTML**');
expect(result.markdown).toContain('*Markdown*');
expect(result.markdown).toContain('```javascript');
expect(result.markdown).toContain('| 名称 | 类型 |');
expect(result.markdown).toContain('> 这是一段引用文本');
});
it('handles plain text without tags', () => {
const result = htmlToMarkdown('Just plain text');
expect(result.markdown).toContain('Just plain text');
expect(result.hasError).toBe(false);
});
it('handles task list items', () => {
const result = htmlToMarkdown(
'<ul><li><input type="checkbox" checked /> Done</li><li><input type="checkbox" /> Todo</li></ul>',
);
expect(result.markdown).toContain('- [x] Done');
expect(result.markdown).toContain('- [ ] Todo');
});
it('handles div and span wrappers', () => {
const result = htmlToMarkdown('<div><span><p>Content</p></span></div>');
expect(result.markdown).toContain('Content');
});
it('handles empty anchor with no text', () => {
const result = htmlToMarkdown('<a href="https://example.com"></a>');
expect(result.markdown).not.toContain('[');
});
it('handles unknown tags gracefully', () => {
const result = htmlToMarkdown('<custom-tag>Content</custom-tag>');
expect(result.markdown).toContain('Content');
});
});
describe('downloadMarkdownFile', () => {
const originalURL = globalThis.URL;
let createObjectURLSpy: ReturnType<typeof vi.fn>;
let revokeObjectURLSpy: ReturnType<typeof vi.fn>;
let clickSpy: ReturnType<typeof vi.fn>;
let appendChildSpy: ReturnType<typeof vi.fn>;
let removeChildSpy: ReturnType<typeof vi.fn>;
beforeEach(() => {
createObjectURLSpy = vi.fn().mockReturnValue('blob:test-url');
revokeObjectURLSpy = vi.fn();
(globalThis as any).URL = {
createObjectURL: createObjectURLSpy,
revokeObjectURL: revokeObjectURLSpy,
};
clickSpy = vi.fn();
appendChildSpy = vi.fn();
removeChildSpy = vi.fn();
const mockLink = {
href: '',
download: '',
click: clickSpy,
};
vi.spyOn(document, 'createElement').mockReturnValue(mockLink as any);
vi.spyOn(document.body, 'appendChild').mockImplementation(appendChildSpy as any);
vi.spyOn(document.body, 'removeChild').mockImplementation(removeChildSpy as any);
});
afterEach(() => {
vi.restoreAllMocks();
(globalThis as any).URL = originalURL;
});
it('should create a blob and trigger download', () => {
downloadMarkdownFile('# Hello', 'test.md');
expect(createObjectURLSpy).toHaveBeenCalledOnce();
expect(clickSpy).toHaveBeenCalledOnce();
expect(appendChildSpy).toHaveBeenCalledOnce();
expect(removeChildSpy).toHaveBeenCalledOnce();
expect(revokeObjectURLSpy).toHaveBeenCalledOnce();
});
it('should use default filename when not provided', () => {
downloadMarkdownFile('content');
const mockLink = (document.createElement as any).mock.results[0].value;
expect(mockLink.download).toBe('export.md');
});
it('should set correct MIME type', () => {
downloadMarkdownFile('content');
const blobArg = createObjectURLSpy.mock.calls[0][0] as Blob;
expect(blobArg.type).toBe('text/markdown;charset=utf-8');
});
});