Merge branch 'main' into develop
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
// unmock the globally-mocked component so we test the real implementation
|
||||
vi.unmock('@/components/CopyButton');
|
||||
|
||||
vi.mock('@/utils/clipboard', () => ({
|
||||
copyTextToClipboard: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { CopyButton } from '@/components/CopyButton';
|
||||
import { copyTextToClipboard } from '@/utils/clipboard';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
const mockedCopy = vi.mocked(copyTextToClipboard);
|
||||
const mockedToast = vi.mocked(toast);
|
||||
|
||||
describe('CopyButton', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('复制成功时调用 copyTextToClipboard 并传入正确 text', async () => {
|
||||
mockedCopy.mockResolvedValue(true);
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
|
||||
render(<CopyButton text="hello world" />);
|
||||
|
||||
await user.click(screen.getByRole('button'));
|
||||
|
||||
expect(mockedCopy).toHaveBeenCalledWith('hello world');
|
||||
expect(mockedToast.success).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('复制成功后图标切换为 Check,1.5 秒后恢复', async () => {
|
||||
mockedCopy.mockResolvedValue(true);
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
|
||||
render(<CopyButton text="test" />);
|
||||
|
||||
// 点击后复制成功,按钮获得 emerald 样式(说明切到了 Check 状态)
|
||||
await user.click(screen.getByRole('button'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button').className).toContain('text-emerald');
|
||||
});
|
||||
|
||||
// 1.5 秒后样式恢复
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1500);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button').className).not.toContain('text-emerald');
|
||||
});
|
||||
});
|
||||
|
||||
it('复制空文本时弹出 error toast', async () => {
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
|
||||
render(<CopyButton text="" />);
|
||||
|
||||
await user.click(screen.getByRole('button'));
|
||||
|
||||
expect(mockedCopy).not.toHaveBeenCalled();
|
||||
expect(mockedToast.error).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('复制失败时弹出 error toast', async () => {
|
||||
mockedCopy.mockResolvedValue(false);
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
|
||||
render(<CopyButton text="something" />);
|
||||
|
||||
await user.click(screen.getByRole('button'));
|
||||
|
||||
expect(mockedCopy).toHaveBeenCalledWith('something');
|
||||
expect(mockedToast.error).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// ==================== 新增测试 ====================
|
||||
|
||||
it('初始渲染时显示 Copy 图标且无 emerald 样式', () => {
|
||||
render(<CopyButton text="initial" />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button.className).not.toContain('text-emerald');
|
||||
// 通过 aria-label 确认按钮存在,图标由 lucide 渲染为 svg
|
||||
expect(button).toHaveAttribute('aria-label');
|
||||
});
|
||||
|
||||
it('自定义 tooltip 会覆盖默认 title 和 aria-label', () => {
|
||||
render(<CopyButton text="tooltip-test" tooltip="自定义提示" />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveAttribute('title', '自定义提示');
|
||||
expect(button).toHaveAttribute('aria-label', '自定义提示');
|
||||
});
|
||||
|
||||
it('className 被正确透传到按钮', () => {
|
||||
render(<CopyButton text="class-test" className="my-custom-class" />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button.className).toContain('my-custom-class');
|
||||
});
|
||||
|
||||
it('点击事件阻止冒泡', async () => {
|
||||
mockedCopy.mockResolvedValue(true);
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
const parentClick = vi.fn();
|
||||
|
||||
render(
|
||||
<div onClick={parentClick}>
|
||||
<CopyButton text="stop-propagation" />
|
||||
</div>,
|
||||
);
|
||||
|
||||
await user.click(screen.getByRole('button'));
|
||||
|
||||
expect(mockedCopy).toHaveBeenCalled();
|
||||
expect(parentClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('组件卸载时清除定时器,不触发状态更新警告', async () => {
|
||||
mockedCopy.mockResolvedValue(true);
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
|
||||
const { unmount } = render(<CopyButton text="unmount-test" />);
|
||||
|
||||
await user.click(screen.getByRole('button'));
|
||||
|
||||
// 在 1.5 秒超时到期前卸载组件
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(500);
|
||||
});
|
||||
|
||||
// 卸载不应抛出 "Can't perform a React state update on an unmounted component" 警告
|
||||
expect(() => unmount()).not.toThrow();
|
||||
|
||||
// 前进剩余时间,确认没有异常
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(2000);
|
||||
});
|
||||
});
|
||||
|
||||
it('快速连续点击不会创建多个重叠定时器', async () => {
|
||||
mockedCopy.mockResolvedValue(true);
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
|
||||
render(<CopyButton text="rapid-click" />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
|
||||
// 快速点击 3 次
|
||||
await user.click(button);
|
||||
await user.click(button);
|
||||
await user.click(button);
|
||||
|
||||
// copyTextToClipboard 应该被调用 3 次(每次点击都执行)
|
||||
expect(mockedCopy).toHaveBeenCalledTimes(3);
|
||||
|
||||
// 但 setTimeout 相关的 clearTimeout + setTimeout 组合应正常工作
|
||||
// advance 1.5 秒后,copied 状态应恢复为 false
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1500);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(button.className).not.toContain('text-emerald');
|
||||
});
|
||||
});
|
||||
|
||||
it('其他 button props 通过 ...props 透传', () => {
|
||||
render(<CopyButton text="props-test" data-testid="copy-btn" disabled id="copy-button-id" />);
|
||||
|
||||
const button = screen.getByRole('button');
|
||||
expect(button).toHaveAttribute('data-testid', 'copy-btn');
|
||||
expect(button).toBeDisabled();
|
||||
expect(button).toHaveAttribute('id', 'copy-button-id');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* 生成器内部类型定义
|
||||
* 与 testDataGenerator.ts 分离,用于生成器库内部
|
||||
*/
|
||||
|
||||
import type { GeneratorDefinition, GeneratorCategory } from '@/types/testDataGenerator';
|
||||
|
||||
export type { GeneratorDefinition, GeneratorCategory };
|
||||
|
||||
/**
|
||||
* 生成器注册表
|
||||
*/
|
||||
export interface GeneratorRegistry {
|
||||
/** 分类列表 */
|
||||
categories: GeneratorCategory[];
|
||||
/** 生成器列表 */
|
||||
generators: GeneratorDefinition[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 随机数生成选项
|
||||
*/
|
||||
export interface RandomOptions {
|
||||
/** 最小值 */
|
||||
min?: number;
|
||||
/** 最大值 */
|
||||
max?: number;
|
||||
/** 是否包含最小值 */
|
||||
includeMin?: boolean;
|
||||
/** 是否包含最大值 */
|
||||
includeMax?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符集选项
|
||||
*/
|
||||
export interface CharsetOptions {
|
||||
/** 是否包含大写字母 */
|
||||
uppercase?: boolean;
|
||||
/** 是否包含小写字母 */
|
||||
lowercase?: boolean;
|
||||
/** 是否包含数字 */
|
||||
digits?: boolean;
|
||||
/** 是否包含特殊字符 */
|
||||
special?: boolean;
|
||||
/** 自定义字符集 */
|
||||
custom?: string;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useGenerator } from '@/pages/TestDataGenerator/hooks/useGenerator';
|
||||
import type { FieldConfig, WorkerResponseMessage } from '@/types/testDataGenerator';
|
||||
|
||||
const mockField: FieldConfig = {
|
||||
id: 'field-1',
|
||||
name: 'username',
|
||||
generatorId: 'string',
|
||||
params: {},
|
||||
required: true,
|
||||
nullRate: 0,
|
||||
unique: false,
|
||||
};
|
||||
|
||||
type WorkerListener = (event: MessageEvent<WorkerResponseMessage>) => void;
|
||||
|
||||
class MockWorker {
|
||||
static instances: MockWorker[] = [];
|
||||
onmessage: WorkerListener | null = null;
|
||||
onerror: ((event: ErrorEvent) => void) | null = null;
|
||||
postedMessages: unknown[] = [];
|
||||
|
||||
constructor(_url: URL, _options?: WorkerOptions) {
|
||||
MockWorker.instances.push(this);
|
||||
}
|
||||
|
||||
postMessage(message: unknown) {
|
||||
this.postedMessages.push(message);
|
||||
}
|
||||
|
||||
terminate() {
|
||||
const index = MockWorker.instances.indexOf(this);
|
||||
if (index >= 0) {
|
||||
MockWorker.instances.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
emit(message: WorkerResponseMessage) {
|
||||
this.onmessage?.({ data: message } as MessageEvent<WorkerResponseMessage>);
|
||||
}
|
||||
}
|
||||
|
||||
describe('useGenerator', () => {
|
||||
beforeEach(() => {
|
||||
MockWorker.instances = [];
|
||||
vi.stubGlobal('Worker', MockWorker);
|
||||
});
|
||||
|
||||
it('应忽略过期 generationId 的 complete 消息', async () => {
|
||||
const { result } = renderHook(() => useGenerator());
|
||||
|
||||
act(() => {
|
||||
result.current.generate([mockField], 10);
|
||||
});
|
||||
|
||||
const worker = MockWorker.instances[0];
|
||||
expect(worker).toBeDefined();
|
||||
|
||||
act(() => {
|
||||
result.current.cancel();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.generate([mockField], 5);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
worker.emit({
|
||||
type: 'complete',
|
||||
generationId: 1,
|
||||
payload: {
|
||||
success: true,
|
||||
data: [{ username: 'stale' }],
|
||||
stats: { total: 10, success: 10, failed: 0, duration: 1 },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.current.result).toBeNull();
|
||||
expect(result.current.isGenerating).toBe(true);
|
||||
|
||||
act(() => {
|
||||
worker.emit({
|
||||
type: 'complete',
|
||||
generationId: 3,
|
||||
payload: {
|
||||
success: true,
|
||||
data: [{ username: 'fresh' }],
|
||||
stats: { total: 5, success: 5, failed: 0, duration: 1 },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isGenerating).toBe(false);
|
||||
});
|
||||
expect(result.current.result?.data?.[0]).toEqual({ username: 'fresh' });
|
||||
});
|
||||
|
||||
it('cancel 后应发送 cancel 消息并使 generationId 失效', () => {
|
||||
const { result } = renderHook(() => useGenerator());
|
||||
|
||||
act(() => {
|
||||
result.current.generate([mockField], 100);
|
||||
});
|
||||
|
||||
const worker = MockWorker.instances[0];
|
||||
|
||||
act(() => {
|
||||
result.current.cancel();
|
||||
});
|
||||
|
||||
expect(result.current.isGenerating).toBe(false);
|
||||
expect(worker.postedMessages).toEqual(expect.arrayContaining([{ type: 'cancel' }]));
|
||||
});
|
||||
});
|
||||
@@ -118,6 +118,7 @@ export default function TestDataGeneratorPage() {
|
||||
[clearResult],
|
||||
);
|
||||
|
||||
// 保存规则成功后清除编辑状态
|
||||
const handleRuleSaved = useCallback(() => {
|
||||
setEditingRule(null);
|
||||
}, []);
|
||||
@@ -128,7 +129,6 @@ export default function TestDataGeneratorPage() {
|
||||
}, [fields, count, format, generate]);
|
||||
|
||||
const selectedField = selectedIndex !== null && selectedIndex >= 0 ? fields[selectedIndex] : null;
|
||||
|
||||
const handleOpenEditor = useCallback((index: number) => {
|
||||
setSelectedIndex(index);
|
||||
setIsEditorOpen(true);
|
||||
@@ -137,8 +137,11 @@ export default function TestDataGeneratorPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground antialiased selection:bg-primary/20">
|
||||
<div className="max-w-7xl mx-auto p-4 sm:p-6">
|
||||
{/* 主要内容区域 - 左右分栏 */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-5 gap-4 items-start">
|
||||
{/* 左侧面板 - 字段配置 */}
|
||||
<div className="lg:col-span-3 space-y-4">
|
||||
{/* 标签页切换 */}
|
||||
<div className="flex gap-1 p-1 bg-muted rounded-lg">
|
||||
<button
|
||||
onClick={() => setActiveTab('fields')}
|
||||
@@ -207,7 +210,10 @@ export default function TestDataGeneratorPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右侧面板 - 数据预览和结果 */}
|
||||
<div className="lg:col-span-2 space-y-4">
|
||||
{/* 结果状态 */}
|
||||
{/* 仅在失败或有警告时显示结果面板 */}
|
||||
{((result && !result.success) ||
|
||||
(result?.warnings && result.warnings.length > 0) ||
|
||||
error) && (
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import * as ruleStorage from '../ruleStorage';
|
||||
|
||||
const STORAGE_KEY = 'testDataGenerator_rules';
|
||||
|
||||
const mockField = {
|
||||
id: 'field-1',
|
||||
name: 'username',
|
||||
generatorId: 'string',
|
||||
params: {},
|
||||
required: true,
|
||||
nullRate: 0,
|
||||
unique: false,
|
||||
};
|
||||
|
||||
describe('ruleStorage', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('save 在 localStorage 写入失败时应返回 null', () => {
|
||||
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
|
||||
throw new DOMException('QuotaExceededError');
|
||||
});
|
||||
|
||||
const result = ruleStorage.save({
|
||||
name: 'Test Rule',
|
||||
fields: [mockField],
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('update 在 localStorage 写入失败时应返回 null', () => {
|
||||
const saved = ruleStorage.save({
|
||||
name: 'Test Rule',
|
||||
fields: [mockField],
|
||||
});
|
||||
expect(saved).not.toBeNull();
|
||||
|
||||
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
|
||||
throw new DOMException('QuotaExceededError');
|
||||
});
|
||||
|
||||
const updated = ruleStorage.update(saved!.id, { name: 'Updated Rule' });
|
||||
expect(updated).toBeNull();
|
||||
});
|
||||
|
||||
it('deleteRule 在 localStorage 写入失败时应返回 false', () => {
|
||||
const saved = ruleStorage.save({
|
||||
name: 'Test Rule',
|
||||
fields: [mockField],
|
||||
});
|
||||
expect(saved).not.toBeNull();
|
||||
|
||||
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
|
||||
throw new DOMException('QuotaExceededError');
|
||||
});
|
||||
|
||||
expect(ruleStorage.deleteRule(saved!.id)).toBe(false);
|
||||
expect(ruleStorage.getById(saved!.id)).toBeDefined();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user