fix(tests): 修复 CI 失败的测试 - 补充 withTranslation 和 CopyButton mock

- vitest.setup.ts: react-i18next mock 添加 withTranslation HOC(读取 zh/common.json 翻译)
- vitest.setup.ts: 添加 @/components/CopyButton 全局 mock
- App 测试: 补充 withTranslation 导出
- TextMode 测试: 修复多个 CopyButton 实例导致的 getByTestId 冲突,改用 getByRole
This commit is contained in:
雨霖铃
2026-05-27 23:42:44 +08:00
committed by Ubuntu
3 changed files with 70 additions and 6 deletions
+62
View File
@@ -1,5 +1,26 @@
import '@testing-library/jest-dom';
import { afterEach, beforeEach, vi } from 'vitest';
import { readFileSync } from 'fs';
import { resolve } from 'path';
import React from 'react';
// 读取中文翻译文件用于 withTranslation mock
const zhCommon = JSON.parse(
readFileSync(resolve(__dirname, 'i18n/locales/zh/common.json'), 'utf-8'),
);
// 支持嵌套 key 查找,如 "errorBoundary.title" → zhCommon.errorBoundary.title
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function nestedLookup(obj: Record<string, any>, key: string): string | undefined {
const parts = key.split('.');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let current: any = obj;
for (const part of parts) {
if (current == null || typeof current !== 'object') return undefined;
current = current[part];
}
return typeof current === 'string' ? current : undefined;
}
vi.mock('@/utils/useLazyTranslation', () => ({
useLazyTranslation: (ns?: string) => ({
@@ -21,12 +42,53 @@ vi.mock('react-i18next', () => ({
language: 'zh-CN',
},
}),
withTranslation: (ns?: string) => {
const translations = ns === 'common' ? zhCommon : {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (Component: React.ComponentType<any>) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const Wrapped = (props: any) =>
React.createElement(Component, {
...props,
t: (key: string) => nestedLookup(translations, key) || key,
i18n: { language: 'zh-CN', changeLanguage: vi.fn() },
});
Wrapped.displayName = `withTranslation(${Component.displayName || Component.name || 'Component'})`;
return Wrapped;
};
},
initReactI18next: {
type: '3rdParty',
init: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock('@/components/CopyButton', () => ({
CopyButton: ({
text,
tooltip,
onClick,
}: {
text: string;
tooltip?: string;
onClick?: (e: React.MouseEvent) => void;
}) =>
React.createElement(
'button',
{
'aria-label': tooltip || 'copy',
type: 'button',
onClick: async (e: React.MouseEvent) => {
if (text) {
await navigator.clipboard.writeText(text);
}
onClick?.(e);
},
},
'Copy',
),
}));
const storageMock = {
local: {
get: vi.fn().mockImplementation(() => Promise.resolve({})),