Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
test: add comprehensive unit and integration tests for RAG Pipeline components (#32237)
Coding On Starb65678bd4cd4
diff --git a/web/__tests__/rag-pipeline/chunk-preview-formatting.test.ts b/web/__tests__/rag-pipeline/chunk-preview-formatting.test.tsnew file mode 100644index 00000000000..c4cafbc1c5e--- /dev/null+++ b/web/__tests__/rag-pipeline/chunk-preview-formatting.test.ts@@ -0,0 +1,210 @@+/**+ * Integration test: Chunk preview formatting pipeline+ *+ * Tests the formatPreviewChunks utility across all chunking modes+ * (text, parentChild, QA) with real data structures.+ */+import { describe, expect, it, vi } from 'vitest'++vi.mock('@/config', () => ({+ RAG_PIPELINE_PREVIEW_CHUNK_NUM: 3,+}))++vi.mock('@/models/datasets', () => ({+ ChunkingMode: {+ text: 'text',+ parentChild: 'parent-child',+ qa: 'qa',+ },+}))++const { formatPreviewChunks } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/result/result-preview/utils',+)++describe('Chunk Preview Formatting', () => {+ describe('general text chunks', () => {+ it('should format text chunks correctly', () => {+ const outputs = {+ chunk_structure: 'text',+ preview: [+ { content: 'Chunk 1 content', summary: 'Summary 1' },+ { content: 'Chunk 2 content' },+ ],+ }++ const result = formatPreviewChunks(outputs)++ expect(Array.isArray(result)).toBe(true)+ const chunks = result as Array<{ content: string, summary?: string }>+ expect(chunks).toHaveLength(2)+ expect(chunks[0].content).toBe('Chunk 1 content')+ expect(chunks[0].summary).toBe('Summary 1')+ expect(chunks[1].content).toBe('Chunk 2 content')+ })++ it('should limit chunks to RAG_PIPELINE_PREVIEW_CHUNK_NUM', () => {+ const outputs = {+ chunk_structure: 'text',+ preview: Array.from({ length: 10 }, (_, i) => ({+ content: `Chunk ${i + 1}`,+ })),+ }++ const result = formatPreviewChunks(outputs)+ const chunks = result as Array<{ content: string }>++ expect(chunks).toHaveLength(3) // Mocked limit+ })+ })++ describe('parent-child chunks — paragraph mode', () => {+ it('should format paragraph parent-child chunks', () => {+ const outputs = {+ chunk_structure: 'parent-child',+ parent_mode: 'paragraph',+ preview: [+ {+ content: 'Parent paragraph',+ child_chunks: ['Child 1', 'Child 2'],+ summary: 'Parent summary',+ },+ ],+ }++ const result = formatPreviewChunks(outputs) as {+ parent_child_chunks: Array<{+ parent_content: string+ parent_summary?: string+ child_contents: string[]+ parent_mode: string+ }>+ parent_mode: string+ }++ expect(result.parent_mode).toBe('paragraph')+ expect(result.parent_child_chunks).toHaveLength(1)+ expect(result.parent_child_chunks[0].parent_content).toBe('Parent paragraph')+ expect(result.parent_child_chunks[0].parent_summary).toBe('Parent summary')+ expect(result.parent_child_chunks[0].child_contents).toEqual(['Child 1', 'Child 2'])+ })++ it('should limit parent chunks in paragraph mode', () => {+ const outputs = {+ chunk_structure: 'parent-child',+ parent_mode: 'paragraph',+ preview: Array.from({ length: 10 }, (_, i) => ({+ content: `Parent ${i + 1}`,+ child_chunks: [`Child of ${i + 1}`],+ })),+ }++ const result = formatPreviewChunks(outputs) as {+ parent_child_chunks: unknown[]+ }++ expect(result.parent_child_chunks).toHaveLength(3) // Mocked limit+ })+ })++ describe('parent-child chunks — full-doc mode', () => {+ it('should format full-doc parent-child chunks', () => {+ const outputs = {+ chunk_structure: 'parent-child',+ parent_mode: 'full-doc',+ preview: [+ {+ content: 'Full document content',+ child_chunks: ['Section 1', 'Section 2', 'Section 3'],+ },+ ],+ }++ const result = formatPreviewChunks(outputs) as {+ parent_child_chunks: Array<{+ parent_content: string+ child_contents: string[]+ parent_mode: string+ }>+ }++ expect(result.parent_child_chunks).toHaveLength(1)+ expect(result.parent_child_chunks[0].parent_content).toBe('Full document content')+ expect(result.parent_child_chunks[0].parent_mode).toBe('full-doc')+ })++ it('should limit child chunks in full-doc mode', () => {+ const outputs = {+ chunk_structure: 'parent-child',+ parent_mode: 'full-doc',+ preview: [+ {+ content: 'Document',+ child_chunks: Array.from({ length: 20 }, (_, i) => `Section ${i + 1}`),+ },+ ],+ }++ const result = formatPreviewChunks(outputs) as {+ parent_child_chunks: Array<{ child_contents: string[] }>+ }++ expect(result.parent_child_chunks[0].child_contents).toHaveLength(3) // Mocked limit+ })+ })++ describe('QA chunks', () => {+ it('should format QA chunks correctly', () => {+ const outputs = {+ chunk_structure: 'qa',+ qa_preview: [+ { question: 'What is AI?', answer: 'Artificial Intelligence is...' },+ { question: 'What is ML?', answer: 'Machine Learning is...' },+ ],+ }++ const result = formatPreviewChunks(outputs) as {+ qa_chunks: Array<{ question: string, answer: string }>+ }++ expect(result.qa_chunks).toHaveLength(2)+ expect(result.qa_chunks[0].question).toBe('What is AI?')+ expect(result.qa_chunks[0].answer).toBe('Artificial Intelligence is...')+ })++ it('should limit QA chunks', () => {+ const outputs = {+ chunk_structure: 'qa',+ qa_preview: Array.from({ length: 10 }, (_, i) => ({+ question: `Q${i + 1}`,+ answer: `A${i + 1}`,+ })),+ }++ const result = formatPreviewChunks(outputs) as {+ qa_chunks: unknown[]+ }++ expect(result.qa_chunks).toHaveLength(3) // Mocked limit+ })+ })++ describe('edge cases', () => {+ it('should return undefined for null outputs', () => {+ expect(formatPreviewChunks(null)).toBeUndefined()+ })++ it('should return undefined for undefined outputs', () => {+ expect(formatPreviewChunks(undefined)).toBeUndefined()+ })++ it('should return undefined for unknown chunk_structure', () => {+ const outputs = {+ chunk_structure: 'unknown-type',+ preview: [],+ }++ expect(formatPreviewChunks(outputs)).toBeUndefined()+ })+ })+})diff --git a/web/__tests__/rag-pipeline/dsl-export-import-flow.test.ts b/web/__tests__/rag-pipeline/dsl-export-import-flow.test.tsnew file mode 100644index 00000000000..578552840d9--- /dev/null+++ b/web/__tests__/rag-pipeline/dsl-export-import-flow.test.ts@@ -0,0 +1,179 @@+/**+ * Integration test: DSL export/import flow+ *+ * Validates DSL export logic (sync draft → check secrets → download)+ * and DSL import modal state management.+ */+import { act, renderHook } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'++const mockDoSyncWorkflowDraft = vi.fn().mockResolvedValue(undefined)+const mockExportPipelineConfig = vi.fn().mockResolvedValue({ data: 'yaml-content' })+const mockNotify = vi.fn()+const mockEventEmitter = { emit: vi.fn() }+const mockDownloadBlob = vi.fn()++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}))++vi.mock('@/app/components/base/toast', () => ({+ useToastContext: () => ({ notify: mockNotify }),+}))++vi.mock('@/app/components/workflow/constants', () => ({+ DSL_EXPORT_CHECK: 'DSL_EXPORT_CHECK',+}))++vi.mock('@/app/components/workflow/store', () => ({+ useWorkflowStore: () => ({+ getState: () => ({+ pipelineId: 'pipeline-abc',+ knowledgeName: 'My Pipeline',+ }),+ }),+}))++vi.mock('@/context/event-emitter', () => ({+ useEventEmitterContextContext: () => ({+ eventEmitter: mockEventEmitter,+ }),+}))++vi.mock('@/service/use-pipeline', () => ({+ useExportPipelineDSL: () => ({+ mutateAsync: mockExportPipelineConfig,+ }),+}))++vi.mock('@/service/workflow', () => ({+ fetchWorkflowDraft: vi.fn(),+}))++vi.mock('@/utils/download', () => ({+ downloadBlob: (...args: unknown[]) => mockDownloadBlob(...args),+}))++vi.mock('@/app/components/rag-pipeline/hooks/use-nodes-sync-draft', () => ({+ useNodesSyncDraft: () => ({+ doSyncWorkflowDraft: mockDoSyncWorkflowDraft,+ }),+}))++describe('DSL Export/Import Flow', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Export Flow', () => {+ it('should sync draft then export then download', async () => {+ const { useDSL } = await import('@/app/components/rag-pipeline/hooks/use-DSL')+ const { result } = renderHook(() => useDSL())++ await act(async () => {+ await result.current.handleExportDSL()+ })++ expect(mockDoSyncWorkflowDraft).toHaveBeenCalled()+ expect(mockExportPipelineConfig).toHaveBeenCalledWith({+ pipelineId: 'pipeline-abc',+ include: false,+ })+ expect(mockDownloadBlob).toHaveBeenCalledWith(expect.objectContaining({+ fileName: 'My Pipeline.pipeline',+ }))+ })++ it('should export with include flag when specified', async () => {+ const { useDSL } = await import('@/app/components/rag-pipeline/hooks/use-DSL')+ const { result } = renderHook(() => useDSL())++ await act(async () => {+ await result.current.handleExportDSL(true)+ })++ expect(mockExportPipelineConfig).toHaveBeenCalledWith({+ pipelineId: 'pipeline-abc',+ include: true,+ })+ })++ it('should notify on export error', async () => {+ mockDoSyncWorkflowDraft.mockRejectedValueOnce(new Error('sync failed'))+ const { useDSL } = await import('@/app/components/rag-pipeline/hooks/use-DSL')+ const { result } = renderHook(() => useDSL())++ await act(async () => {+ await result.current.handleExportDSL()+ })++ expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ type: 'error',+ }))+ })+ })++ describe('Export Check Flow', () => {+ it('should export directly when no secret environment variables', async () => {+ const { fetchWorkflowDraft } = await import('@/service/workflow')+ vi.mocked(fetchWorkflowDraft).mockResolvedValueOnce({+ environment_variables: [+ { value_type: 'string', key: 'API_URL', value: 'https://api.example.com' },+ ],+ } as unknown as Awaited<ReturnType<typeof fetchWorkflowDraft>>)++ const { useDSL } = await import('@/app/components/rag-pipeline/hooks/use-DSL')+ const { result } = renderHook(() => useDSL())++ await act(async () => {+ await result.current.exportCheck()+ })++ // Should proceed to export directly (no secret vars)+ expect(mockDoSyncWorkflowDraft).toHaveBeenCalled()+ })++ it('should emit DSL_EXPORT_CHECK event when secret variables exist', async () => {+ const { fetchWorkflowDraft } = await import('@/service/workflow')+ vi.mocked(fetchWorkflowDraft).mockResolvedValueOnce({+ environment_variables: [+ { value_type: 'secret', key: 'API_KEY', value: '***' },+ ],+ } as unknown as Awaited<ReturnType<typeof fetchWorkflowDraft>>)++ const { useDSL } = await import('@/app/components/rag-pipeline/hooks/use-DSL')+ const { result } = renderHook(() => useDSL())++ await act(async () => {+ await result.current.exportCheck()+ })++ expect(mockEventEmitter.emit).toHaveBeenCalledWith(expect.objectContaining({+ type: 'DSL_EXPORT_CHECK',+ payload: expect.objectContaining({+ data: expect.arrayContaining([+ expect.objectContaining({ value_type: 'secret' }),+ ]),+ }),+ }))+ })++ it('should notify on export check error', async () => {+ const { fetchWorkflowDraft } = await import('@/service/workflow')+ vi.mocked(fetchWorkflowDraft).mockRejectedValueOnce(new Error('fetch failed'))++ const { useDSL } = await import('@/app/components/rag-pipeline/hooks/use-DSL')+ const { result } = renderHook(() => useDSL())++ await act(async () => {+ await result.current.exportCheck()+ })++ expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({+ type: 'error',+ }))+ })+ })+})diff --git a/web/__tests__/rag-pipeline/input-field-crud-flow.test.ts b/web/__tests__/rag-pipeline/input-field-crud-flow.test.tsnew file mode 100644index 00000000000..233c9a288a1--- /dev/null+++ b/web/__tests__/rag-pipeline/input-field-crud-flow.test.ts@@ -0,0 +1,278 @@+/**+ * Integration test: Input field CRUD complete flow+ *+ * Validates the full lifecycle of input fields:+ * creation, editing, renaming, removal, and data conversion round-trip.+ */+import type { FormData } from '@/app/components/rag-pipeline/components/panel/input-field/editor/form/types'+import type { InputVar } from '@/models/pipeline'+import { describe, expect, it, vi } from 'vitest'+import { SupportUploadFileTypes } from '@/app/components/workflow/types'+import { PipelineInputVarType } from '@/models/pipeline'+import { TransferMethod } from '@/types/app'++vi.mock('@/config', () => ({+ VAR_ITEM_TEMPLATE_IN_PIPELINE: {+ type: 'text-input',+ label: '',+ variable: '',+ max_length: 48,+ default_value: undefined,+ required: true,+ tooltips: undefined,+ options: [],+ placeholder: undefined,+ unit: undefined,+ allowed_file_upload_methods: undefined,+ allowed_file_types: undefined,+ allowed_file_extensions: undefined,+ },+}))++describe('Input Field CRUD Flow', () => {+ describe('Create → Edit → Convert Round-trip', () => {+ it('should create a text field and roundtrip through form data', async () => {+ const { convertToInputFieldFormData, convertFormDataToINputField } = await import(+ '@/app/components/rag-pipeline/components/panel/input-field/editor/utils',+ )++ // Create new field from template (no data passed)+ const newFormData = convertToInputFieldFormData()+ expect(newFormData.type).toBe('text-input')+ expect(newFormData.variable).toBe('')+ expect(newFormData.label).toBe('')+ expect(newFormData.required).toBe(true)++ // Simulate user editing form data+ const editedFormData: FormData = {+ ...newFormData,+ variable: 'user_name',+ label: 'User Name',+ maxLength: 100,+ default: 'John',+ tooltips: 'Enter your name',+ placeholder: 'Type here...',+ allowedTypesAndExtensions: {},+ }++ // Convert back to InputVar+ const inputVar = convertFormDataToINputField(editedFormData)++ expect(inputVar.variable).toBe('user_name')+ expect(inputVar.label).toBe('User Name')+ expect(inputVar.max_length).toBe(100)+ expect(inputVar.default_value).toBe('John')+ expect(inputVar.tooltips).toBe('Enter your name')+ expect(inputVar.placeholder).toBe('Type here...')+ expect(inputVar.required).toBe(true)+ })++ it('should handle file field with upload settings', async () => {+ const { convertToInputFieldFormData, convertFormDataToINputField } = await import(+ '@/app/components/rag-pipeline/components/panel/input-field/editor/utils',+ )++ const fileInputVar: InputVar = {+ type: PipelineInputVarType.singleFile,+ label: 'Upload Document',+ variable: 'doc_file',+ max_length: 1,+ default_value: undefined,+ required: true,+ tooltips: 'Upload a PDF',+ options: [],+ placeholder: undefined,+ unit: undefined,+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],+ allowed_file_types: [SupportUploadFileTypes.document],+ allowed_file_extensions: ['.pdf', '.docx'],+ }++ // Convert to form data+ const formData = convertToInputFieldFormData(fileInputVar)+ expect(formData.allowedFileUploadMethods).toEqual([TransferMethod.local_file, TransferMethod.remote_url])+ expect(formData.allowedTypesAndExtensions).toEqual({+ allowedFileTypes: [SupportUploadFileTypes.document],+ allowedFileExtensions: ['.pdf', '.docx'],+ })++ // Round-trip back+ const restored = convertFormDataToINputField(formData)+ expect(restored.allowed_file_upload_methods).toEqual([TransferMethod.local_file, TransferMethod.remote_url])+ expect(restored.allowed_file_types).toEqual([SupportUploadFileTypes.document])+ expect(restored.allowed_file_extensions).toEqual(['.pdf', '.docx'])+ })++ it('should handle select field with options', async () => {+ const { convertToInputFieldFormData, convertFormDataToINputField } = await import(+ '@/app/components/rag-pipeline/components/panel/input-field/editor/utils',+ )++ const selectVar: InputVar = {+ type: PipelineInputVarType.select,+ label: 'Priority',+ variable: 'priority',+ max_length: 0,+ default_value: 'medium',+ required: false,+ tooltips: 'Select priority level',+ options: ['low', 'medium', 'high'],+ placeholder: 'Choose...',+ unit: undefined,+ allowed_file_upload_methods: undefined,+ allowed_file_types: undefined,+ allowed_file_extensions: undefined,+ }++ const formData = convertToInputFieldFormData(selectVar)+ expect(formData.options).toEqual(['low', 'medium', 'high'])+ expect(formData.default).toBe('medium')++ const restored = convertFormDataToINputField(formData)+ expect(restored.options).toEqual(['low', 'medium', 'high'])+ expect(restored.default_value).toBe('medium')+ })++ it('should handle number field with unit', async () => {+ const { convertToInputFieldFormData, convertFormDataToINputField } = await import(+ '@/app/components/rag-pipeline/components/panel/input-field/editor/utils',+ )++ const numberVar: InputVar = {+ type: PipelineInputVarType.number,+ label: 'Max Tokens',+ variable: 'max_tokens',+ max_length: 0,+ default_value: '1024',+ required: true,+ tooltips: undefined,+ options: [],+ placeholder: undefined,+ unit: 'tokens',+ allowed_file_upload_methods: undefined,+ allowed_file_types: undefined,+ allowed_file_extensions: undefined,+ }++ const formData = convertToInputFieldFormData(numberVar)+ expect(formData.unit).toBe('tokens')+ expect(formData.default).toBe('1024')++ const restored = convertFormDataToINputField(formData)+ expect(restored.unit).toBe('tokens')+ expect(restored.default_value).toBe('1024')+ })+ })++ describe('Omit optional fields', () => {+ it('should not include tooltips when undefined', async () => {+ const { convertToInputFieldFormData } = await import(+ '@/app/components/rag-pipeline/components/panel/input-field/editor/utils',+ )++ const inputVar: InputVar = {+ type: PipelineInputVarType.textInput,+ label: 'Test',+ variable: 'test',+ max_length: 48,+ default_value: undefined,+ required: true,+ tooltips: undefined,+ options: [],+ placeholder: undefined,+ unit: undefined,+ allowed_file_upload_methods: undefined,+ allowed_file_types: undefined,+ allowed_file_extensions: undefined,+ }++ const formData = convertToInputFieldFormData(inputVar)++ // Optional fields should not be present+ expect('tooltips' in formData).toBe(false)+ expect('placeholder' in formData).toBe(false)+ expect('unit' in formData).toBe(false)+ expect('default' in formData).toBe(false)+ })++ it('should include optional fields when explicitly set to empty string', async () => {+ const { convertToInputFieldFormData } = await import(+ '@/app/components/rag-pipeline/components/panel/input-field/editor/utils',+ )++ const inputVar: InputVar = {+ type: PipelineInputVarType.textInput,+ label: 'Test',+ variable: 'test',+ max_length: 48,+ default_value: '',+ required: true,+ tooltips: '',+ options: [],+ placeholder: '',+ unit: '',+ allowed_file_upload_methods: undefined,+ allowed_file_types: undefined,+ allowed_file_extensions: undefined,+ }++ const formData = convertToInputFieldFormData(inputVar)++ expect(formData.default).toBe('')+ expect(formData.tooltips).toBe('')+ expect(formData.placeholder).toBe('')+ expect(formData.unit).toBe('')+ })+ })++ describe('Multiple fields workflow', () => {+ it('should process multiple fields independently', async () => {+ const { convertToInputFieldFormData, convertFormDataToINputField } = await import(+ '@/app/components/rag-pipeline/components/panel/input-field/editor/utils',+ )++ const fields: InputVar[] = [+ {+ type: PipelineInputVarType.textInput,+ label: 'Name',+ variable: 'name',+ max_length: 48,+ default_value: 'Alice',+ required: true,+ tooltips: undefined,+ options: [],+ placeholder: undefined,+ unit: undefined,+ allowed_file_upload_methods: undefined,+ allowed_file_types: undefined,+ allowed_file_extensions: undefined,+ },+ {+ type: PipelineInputVarType.number,+ label: 'Count',+ variable: 'count',+ max_length: 0,+ default_value: '10',+ required: false,+ tooltips: undefined,+ options: [],+ placeholder: undefined,+ unit: 'items',+ allowed_file_upload_methods: undefined,+ allowed_file_types: undefined,+ allowed_file_extensions: undefined,+ },+ ]++ const formDataList = fields.map(f => convertToInputFieldFormData(f))+ const restoredFields = formDataList.map(fd => convertFormDataToINputField(fd))++ expect(restoredFields).toHaveLength(2)+ expect(restoredFields[0].variable).toBe('name')+ expect(restoredFields[0].default_value).toBe('Alice')+ expect(restoredFields[1].variable).toBe('count')+ expect(restoredFields[1].default_value).toBe('10')+ expect(restoredFields[1].unit).toBe('items')+ })+ })+})diff --git a/web/__tests__/rag-pipeline/input-field-editor-flow.test.ts b/web/__tests__/rag-pipeline/input-field-editor-flow.test.tsnew file mode 100644index 00000000000..0fc4699aa86--- /dev/null+++ b/web/__tests__/rag-pipeline/input-field-editor-flow.test.ts@@ -0,0 +1,199 @@+/**+ * Integration test: Input field editor data conversion flow+ *+ * Tests the full pipeline: InputVar -> FormData -> InputVar roundtrip+ * and schema validation for various input types.+ */+import type { InputVar } from '@/models/pipeline'+import { describe, expect, it, vi } from 'vitest'+import { PipelineInputVarType } from '@/models/pipeline'++// Mock the config module for VAR_ITEM_TEMPLATE_IN_PIPELINE+vi.mock('@/config', () => ({+ VAR_ITEM_TEMPLATE_IN_PIPELINE: {+ type: 'text-input',+ label: '',+ variable: '',+ max_length: 48,+ required: false,+ options: [],+ allowed_file_upload_methods: [],+ allowed_file_types: [],+ allowed_file_extensions: [],+ },+ MAX_VAR_KEY_LENGTH: 30,+ RAG_PIPELINE_PREVIEW_CHUNK_NUM: 10,+}))++// Import real functions (not mocked)+const { convertToInputFieldFormData, convertFormDataToINputField } = await import(+ '@/app/components/rag-pipeline/components/panel/input-field/editor/utils',+)++describe('Input Field Editor Data Flow', () => {+ describe('convertToInputFieldFormData', () => {+ it('should convert a text input InputVar to FormData', () => {+ const inputVar: InputVar = {+ type: 'text-input',+ label: 'Name',+ variable: 'user_name',+ max_length: 100,+ required: true,+ default_value: 'John',+ tooltips: 'Enter your name',+ placeholder: 'Type here...',+ options: [],+ } as InputVar++ const formData = convertToInputFieldFormData(inputVar)++ expect(formData.type).toBe('text-input')+ expect(formData.label).toBe('Name')+ expect(formData.variable).toBe('user_name')+ expect(formData.maxLength).toBe(100)+ expect(formData.required).toBe(true)+ expect(formData.default).toBe('John')+ expect(formData.tooltips).toBe('Enter your name')+ expect(formData.placeholder).toBe('Type here...')+ })++ it('should handle file input with upload settings', () => {+ const inputVar: InputVar = {+ type: 'file',+ label: 'Document',+ variable: 'doc',+ required: false,+ allowed_file_upload_methods: ['local_file', 'remote_url'],+ allowed_file_types: ['document', 'image'],+ allowed_file_extensions: ['.pdf', '.jpg'],+ options: [],+ } as InputVar++ const formData = convertToInputFieldFormData(inputVar)++ expect(formData.allowedFileUploadMethods).toEqual(['local_file', 'remote_url'])+ expect(formData.allowedTypesAndExtensions).toEqual({+ allowedFileTypes: ['document', 'image'],+ allowedFileExtensions: ['.pdf', '.jpg'],+ })+ })++ it('should use template defaults when no data provided', () => {+ const formData = convertToInputFieldFormData(undefined)++ expect(formData.type).toBe('text-input')+ expect(formData.maxLength).toBe(48)+ expect(formData.required).toBe(false)+ })++ it('should omit undefined/null optional fields', () => {+ const inputVar: InputVar = {+ type: 'text-input',+ label: 'Simple',+ variable: 'simple_var',+ max_length: 50,+ required: false,+ options: [],+ } as InputVar++ const formData = convertToInputFieldFormData(inputVar)++ expect(formData.default).toBeUndefined()+ expect(formData.tooltips).toBeUndefined()+ expect(formData.placeholder).toBeUndefined()+ expect(formData.unit).toBeUndefined()+ })+ })++ describe('convertFormDataToINputField', () => {+ it('should convert FormData back to InputVar', () => {+ const formData = {+ type: PipelineInputVarType.textInput,+ label: 'Name',+ variable: 'user_name',+ maxLength: 100,+ required: true,+ default: 'John',+ tooltips: 'Enter your name',+ options: [],+ placeholder: 'Type here...',+ allowedTypesAndExtensions: {+ allowedFileTypes: undefined,+ allowedFileExtensions: undefined,+ },+ }++ const inputVar = convertFormDataToINputField(formData)++ expect(inputVar.type).toBe('text-input')+ expect(inputVar.label).toBe('Name')+ expect(inputVar.variable).toBe('user_name')+ expect(inputVar.max_length).toBe(100)+ expect(inputVar.required).toBe(true)+ expect(inputVar.default_value).toBe('John')+ expect(inputVar.tooltips).toBe('Enter your name')+ })+ })++ describe('roundtrip conversion', () => {+ it('should preserve text input data through roundtrip', () => {+ const original: InputVar = {+ type: 'text-input',+ label: 'Question',+ variable: 'question',+ max_length: 200,+ required: true,+ default_value: 'What is AI?',+ tooltips: 'Enter your question',+ placeholder: 'Ask something...',+ options: [],+ } as InputVar++ const formData = convertToInputFieldFormData(original)+ const restored = convertFormDataToINputField(formData)++ expect(restored.type).toBe(original.type)+ expect(restored.label).toBe(original.label)+ expect(restored.variable).toBe(original.variable)+ expect(restored.max_length).toBe(original.max_length)+ expect(restored.required).toBe(original.required)+ expect(restored.default_value).toBe(original.default_value)+ expect(restored.tooltips).toBe(original.tooltips)+ expect(restored.placeholder).toBe(original.placeholder)+ })++ it('should preserve number input data through roundtrip', () => {+ const original = {+ type: 'number',+ label: 'Temperature',+ variable: 'temp',+ required: false,+ default_value: '0.7',+ unit: '°C',+ options: [],+ } as InputVar++ const formData = convertToInputFieldFormData(original)+ const restored = convertFormDataToINputField(formData)++ expect(restored.type).toBe('number')+ expect(restored.unit).toBe('°C')+ expect(restored.default_value).toBe('0.7')+ })++ it('should preserve select options through roundtrip', () => {+ const original: InputVar = {+ type: 'select',+ label: 'Mode',+ variable: 'mode',+ required: true,+ options: ['fast', 'balanced', 'quality'],+ } as InputVar++ const formData = convertToInputFieldFormData(original)+ const restored = convertFormDataToINputField(formData)++ expect(restored.options).toEqual(['fast', 'balanced', 'quality'])+ })+ })+})diff --git a/web/__tests__/rag-pipeline/test-run-flow.test.ts b/web/__tests__/rag-pipeline/test-run-flow.test.tsnew file mode 100644index 00000000000..a2bf557acd0--- /dev/null+++ b/web/__tests__/rag-pipeline/test-run-flow.test.ts@@ -0,0 +1,277 @@+/**+ * Integration test: Test run end-to-end flow+ *+ * Validates the data flow through test-run preparation hooks:+ * step navigation, datasource filtering, and data clearing.+ */+import { act, renderHook } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { BlockEnum } from '@/app/components/workflow/types'++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}))++// Mutable holder so mock data can reference BlockEnum after imports+const mockNodesHolder = vi.hoisted(() => ({ value: [] as Record<string, unknown>[] }))++vi.mock('reactflow', () => ({+ useNodes: () => mockNodesHolder.value,+}))++mockNodesHolder.value = [+ {+ id: 'ds-1',+ data: {+ type: BlockEnum.DataSource,+ title: 'Local Files',+ datasource_type: 'upload_file',+ datasource_configurations: { datasource_label: 'Upload', upload_file_config: {} },+ },+ },+ {+ id: 'ds-2',+ data: {+ type: BlockEnum.DataSource,+ title: 'Web Crawl',+ datasource_type: 'website_crawl',+ datasource_configurations: { datasource_label: 'Crawl' },+ },+ },+ {+ id: 'kb-1',+ data: {+ type: BlockEnum.KnowledgeBase,+ title: 'Knowledge Base',+ },+ },+]++// Mock the Zustand store used by the hooks+const mockSetDocumentsData = vi.fn()+const mockSetSearchValue = vi.fn()+const mockSetSelectedPagesId = vi.fn()+const mockSetOnlineDocuments = vi.fn()+const mockSetCurrentDocument = vi.fn()+const mockSetStep = vi.fn()+const mockSetCrawlResult = vi.fn()+const mockSetWebsitePages = vi.fn()+const mockSetPreviewIndex = vi.fn()+const mockSetCurrentWebsite = vi.fn()+const mockSetOnlineDriveFileList = vi.fn()+const mockSetBucket = vi.fn()+const mockSetPrefix = vi.fn()+const mockSetKeywords = vi.fn()+const mockSetSelectedFileIds = vi.fn()++vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/store', () => ({+ useDataSourceStore: () => ({+ getState: () => ({+ setDocumentsData: mockSetDocumentsData,+ setSearchValue: mockSetSearchValue,+ setSelectedPagesId: mockSetSelectedPagesId,+ setOnlineDocuments: mockSetOnlineDocuments,+ setCurrentDocument: mockSetCurrentDocument,+ setStep: mockSetStep,+ setCrawlResult: mockSetCrawlResult,+ setWebsitePages: mockSetWebsitePages,+ setPreviewIndex: mockSetPreviewIndex,+ setCurrentWebsite: mockSetCurrentWebsite,+ setOnlineDriveFileList: mockSetOnlineDriveFileList,+ setBucket: mockSetBucket,+ setPrefix: mockSetPrefix,+ setKeywords: mockSetKeywords,+ setSelectedFileIds: mockSetSelectedFileIds,+ }),+ }),+}))++vi.mock('@/models/datasets', () => ({+ CrawlStep: {+ init: 'init',+ },+}))++describe('Test Run Flow Integration', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Step Navigation', () => {+ it('should start at step 1 and navigate forward', async () => {+ const { useTestRunSteps } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useTestRunSteps())++ expect(result.current.currentStep).toBe(1)++ act(() => {+ result.current.handleNextStep()+ })++ expect(result.current.currentStep).toBe(2)+ })++ it('should navigate back from step 2 to step 1', async () => {+ const { useTestRunSteps } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useTestRunSteps())++ act(() => {+ result.current.handleNextStep()+ })+ expect(result.current.currentStep).toBe(2)++ act(() => {+ result.current.handleBackStep()+ })+ expect(result.current.currentStep).toBe(1)+ })++ it('should provide labeled steps', async () => {+ const { useTestRunSteps } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useTestRunSteps())++ expect(result.current.steps).toHaveLength(2)+ expect(result.current.steps[0].value).toBe('dataSource')+ expect(result.current.steps[1].value).toBe('documentProcessing')+ })+ })++ describe('Datasource Options', () => {+ it('should filter nodes to only DataSource type', async () => {+ const { useDatasourceOptions } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useDatasourceOptions())++ // Should only include DataSource nodes, not KnowledgeBase+ expect(result.current).toHaveLength(2)+ expect(result.current[0].value).toBe('ds-1')+ expect(result.current[1].value).toBe('ds-2')+ })++ it('should include node data in options', async () => {+ const { useDatasourceOptions } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useDatasourceOptions())++ expect(result.current[0].label).toBe('Local Files')+ expect(result.current[0].data.type).toBe(BlockEnum.DataSource)+ })+ })++ describe('Data Clearing Flow', () => {+ it('should clear online document data', async () => {+ const { useOnlineDocument } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useOnlineDocument())++ act(() => {+ result.current.clearOnlineDocumentData()+ })++ expect(mockSetDocumentsData).toHaveBeenCalledWith([])+ expect(mockSetSearchValue).toHaveBeenCalledWith('')+ expect(mockSetSelectedPagesId).toHaveBeenCalledWith(expect.any(Set))+ expect(mockSetOnlineDocuments).toHaveBeenCalledWith([])+ expect(mockSetCurrentDocument).toHaveBeenCalledWith(undefined)+ })++ it('should clear website crawl data', async () => {+ const { useWebsiteCrawl } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useWebsiteCrawl())++ act(() => {+ result.current.clearWebsiteCrawlData()+ })++ expect(mockSetStep).toHaveBeenCalledWith('init')+ expect(mockSetCrawlResult).toHaveBeenCalledWith(undefined)+ expect(mockSetCurrentWebsite).toHaveBeenCalledWith(undefined)+ expect(mockSetWebsitePages).toHaveBeenCalledWith([])+ expect(mockSetPreviewIndex).toHaveBeenCalledWith(-1)+ })++ it('should clear online drive data', async () => {+ const { useOnlineDrive } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useOnlineDrive())++ act(() => {+ result.current.clearOnlineDriveData()+ })++ expect(mockSetOnlineDriveFileList).toHaveBeenCalledWith([])+ expect(mockSetBucket).toHaveBeenCalledWith('')+ expect(mockSetPrefix).toHaveBeenCalledWith([])+ expect(mockSetKeywords).toHaveBeenCalledWith('')+ expect(mockSetSelectedFileIds).toHaveBeenCalledWith([])+ })+ })++ describe('Full Flow Simulation', () => {+ it('should support complete step navigation cycle', async () => {+ const { useTestRunSteps } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result } = renderHook(() => useTestRunSteps())++ // Start at step 1+ expect(result.current.currentStep).toBe(1)++ // Move to step 2+ act(() => {+ result.current.handleNextStep()+ })+ expect(result.current.currentStep).toBe(2)++ // Go back to step 1+ act(() => {+ result.current.handleBackStep()+ })+ expect(result.current.currentStep).toBe(1)++ // Move forward again+ act(() => {+ result.current.handleNextStep()+ })+ expect(result.current.currentStep).toBe(2)+ })++ it('should not regress when clearing all data sources in sequence', async () => {+ const {+ useOnlineDocument,+ useWebsiteCrawl,+ useOnlineDrive,+ } = await import(+ '@/app/components/rag-pipeline/components/panel/test-run/preparation/hooks',+ )+ const { result: docResult } = renderHook(() => useOnlineDocument())+ const { result: crawlResult } = renderHook(() => useWebsiteCrawl())+ const { result: driveResult } = renderHook(() => useOnlineDrive())++ // Clear all data sources+ act(() => {+ docResult.current.clearOnlineDocumentData()+ crawlResult.current.clearWebsiteCrawlData()+ driveResult.current.clearOnlineDriveData()+ })++ expect(mockSetDocumentsData).toHaveBeenCalledWith([])+ expect(mockSetStep).toHaveBeenCalledWith('init')+ expect(mockSetOnlineDriveFileList).toHaveBeenCalledWith([])+ })+ })+})diff --git a/web/app/components/rag-pipeline/index.spec.tsx b/web/app/components/rag-pipeline/__tests__/index.spec.tsxsimilarity index 86%rename from web/app/components/rag-pipeline/index.spec.tsxrename to web/app/components/rag-pipeline/__tests__/index.spec.tsxindex 5adfc828cf9..221713defe6 100644--- a/web/app/components/rag-pipeline/index.spec.tsx+++ b/web/app/components/rag-pipeline/__tests__/index.spec.tsx@@ -3,45 +3,36 @@ import { cleanup, render, screen } from '@testing-library/react'import * as React from 'react'import { BlockEnum } from '@/app/components/workflow/types'-// Import real utility functions (pure functions, no side effects)--// Import mocked modules for manipulationimport { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'-import { usePipelineInit } from './hooks'-import RagPipelineWrapper from './index'-import { processNodesWithoutDataSource } from './utils'+import { usePipelineInit } from '../hooks'+import RagPipelineWrapper from '../index'+import { processNodesWithoutDataSource } from '../utils'-// Mock: Context - need to control return valuesvi.mock('@/context/dataset-detail', () => ({useDatasetDetailContextWithSelector: vi.fn(),}))-// Mock: Hook with API calls-vi.mock('./hooks', () => ({+vi.mock('../hooks', () => ({usePipelineInit: vi.fn(),}))-// Mock: Store creator-vi.mock('./store', () => ({+vi.mock('../store', () => ({createRagPipelineSliceSlice: vi.fn(() => ({})),}))-// Mock: Utility with complex workflow dependencies (generateNewNode, etc.)-vi.mock('./utils', () => ({+vi.mock('../utils', () => ({processNodesWithoutDataSource: vi.fn((nodes, viewport) => ({nodes,viewport,})),}))-// Mock: Complex component with useParams, Toast, API calls-vi.mock('./components/conversion', () => ({+vi.mock('../components/conversion', () => ({default: () => <div data-testid="conversion-component">Conversion Component</div>,}))-// Mock: Complex component with many hooks and workflow dependencies-vi.mock('./components/rag-pipeline-main', () => ({- default: ({ nodes, edges, viewport }: any) => (+vi.mock('../components/rag-pipeline-main', () => ({+ default: ({ nodes, edges, viewport }: { nodes?: unknown[], edges?: unknown[], viewport?: { zoom?: number } }) => (<div data-testid="rag-pipeline-main"><span data-testid="nodes-count">{nodes?.length ?? 0}</span><span data-testid="edges-count">{edges?.length ?? 0}</span>@@ -50,35 +41,29 @@ vi.mock('./components/rag-pipeline-main', () => ({),}))-// Mock: Complex component with ReactFlow and many providersvi.mock('@/app/components/workflow', () => ({default: ({ children }: { children: React.ReactNode }) => (<div data-testid="workflow-default-context">{children}</div>),}))-// Mock: Context providervi.mock('@/app/components/workflow/context', () => ({WorkflowContextProvider: ({ children }: { children: React.ReactNode }) => (<div data-testid="workflow-context-provider">{children}</div>),}))-// Type assertions for mocked functionsconst mockUseDatasetDetailContextWithSelector = vi.mocked(useDatasetDetailContextWithSelector)const mockUsePipelineInit = vi.mocked(usePipelineInit)const mockProcessNodesWithoutDataSource = vi.mocked(processNodesWithoutDataSource)-// Helper to mock selector with actual execution (increases function coverage)-// This executes the real selector function: s => s.dataset?.pipeline_idconst mockSelectorWithDataset = (pipelineId: string | null | undefined) => {- mockUseDatasetDetailContextWithSelector.mockImplementation((selector: (state: any) => any) => {+ mockUseDatasetDetailContextWithSelector.mockImplementation((selector: (state: Record<string, unknown>) => unknown) => {const mockState = { dataset: pipelineId ? { pipeline_id: pipelineId } : null }return selector(mockState)})}-// Test data factoryconst createMockWorkflowData = (overrides?: Partial<FetchWorkflowDraftResponse>): FetchWorkflowDraftResponse => ({graph: {nodes: [@@ -157,7 +142,6 @@ describe('RagPipelineWrapper', () => {describe('RagPipeline', () => {beforeEach(() => {- // Default setup for RagPipeline tests - execute real selector functionmockSelectorWithDataset('pipeline-123')})@@ -167,7 +151,6 @@ describe('RagPipeline', () => {render(<RagPipelineWrapper />)- // Real Loading component has role="status"expect(screen.getByRole('status')).toBeInTheDocument()})@@ -240,8 +223,6 @@ describe('RagPipeline', () => {render(<RagPipelineWrapper />)- // initialNodes is a real function - verify nodes are rendered- // The real initialNodes processes nodes and adds position dataexpect(screen.getByTestId('rag-pipeline-main')).toBeInTheDocument()})@@ -251,7 +232,6 @@ describe('RagPipeline', () => {render(<RagPipelineWrapper />)- // initialEdges is a real function - verify component renders with edgesexpect(screen.getByTestId('edges-count').textContent).toBe('1')})@@ -269,7 +249,6 @@ describe('RagPipeline', () => {render(<RagPipelineWrapper />)- // When data is undefined, Loading is shown, processNodesWithoutDataSource is not calledexpect(mockProcessNodesWithoutDataSource).not.toHaveBeenCalled()})@@ -279,13 +258,10 @@ describe('RagPipeline', () => {const { rerender } = render(<RagPipelineWrapper />)- // Clear mock call count after initial rendermockProcessNodesWithoutDataSource.mockClear()- // Rerender with same data reference (no change to mockUsePipelineInit)rerender(<RagPipelineWrapper />)- // processNodesWithoutDataSource should not be called again due to useMemo// Note: React strict mode may cause double render, so we check it's not excessiveexpect(mockProcessNodesWithoutDataSource.mock.calls.length).toBeLessThanOrEqual(1)})@@ -327,7 +303,7 @@ describe('RagPipeline', () => {graph: {nodes: [],edges: [],- viewport: undefined as any,+ viewport: undefined as never,},})mockUsePipelineInit.mockReturnValue({ data: mockData, isLoading: false })@@ -342,7 +318,7 @@ describe('RagPipeline', () => {graph: {nodes: [],edges: [],- viewport: null as any,+ viewport: null as never,},})mockUsePipelineInit.mockReturnValue({ data: mockData, isLoading: false })@@ -438,7 +414,7 @@ describe('processNodesWithoutDataSource utility integration', () => {const mockData = createMockWorkflowData()mockUsePipelineInit.mockReturnValue({ data: mockData, isLoading: false })mockProcessNodesWithoutDataSource.mockReturnValue({- nodes: [{ id: 'processed-node', type: 'custom', data: { type: BlockEnum.Start, title: 'Processed', desc: '' }, position: { x: 0, y: 0 } }] as any,+ nodes: [{ id: 'processed-node', type: 'custom', data: { type: BlockEnum.Start, title: 'Processed', desc: '' }, position: { x: 0, y: 0 } }] as unknown as ReturnType<typeof processNodesWithoutDataSource>['nodes'],viewport: { x: 0, y: 0, zoom: 2 },})@@ -467,14 +443,11 @@ describe('Conditional Rendering Flow', () => {it('should transition from loading to loaded state', () => {mockSelectorWithDataset('pipeline-123')- // Start with loading statemockUsePipelineInit.mockReturnValue({ data: undefined, isLoading: true })const { rerender } = render(<RagPipelineWrapper />)- // Real Loading component has role="status"expect(screen.getByRole('status')).toBeInTheDocument()- // Transition to loaded stateconst mockData = createMockWorkflowData()mockUsePipelineInit.mockReturnValue({ data: mockData, isLoading: false })rerender(<RagPipelineWrapper />)@@ -483,7 +456,6 @@ describe('Conditional Rendering Flow', () => {})it('should switch from Conversion to Pipeline when pipelineId becomes available', () => {- // Start without pipelineIdmockSelectorWithDataset(null)mockUsePipelineInit.mockReturnValue({ data: undefined, isLoading: false })@@ -491,13 +463,11 @@ describe('Conditional Rendering Flow', () => {expect(screen.getByTestId('conversion-component')).toBeInTheDocument()- // PipelineId becomes availablemockSelectorWithDataset('new-pipeline-id')mockUsePipelineInit.mockReturnValue({ data: undefined, isLoading: true })rerender(<RagPipelineWrapper />)expect(screen.queryByTestId('conversion-component')).not.toBeInTheDocument()- // Real Loading component has role="status"expect(screen.getByRole('status')).toBeInTheDocument()})})@@ -510,21 +480,18 @@ describe('Error Handling', () => {it('should throw when graph nodes is null', () => {const mockData = {graph: {- nodes: null as any,- edges: null as any,+ nodes: null,+ edges: null,viewport: { x: 0, y: 0, zoom: 1 },},hash: 'test',updated_at: 123,- } as FetchWorkflowDraftResponse+ } as unknown as FetchWorkflowDraftResponsemockUsePipelineInit.mockReturnValue({ data: mockData, isLoading: false })- // Suppress console.error for expected errorconst consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})- // Real initialNodes will throw when nodes is null- // This documents the component's current behavior - it requires valid nodes arrayexpect(() => render(<RagPipelineWrapper />)).toThrow()consoleSpy.mockRestore()@@ -538,11 +505,8 @@ describe('Error Handling', () => {mockUsePipelineInit.mockReturnValue({ data: mockData, isLoading: false })- // Suppress console.error for expected errorconst consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})- // When graph is undefined, component throws because data.graph.nodes is accessed- // This documents the component's current behavior - it requires graph to be presentexpect(() => render(<RagPipelineWrapper />)).toThrow()consoleSpy.mockRestore()diff --git a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsxnew file mode 100644index 00000000000..2bd20fb5c37--- /dev/null+++ b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx@@ -0,0 +1,182 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import Conversion from '../conversion'++const mockConvert = vi.fn()+const mockInvalidDatasetDetail = vi.fn()+vi.mock('next/navigation', () => ({+ useParams: () => ({ datasetId: 'ds-123' }),+}))++vi.mock('@/service/use-pipeline', () => ({+ useConvertDatasetToPipeline: () => ({+ mutateAsync: mockConvert,+ isPending: false,+ }),+}))++vi.mock('@/service/knowledge/use-dataset', () => ({+ datasetDetailQueryKeyPrefix: ['dataset-detail'],+}))++vi.mock('@/service/use-base', () => ({+ useInvalid: () => mockInvalidDatasetDetail,+}))++vi.mock('@/app/components/base/toast', () => ({+ default: {+ notify: vi.fn(),+ },+}))++vi.mock('@/app/components/base/button', () => ({+ default: ({ children, onClick, ...props }: Record<string, unknown>) => (+ <button onClick={onClick as () => void} {...props}>{children as string}</button>+ ),+}))++vi.mock('@/app/components/base/confirm', () => ({+ default: ({+ isShow,+ onConfirm,+ onCancel,+ title,+ }: {+ isShow: boolean+ onConfirm: () => void+ onCancel: () => void+ title: string+ }) =>+ isShow+ ? (+ <div data-testid="confirm-modal">+ <span>{title}</span>+ <button data-testid="confirm-btn" onClick={onConfirm}>Confirm</button>+ <button data-testid="cancel-btn" onClick={onCancel}>Cancel</button>+ </div>+ )+ : null,+}))++vi.mock('../screenshot', () => ({+ default: () => <div data-testid="screenshot" />,+}))++describe('Conversion', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('should render conversion title and description', () => {+ render(<Conversion />)++ expect(screen.getByText('datasetPipeline.conversion.title')).toBeInTheDocument()+ expect(screen.getByText('datasetPipeline.conversion.descriptionChunk1')).toBeInTheDocument()+ expect(screen.getByText('datasetPipeline.conversion.descriptionChunk2')).toBeInTheDocument()+ })++ it('should render convert button', () => {+ render(<Conversion />)++ expect(screen.getByText('datasetPipeline.operations.convert')).toBeInTheDocument()+ })++ it('should render warning text', () => {+ render(<Conversion />)++ expect(screen.getByText('datasetPipeline.conversion.warning')).toBeInTheDocument()+ })++ it('should render screenshot component', () => {+ render(<Conversion />)++ expect(screen.getByTestId('screenshot')).toBeInTheDocument()+ })++ it('should show confirm modal when convert button clicked', () => {+ render(<Conversion />)++ expect(screen.queryByTestId('confirm-modal')).not.toBeInTheDocument()++ fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))++ expect(screen.getByTestId('confirm-modal')).toBeInTheDocument()+ expect(screen.getByText('datasetPipeline.conversion.confirm.title')).toBeInTheDocument()+ })++ it('should hide confirm modal when cancel is clicked', () => {+ render(<Conversion />)++ fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))+ expect(screen.getByTestId('confirm-modal')).toBeInTheDocument()++ fireEvent.click(screen.getByTestId('cancel-btn'))+ expect(screen.queryByTestId('confirm-modal')).not.toBeInTheDocument()+ })++ it('should call convert when confirm is clicked', () => {+ render(<Conversion />)++ fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))+ fireEvent.click(screen.getByTestId('confirm-btn'))++ expect(mockConvert).toHaveBeenCalledWith('ds-123', expect.objectContaining({+ onSuccess: expect.any(Function),+ onError: expect.any(Function),+ }))+ })++ it('should handle successful conversion', async () => {+ const Toast = await import('@/app/components/base/toast')+ mockConvert.mockImplementation((_id: string, opts: { onSuccess: (res: { status: string }) => void }) => {+ opts.onSuccess({ status: 'success' })+ })++ render(<Conversion />)++ fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))+ fireEvent.click(screen.getByTestId('confirm-btn'))++ expect(Toast.default.notify).toHaveBeenCalledWith(expect.objectContaining({+ type: 'success',+ }))+ expect(mockInvalidDatasetDetail).toHaveBeenCalled()+ })++ it('should handle failed conversion', async () => {+ const Toast = await import('@/app/components/base/toast')+ mockConvert.mockImplementation((_id: string, opts: { onSuccess: (res: { status: string }) => void }) => {+ opts.onSuccess({ status: 'failed' })+ })++ render(<Conversion />)++ fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))+ fireEvent.click(screen.getByTestId('confirm-btn'))++ expect(Toast.default.notify).toHaveBeenCalledWith(expect.objectContaining({+ type: 'error',+ }))+ })++ it('should handle conversion error', async () => {+ const Toast = await import('@/app/components/base/toast')+ mockConvert.mockImplementation((_id: string, opts: { onError: () => void }) => {+ opts.onError()+ })++ render(<Conversion />)++ fireEvent.click(screen.getByText('datasetPipeline.operations.convert'))+ fireEvent.click(screen.getByTestId('confirm-btn'))++ expect(Toast.default.notify).toHaveBeenCalledWith(expect.objectContaining({+ type: 'error',+ }))+ })+})diff --git a/web/app/components/rag-pipeline/components/index.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/index.spec.tsxsimilarity index 82%rename from web/app/components/rag-pipeline/components/index.spec.tsxrename to web/app/components/rag-pipeline/components/__tests__/index.spec.tsxindex e17f07303d9..5c3781e8c14 100644--- a/web/app/components/rag-pipeline/components/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/index.spec.tsx@@ -3,29 +3,19 @@ import type { EnvironmentVariable } from '@/app/components/workflow/types'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { createMockProviderContextValue } from '@/__mocks__/provider-context'-// ============================================================================-// Import Components After Mocks Setup-// ============================================================================--import Conversion from './conversion'-import RagPipelinePanel from './panel'-import PublishAsKnowledgePipelineModal from './publish-as-knowledge-pipeline-modal'-import PublishToast from './publish-toast'-import RagPipelineChildren from './rag-pipeline-children'-import PipelineScreenShot from './screenshot'--// ============================================================================-// Mock External Dependencies - All vi.mock calls must come before any imports-// ============================================================================--// Mock next/navigation+import Conversion from '../conversion'+import RagPipelinePanel from '../panel'+import PublishAsKnowledgePipelineModal from '../publish-as-knowledge-pipeline-modal'+import PublishToast from '../publish-toast'+import RagPipelineChildren from '../rag-pipeline-children'+import PipelineScreenShot from '../screenshot'+const mockPush = vi.fn()vi.mock('next/navigation', () => ({useParams: () => ({ datasetId: 'test-dataset-id' }),useRouter: () => ({ push: mockPush }),}))-// Mock next/imagevi.mock('next/image', () => ({default: ({ src, alt, width, height }: { src: string, alt: string, width: number, height: number }) => (// eslint-disable-next-line next/no-img-element@@ -33,7 +23,6 @@ vi.mock('next/image', () => ({),}))-// Mock next/dynamicvi.mock('next/dynamic', () => ({default: (importFn: () => Promise<{ default: React.ComponentType<unknown> }>, options?: { ssr?: boolean }) => {const DynamicComponent = ({ children, ...props }: PropsWithChildren) => {@@ -44,7 +33,6 @@ vi.mock('next/dynamic', () => ({},}))-// Mock workflow store - using controllable statelet mockShowImportDSLModal = falseconst mockSetShowImportDSLModal = vi.fn((value: boolean) => {mockShowImportDSLModal = value@@ -112,7 +100,6 @@ vi.mock('@/app/components/workflow/store', () => {}})-// Mock workflow hooks - extract mock functions for assertions using vi.hoistedconst {mockHandlePaneContextmenuCancel,mockExportCheck,@@ -148,8 +135,7 @@ vi.mock('@/app/components/workflow/hooks', () => {}})-// Mock rag-pipeline hooks-vi.mock('../hooks', () => ({+vi.mock('../../hooks', () => ({useAvailableNodesMetaData: () => ({}),useDSL: () => ({exportCheck: mockExportCheck,@@ -178,18 +164,15 @@ vi.mock('../hooks', () => ({}),}))-// Mock rag-pipeline search hook-vi.mock('../hooks/use-rag-pipeline-search', () => ({+vi.mock('../../hooks/use-rag-pipeline-search', () => ({useRagPipelineSearch: vi.fn(),}))-// Mock configs-map hook-vi.mock('../hooks/use-configs-map', () => ({+vi.mock('../../hooks/use-configs-map', () => ({useConfigsMap: () => ({}),}))-// Mock inspect-vars-crud hook-vi.mock('../hooks/use-inspect-vars-crud', () => ({+vi.mock('../../hooks/use-inspect-vars-crud', () => ({useInspectVarsCrud: () => ({hasNodeInspectVars: vi.fn(),hasSetInspectVar: vi.fn(),@@ -208,14 +191,12 @@ vi.mock('../hooks/use-inspect-vars-crud', () => ({}),}))-// Mock workflow hooks for fetch-workflow-inspect-varsvi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({useSetWorkflowVarsWithValue: () => ({fetchInspectVars: vi.fn(),}),}))-// Mock service hooks - with controllable convert functionlet mockConvertFn = vi.fn()let mockIsPending = falsevi.mock('@/service/use-pipeline', () => ({@@ -253,7 +234,6 @@ vi.mock('@/service/workflow', () => ({}),}))-// Mock event emitter context - with controllable subscriptionlet mockEventSubscriptionCallback: ((v: { type: string, payload?: { data?: EnvironmentVariable[] } }) => void) | null = nullconst mockUseSubscription = vi.fn((callback: (v: { type: string, payload?: { data?: EnvironmentVariable[] } }) => void) => {mockEventSubscriptionCallback = callback@@ -267,7 +247,6 @@ vi.mock('@/context/event-emitter', () => ({}),}))-// Mock toastvi.mock('@/app/components/base/toast', () => ({default: {notify: vi.fn(),@@ -280,33 +259,28 @@ vi.mock('@/app/components/base/toast', () => ({},}))-// Mock useTheme hookvi.mock('@/hooks/use-theme', () => ({default: () => ({theme: 'light',}),}))-// Mock basePathvi.mock('@/utils/var', () => ({basePath: '/public',}))-// Mock provider contextvi.mock('@/context/provider-context', () => ({useProviderContext: () => createMockProviderContextValue(),useProviderContextSelector: <T,>(selector: (state: ReturnType<typeof createMockProviderContextValue>) => T): T =>selector(createMockProviderContextValue()),}))-// Mock WorkflowWithInnerContextvi.mock('@/app/components/workflow', () => ({WorkflowWithInnerContext: ({ children }: PropsWithChildren) => (<div data-testid="workflow-inner-context">{children}</div>),}))-// Mock workflow panelvi.mock('@/app/components/workflow/panel', () => ({default: ({ components }: { components?: { left?: React.ReactNode, right?: React.ReactNode } }) => (<div data-testid="workflow-panel">@@ -316,19 +290,16 @@ vi.mock('@/app/components/workflow/panel', () => ({),}))-// Mock PluginDependency-vi.mock('../../workflow/plugin-dependency', () => ({+vi.mock('../../../workflow/plugin-dependency', () => ({default: () => <div data-testid="plugin-dependency" />,}))-// Mock plugin-dependency hooksvi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({usePluginDependencies: () => ({handleCheckPluginDependencies: vi.fn().mockResolvedValue(undefined),}),}))-// Mock DSLExportConfirmModalvi.mock('@/app/components/workflow/dsl-export-confirm-modal', () => ({default: ({ envList, onConfirm, onClose }: { envList: EnvironmentVariable[], onConfirm: () => void, onClose: () => void }) => (<div data-testid="dsl-export-confirm-modal">@@ -339,13 +310,11 @@ vi.mock('@/app/components/workflow/dsl-export-confirm-modal', () => ({),}))-// Mock workflow constantsvi.mock('@/app/components/workflow/constants', () => ({DSL_EXPORT_CHECK: 'DSL_EXPORT_CHECK',WORKFLOW_DATA_UPDATE: 'WORKFLOW_DATA_UPDATE',}))-// Mock workflow utilsvi.mock('@/app/components/workflow/utils', () => ({initialNodes: vi.fn(nodes => nodes),initialEdges: vi.fn(edges => edges),@@ -353,7 +322,6 @@ vi.mock('@/app/components/workflow/utils', () => ({getKeyboardKeyNameBySystem: (key: string) => key,}))-// Mock Confirm componentvi.mock('@/app/components/base/confirm', () => ({default: ({ title, content, isShow, onConfirm, onCancel, isLoading, isDisabled }: {title: string@@ -381,7 +349,6 @@ vi.mock('@/app/components/base/confirm', () => ({: null,}))-// Mock Modal componentvi.mock('@/app/components/base/modal', () => ({default: ({ children, isShow, onClose, className }: PropsWithChildren<{isShow: boolean@@ -396,7 +363,6 @@ vi.mock('@/app/components/base/modal', () => ({: null,}))-// Mock Input componentvi.mock('@/app/components/base/input', () => ({default: ({ value, onChange, placeholder }: {value: string@@ -412,7 +378,6 @@ vi.mock('@/app/components/base/input', () => ({),}))-// Mock Textarea componentvi.mock('@/app/components/base/textarea', () => ({default: ({ value, onChange, placeholder, className }: {value: string@@ -430,7 +395,6 @@ vi.mock('@/app/components/base/textarea', () => ({),}))-// Mock AppIcon componentvi.mock('@/app/components/base/app-icon', () => ({default: ({ onClick, iconType, icon, background, imageUrl, className, size }: {onClick?: () => void@@ -454,7 +418,6 @@ vi.mock('@/app/components/base/app-icon', () => ({),}))-// Mock AppIconPicker componentvi.mock('@/app/components/base/app-icon-picker', () => ({default: ({ onSelect, onClose }: {onSelect: (item: { type: string, icon?: string, background?: string, url?: string }) => void@@ -478,7 +441,6 @@ vi.mock('@/app/components/base/app-icon-picker', () => ({),}))-// Mock Uploader componentvi.mock('@/app/components/app/create-from-dsl-modal/uploader', () => ({default: ({ file, updateFile, className, accept, displayName }: {file?: File@@ -504,25 +466,21 @@ vi.mock('@/app/components/app/create-from-dsl-modal/uploader', () => ({),}))-// Mock use-context-selectorvi.mock('use-context-selector', () => ({useContext: vi.fn(() => ({notify: vi.fn(),})),}))-// Mock RagPipelineHeader-vi.mock('./rag-pipeline-header', () => ({+vi.mock('../rag-pipeline-header', () => ({default: () => <div data-testid="rag-pipeline-header" />,}))-// Mock PublishToast-vi.mock('./publish-toast', () => ({+vi.mock('../publish-toast', () => ({default: () => <div data-testid="publish-toast" />,}))-// Mock UpdateDSLModal for RagPipelineChildren tests-vi.mock('./update-dsl-modal', () => ({+vi.mock('../update-dsl-modal', () => ({default: ({ onCancel, onBackup, onImport }: {onCancel: () => voidonBackup: () => void@@ -536,7 +494,6 @@ vi.mock('./update-dsl-modal', () => ({),}))-// Mock DSLExportConfirmModal for RagPipelineChildren testsvi.mock('@/app/components/workflow/dsl-export-confirm-modal', () => ({default: ({ envList, onConfirm, onClose }: {envList: EnvironmentVariable[]@@ -555,18 +512,11 @@ vi.mock('@/app/components/workflow/dsl-export-confirm-modal', () => ({),}))-// ============================================================================-// Test Suites-// ============================================================================-describe('Conversion', () => {beforeEach(() => {vi.clearAllMocks()})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render conversion component without crashing', () => {render(<Conversion />)@@ -600,9 +550,6 @@ describe('Conversion', () => {})})- // --------------------------------------------------------------------------- // User Interactions Tests- // --------------------------------------------------------------------------describe('User Interactions', () => {it('should show confirm modal when convert button is clicked', () => {render(<Conversion />)@@ -617,20 +564,15 @@ describe('Conversion', () => {it('should hide confirm modal when cancel is clicked', () => {render(<Conversion />)- // Open modalconst convertButton = screen.getByRole('button', { name: /datasetPipeline\.operations\.convert/i })fireEvent.click(convertButton)expect(screen.getByTestId('confirm-modal')).toBeInTheDocument()- // Cancel modalfireEvent.click(screen.getByTestId('cancel-btn'))expect(screen.queryByTestId('confirm-modal')).not.toBeInTheDocument()})})- // --------------------------------------------------------------------------- // API Callback Tests - covers lines 21-39- // --------------------------------------------------------------------------describe('API Callbacks', () => {beforeEach(() => {mockConvertFn = vi.fn()@@ -638,14 +580,12 @@ describe('Conversion', () => {})it('should call convert with datasetId and show success toast on success', async () => {- // Setup mock to capture and call onSuccess callbackmockConvertFn.mockImplementation((_datasetId: string, options: { onSuccess: (res: { status: string }) => void }) => {options.onSuccess({ status: 'success' })})render(<Conversion />)- // Open modal and confirmconst convertButton = screen.getByRole('button', { name: /datasetPipeline\.operations\.convert/i })fireEvent.click(convertButton)fireEvent.click(screen.getByTestId('confirm-btn'))@@ -690,7 +630,6 @@ describe('Conversion', () => {await waitFor(() => {expect(mockConvertFn).toHaveBeenCalled()})- // Modal should still be visible since conversion failedexpect(screen.getByTestId('confirm-modal')).toBeInTheDocument()})@@ -711,32 +650,23 @@ describe('Conversion', () => {})})- // --------------------------------------------------------------------------- // Memoization Tests- // --------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with React.memo', () => {- // Conversion is exported with React.memoexpect((Conversion as unknown as { $$typeof: symbol }).$$typeof).toBe(Symbol.for('react.memo'))})it('should use useCallback for handleConvert', () => {const { rerender } = render(<Conversion />)- // Rerender should not cause issues with callbackrerender(<Conversion />)expect(screen.getByRole('button', { name: /datasetPipeline\.operations\.convert/i })).toBeInTheDocument()})})- // --------------------------------------------------------------------------- // Edge Cases Tests- // --------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle missing datasetId gracefully', () => {render(<Conversion />)- // Component should render without crashingexpect(screen.getByText('datasetPipeline.conversion.title')).toBeInTheDocument()})})@@ -747,9 +677,6 @@ describe('PipelineScreenShot', () => {vi.clearAllMocks()})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {render(<PipelineScreenShot />)@@ -770,14 +697,10 @@ describe('PipelineScreenShot', () => {render(<PipelineScreenShot />)const img = screen.getByTestId('mock-image')- // Default theme is 'light' from mockexpect(img).toHaveAttribute('src', '/public/screenshots/light/Pipeline.png')})})- // --------------------------------------------------------------------------- // Memoization Tests- // --------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with React.memo', () => {expect((PipelineScreenShot as unknown as { $$typeof: symbol }).$$typeof).toBe(Symbol.for('react.memo'))@@ -790,9 +713,6 @@ describe('PublishToast', () => {vi.clearAllMocks()})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {// Note: PublishToast is mocked, so we just verify the mock renders@@ -802,12 +722,8 @@ describe('PublishToast', () => {})})- // --------------------------------------------------------------------------- // Memoization Tests- // --------------------------------------------------------------------------describe('Memoization', () => {it('should be defined', () => {- // The real PublishToast is mocked, but we can verify the importexpect(PublishToast).toBeDefined()})})@@ -826,9 +742,6 @@ describe('PublishAsKnowledgePipelineModal', () => {onConfirm: mockOnConfirm,}- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render modal with title', () => {render(<PublishAsKnowledgePipelineModal {...defaultProps} />)@@ -863,9 +776,6 @@ describe('PublishAsKnowledgePipelineModal', () => {})})- // --------------------------------------------------------------------------- // User Interactions Tests- // --------------------------------------------------------------------------describe('User Interactions', () => {it('should update name when input changes', () => {render(<PublishAsKnowledgePipelineModal {...defaultProps} />)@@ -906,11 +816,9 @@ describe('PublishAsKnowledgePipelineModal', () => {render(<PublishAsKnowledgePipelineModal {...defaultProps} />)- // Update valuesfireEvent.change(screen.getByTestId('input'), { target: { value: ' Trimmed Name ' } })fireEvent.change(screen.getByTestId('textarea'), { target: { value: ' Trimmed Description ' } })- // Click publishfireEvent.click(screen.getByRole('button', { name: /workflow\.common\.publish/i }))expect(mockOnConfirm).toHaveBeenCalledWith(@@ -931,52 +839,39 @@ describe('PublishAsKnowledgePipelineModal', () => {it('should update icon when emoji is selected', () => {render(<PublishAsKnowledgePipelineModal {...defaultProps} />)- // Open pickerfireEvent.click(screen.getByTestId('app-icon'))- // Select emojifireEvent.click(screen.getByTestId('select-emoji'))- // Picker should closeexpect(screen.queryByTestId('app-icon-picker')).not.toBeInTheDocument()})it('should update icon when image is selected', () => {render(<PublishAsKnowledgePipelineModal {...defaultProps} />)- // Open pickerfireEvent.click(screen.getByTestId('app-icon'))- // Select imagefireEvent.click(screen.getByTestId('select-image'))- // Picker should closeexpect(screen.queryByTestId('app-icon-picker')).not.toBeInTheDocument()})it('should close picker and restore icon when picker is closed', () => {render(<PublishAsKnowledgePipelineModal {...defaultProps} />)- // Open pickerfireEvent.click(screen.getByTestId('app-icon'))expect(screen.getByTestId('app-icon-picker')).toBeInTheDocument()- // Close pickerfireEvent.click(screen.getByTestId('close-picker'))- // Picker should closeexpect(screen.queryByTestId('app-icon-picker')).not.toBeInTheDocument()})})- // --------------------------------------------------------------------------- // Props Validation Tests- // --------------------------------------------------------------------------describe('Props Validation', () => {it('should disable publish button when name is empty', () => {render(<PublishAsKnowledgePipelineModal {...defaultProps} />)- // Clear the namefireEvent.change(screen.getByTestId('input'), { target: { value: '' } })const publishButton = screen.getByRole('button', { name: /workflow\.common\.publish/i })@@ -986,7 +881,6 @@ describe('PublishAsKnowledgePipelineModal', () => {it('should disable publish button when name is only whitespace', () => {render(<PublishAsKnowledgePipelineModal {...defaultProps} />)- // Set whitespace-only namefireEvent.change(screen.getByTestId('input'), { target: { value: ' ' } })const publishButton = screen.getByRole('button', { name: /workflow\.common\.publish/i })@@ -1009,14 +903,10 @@ describe('PublishAsKnowledgePipelineModal', () => {})})- // --------------------------------------------------------------------------- // Memoization Tests- // --------------------------------------------------------------------------describe('Memoization', () => {it('should use useCallback for handleSelectIcon', () => {const { rerender } = render(<PublishAsKnowledgePipelineModal {...defaultProps} />)- // Rerender should not cause issuesrerender(<PublishAsKnowledgePipelineModal {...defaultProps} />)expect(screen.getByTestId('app-icon')).toBeInTheDocument()})@@ -1028,9 +918,6 @@ describe('RagPipelinePanel', () => {vi.clearAllMocks()})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render panel component without crashing', () => {render(<RagPipelinePanel />)@@ -1046,9 +933,6 @@ describe('RagPipelinePanel', () => {})})- // --------------------------------------------------------------------------- // Memoization Tests- // --------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with memo', () => {expect((RagPipelinePanel as unknown as { $$typeof: symbol }).$$typeof).toBe(Symbol.for('react.memo'))@@ -1063,9 +947,6 @@ describe('RagPipelineChildren', () => {mockEventSubscriptionCallback = null})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {render(<RagPipelineChildren />)@@ -1090,9 +971,6 @@ describe('RagPipelineChildren', () => {})})- // --------------------------------------------------------------------------- // Event Subscription Tests - covers lines 37-40- // --------------------------------------------------------------------------describe('Event Subscription', () => {it('should subscribe to event emitter', () => {render(<RagPipelineChildren />)@@ -1103,12 +981,10 @@ describe('RagPipelineChildren', () => {it('should handle DSL_EXPORT_CHECK event and set secretEnvList', async () => {render(<RagPipelineChildren />)- // Simulate DSL_EXPORT_CHECK eventconst mockEnvVariables: EnvironmentVariable[] = [{ id: '1', name: 'SECRET_KEY', value: 'test-secret', value_type: 'secret' as const, description: '' },]- // Trigger the subscription callbackif (mockEventSubscriptionCallback) {mockEventSubscriptionCallback({type: 'DSL_EXPORT_CHECK',@@ -1116,7 +992,6 @@ describe('RagPipelineChildren', () => {})}- // DSLExportConfirmModal should be renderedawait waitFor(() => {expect(screen.getByTestId('dsl-export-confirm-modal')).toBeInTheDocument()})@@ -1125,7 +1000,6 @@ describe('RagPipelineChildren', () => {it('should not show DSLExportConfirmModal for non-DSL_EXPORT_CHECK events', () => {render(<RagPipelineChildren />)- // Trigger a different event typeif (mockEventSubscriptionCallback) {mockEventSubscriptionCallback({type: 'OTHER_EVENT',@@ -1136,9 +1010,6 @@ describe('RagPipelineChildren', () => {})})- // --------------------------------------------------------------------------- // UpdateDSLModal Handlers Tests - covers lines 48-51- // --------------------------------------------------------------------------describe('UpdateDSLModal Handlers', () => {beforeEach(() => {mockShowImportDSLModal = true@@ -1168,14 +1039,10 @@ describe('RagPipelineChildren', () => {})})- // --------------------------------------------------------------------------- // DSLExportConfirmModal Tests - covers lines 55-60- // --------------------------------------------------------------------------describe('DSLExportConfirmModal', () => {it('should render DSLExportConfirmModal when secretEnvList has items', async () => {render(<RagPipelineChildren />)- // Simulate DSL_EXPORT_CHECK event with secretsconst mockEnvVariables: EnvironmentVariable[] = [{ id: '1', name: 'API_KEY', value: 'secret-value', value_type: 'secret' as const, description: '' },]@@ -1195,7 +1062,6 @@ describe('RagPipelineChildren', () => {it('should close DSLExportConfirmModal when onClose is triggered', async () => {render(<RagPipelineChildren />)- // First show the modalconst mockEnvVariables: EnvironmentVariable[] = [{ id: '1', name: 'API_KEY', value: 'secret-value', value_type: 'secret' as const, description: '' },]@@ -1211,7 +1077,6 @@ describe('RagPipelineChildren', () => {expect(screen.getByTestId('dsl-export-confirm-modal')).toBeInTheDocument()})- // Close the modalfireEvent.click(screen.getByTestId('dsl-export-close'))await waitFor(() => {@@ -1222,7 +1087,6 @@ describe('RagPipelineChildren', () => {it('should call handleExportDSL when onConfirm is triggered', async () => {render(<RagPipelineChildren />)- // Show the modalconst mockEnvVariables: EnvironmentVariable[] = [{ id: '1', name: 'API_KEY', value: 'secret-value', value_type: 'secret' as const, description: '' },]@@ -1238,16 +1102,12 @@ describe('RagPipelineChildren', () => {expect(screen.getByTestId('dsl-export-confirm-modal')).toBeInTheDocument()})- // Confirm exportfireEvent.click(screen.getByTestId('dsl-export-confirm'))expect(mockHandleExportDSL).toHaveBeenCalledTimes(1)})})- // --------------------------------------------------------------------------- // Memoization Tests- // --------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with memo', () => {expect((RagPipelineChildren as unknown as { $$typeof: symbol }).$$typeof).toBe(Symbol.for('react.memo'))@@ -1255,10 +1115,6 @@ describe('RagPipelineChildren', () => {})})-// ============================================================================-// Integration Tests-// ============================================================================-describe('Integration Tests', () => {beforeEach(() => {vi.clearAllMocks()@@ -1276,17 +1132,13 @@ describe('Integration Tests', () => {/>,)- // Update namefireEvent.change(screen.getByTestId('input'), { target: { value: 'My Pipeline' } })- // Add descriptionfireEvent.change(screen.getByTestId('textarea'), { target: { value: 'A great pipeline' } })- // Change iconfireEvent.click(screen.getByTestId('app-icon'))fireEvent.click(screen.getByTestId('select-emoji'))- // PublishfireEvent.click(screen.getByRole('button', { name: /workflow\.common\.publish/i }))await waitFor(() => {@@ -1304,10 +1156,6 @@ describe('Integration Tests', () => {})})-// ============================================================================-// Edge Cases-// ============================================================================-describe('Edge Cases', () => {beforeEach(() => {vi.clearAllMocks()@@ -1322,7 +1170,6 @@ describe('Edge Cases', () => {/>,)- // Clear the nameconst input = screen.getByTestId('input')fireEvent.change(input, { target: { value: '' } })expect(input).toHaveValue('')@@ -1360,10 +1207,6 @@ describe('Edge Cases', () => {})})-// ============================================================================-// Accessibility Tests-// ============================================================================-describe('Accessibility', () => {describe('Conversion', () => {it('should have accessible button', () => {diff --git a/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsxnew file mode 100644index 00000000000..0d6687cbed2--- /dev/null+++ b/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx@@ -0,0 +1,244 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import PublishAsKnowledgePipelineModal from '../publish-as-knowledge-pipeline-modal'++vi.mock('@/app/components/workflow/store', () => ({+ useWorkflowStore: () => ({+ getState: () => ({+ knowledgeName: 'Test Pipeline',+ knowledgeIcon: {+ icon_type: 'emoji',+ icon: '🔧',+ icon_background: '#fff',+ icon_url: '',+ },+ }),+ }),+}))++vi.mock('@/app/components/base/modal', () => ({+ default: ({ children, isShow }: { children: React.ReactNode, isShow: boolean }) =>+ isShow ? <div data-testid="modal">{children}</div> : null,+}))++vi.mock('@/app/components/base/button', () => ({+ default: ({ children, onClick, disabled, ...props }: Record<string, unknown>) => (+ <button onClick={onClick as () => void} disabled={disabled as boolean} {...props}>+ {children as string}+ </button>+ ),+}))++vi.mock('@/app/components/base/input', () => ({+ default: ({ value, onChange, ...props }: Record<string, unknown>) => (+ <input+ data-testid="name-input"+ value={value as string}+ onChange={onChange as () => void}+ {...props}+ />+ ),+}))++vi.mock('@/app/components/base/textarea', () => ({+ default: ({ value, onChange, ...props }: Record<string, unknown>) => (+ <textarea+ data-testid="description-textarea"+ value={value as string}+ onChange={onChange as () => void}+ {...props}+ />+ ),+}))++vi.mock('@/app/components/base/app-icon', () => ({+ default: ({ onClick }: { onClick?: () => void }) => (+ <div data-testid="app-icon" onClick={onClick} />+ ),+}))++vi.mock('@/app/components/base/app-icon-picker', () => ({+ default: ({ onSelect, onClose }: { onSelect: (item: { type: string, icon: string, background: string, url: string }) => void, onClose: () => void }) => (+ <div data-testid="icon-picker">+ <button data-testid="select-emoji" onClick={() => onSelect({ type: 'emoji', icon: '🎉', background: '#eee', url: '' })}>+ Select Emoji+ </button>+ <button data-testid="select-image" onClick={() => onSelect({ type: 'image', icon: '', background: '', url: 'http://img.png' })}>+ Select Image+ </button>+ <button data-testid="close-picker" onClick={onClose}>+ Close+ </button>+ </div>+ ),+}))++vi.mock('es-toolkit/function', () => ({+ noop: () => {},+}))++describe('PublishAsKnowledgePipelineModal', () => {+ const mockOnCancel = vi.fn()+ const mockOnConfirm = vi.fn().mockResolvedValue(undefined)++ const defaultProps = {+ onCancel: mockOnCancel,+ onConfirm: mockOnConfirm,+ }++ beforeEach(() => {+ vi.clearAllMocks()+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('should render modal with title', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ expect(screen.getByTestId('modal')).toBeInTheDocument()+ expect(screen.getByText('pipeline.common.publishAs')).toBeInTheDocument()+ })++ it('should initialize with knowledgeName from store', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ const nameInput = screen.getByTestId('name-input') as HTMLInputElement+ expect(nameInput.value).toBe('Test Pipeline')+ })++ it('should initialize description as empty', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ const textarea = screen.getByTestId('description-textarea') as HTMLTextAreaElement+ expect(textarea.value).toBe('')+ })++ it('should call onCancel when close button clicked', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ fireEvent.click(screen.getByTestId('publish-modal-close-btn'))++ expect(mockOnCancel).toHaveBeenCalled()+ })++ it('should call onCancel when cancel button clicked', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ fireEvent.click(screen.getByText('common.operation.cancel'))++ expect(mockOnCancel).toHaveBeenCalled()+ })++ it('should call onConfirm with name, icon, and description when confirm clicked', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ fireEvent.click(screen.getByText('workflow.common.publish'))++ expect(mockOnConfirm).toHaveBeenCalledWith(+ 'Test Pipeline',+ expect.objectContaining({ icon_type: 'emoji', icon: '🔧' }),+ '',+ )+ })++ it('should update pipeline name when input changes', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ const nameInput = screen.getByTestId('name-input')+ fireEvent.change(nameInput, { target: { value: 'New Name' } })++ expect((nameInput as HTMLInputElement).value).toBe('New Name')+ })++ it('should update description when textarea changes', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ const textarea = screen.getByTestId('description-textarea')+ fireEvent.change(textarea, { target: { value: 'My description' } })++ expect((textarea as HTMLTextAreaElement).value).toBe('My description')+ })++ it('should disable confirm button when name is empty', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ const nameInput = screen.getByTestId('name-input')+ fireEvent.change(nameInput, { target: { value: '' } })++ const confirmBtn = screen.getByText('workflow.common.publish')+ expect(confirmBtn).toBeDisabled()+ })++ it('should disable confirm button when confirmDisabled is true', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} confirmDisabled />)++ const confirmBtn = screen.getByText('workflow.common.publish')+ expect(confirmBtn).toBeDisabled()+ })++ it('should not call onConfirm when confirmDisabled is true', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} confirmDisabled />)++ fireEvent.click(screen.getByText('workflow.common.publish'))++ expect(mockOnConfirm).not.toHaveBeenCalled()+ })++ it('should show icon picker when app icon clicked', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ expect(screen.queryByTestId('icon-picker')).not.toBeInTheDocument()++ fireEvent.click(screen.getByTestId('app-icon'))++ expect(screen.getByTestId('icon-picker')).toBeInTheDocument()+ })++ it('should update icon when emoji is selected', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ fireEvent.click(screen.getByTestId('app-icon'))+ fireEvent.click(screen.getByTestId('select-emoji'))++ expect(screen.queryByTestId('icon-picker')).not.toBeInTheDocument()+ })++ it('should update icon when image is selected', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ fireEvent.click(screen.getByTestId('app-icon'))+ fireEvent.click(screen.getByTestId('select-image'))++ expect(screen.queryByTestId('icon-picker')).not.toBeInTheDocument()+ })++ it('should close icon picker when close is clicked', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ fireEvent.click(screen.getByTestId('app-icon'))+ fireEvent.click(screen.getByTestId('close-picker'))++ expect(screen.queryByTestId('icon-picker')).not.toBeInTheDocument()+ })++ it('should trim name and description before submitting', () => {+ render(<PublishAsKnowledgePipelineModal {...defaultProps} />)++ const nameInput = screen.getByTestId('name-input')+ fireEvent.change(nameInput, { target: { value: ' Trimmed Name ' } })++ const textarea = screen.getByTestId('description-textarea')+ fireEvent.change(textarea, { target: { value: ' Some desc ' } })++ fireEvent.click(screen.getByText('workflow.common.publish'))++ expect(mockOnConfirm).toHaveBeenCalledWith(+ 'Trimmed Name',+ expect.any(Object),+ 'Some desc',+ )+ })+})diff --git a/web/app/components/rag-pipeline/components/publish-toast.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/publish-toast.spec.tsxsimilarity index 69%rename from web/app/components/rag-pipeline/components/publish-toast.spec.tsxrename to web/app/components/rag-pipeline/components/__tests__/publish-toast.spec.tsxindex d61f091ed2a..0e65f8f1db3 100644--- a/web/app/components/rag-pipeline/components/publish-toast.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/publish-toast.spec.tsx@@ -1,15 +1,7 @@import { cleanup, fireEvent, render, screen } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import PublishToast from './publish-toast'+import PublishToast from '../publish-toast'-// Mock react-i18next-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string) => key,- }),-}))--// Mock workflow store with controllable statelet mockPublishedAt = 0vi.mock('@/app/components/workflow/store', () => ({useStore: (selector: (state: Record<string, unknown>) => unknown) => {@@ -32,19 +24,19 @@ describe('PublishToast', () => {mockPublishedAt = 0render(<PublishToast />)- expect(screen.getByText('publishToast.title')).toBeInTheDocument()+ expect(screen.getByText('pipeline.publishToast.title')).toBeInTheDocument()})it('should render toast title', () => {render(<PublishToast />)- expect(screen.getByText('publishToast.title')).toBeInTheDocument()+ expect(screen.getByText('pipeline.publishToast.title')).toBeInTheDocument()})it('should render toast description', () => {render(<PublishToast />)- expect(screen.getByText('publishToast.desc')).toBeInTheDocument()+ expect(screen.getByText('pipeline.publishToast.desc')).toBeInTheDocument()})it('should not render when publishedAt is set', () => {@@ -57,14 +49,13 @@ describe('PublishToast', () => {it('should have correct positioning classes', () => {render(<PublishToast />)- const container = screen.getByText('publishToast.title').closest('.absolute')+ const container = screen.getByText('pipeline.publishToast.title').closest('.absolute')expect(container).toHaveClass('bottom-[45px]', 'left-0', 'right-0', 'z-10')})it('should render info icon', () => {const { container } = render(<PublishToast />)- // The RiInformation2Fill icon should be renderedconst iconContainer = container.querySelector('.text-text-accent')expect(iconContainer).toBeInTheDocument()})@@ -72,7 +63,6 @@ describe('PublishToast', () => {it('should render close button', () => {const { container } = render(<PublishToast />)- // The close button is a div with cursor-pointer, not a semantic buttonconst closeButton = container.querySelector('.cursor-pointer')expect(closeButton).toBeInTheDocument()})@@ -82,25 +72,23 @@ describe('PublishToast', () => {it('should hide toast when close button is clicked', () => {const { container } = render(<PublishToast />)- // The close button is a div with cursor-pointer, not a semantic buttonconst closeButton = container.querySelector('.cursor-pointer')- expect(screen.getByText('publishToast.title')).toBeInTheDocument()+ expect(screen.getByText('pipeline.publishToast.title')).toBeInTheDocument()fireEvent.click(closeButton!)- expect(screen.queryByText('publishToast.title')).not.toBeInTheDocument()+ expect(screen.queryByText('pipeline.publishToast.title')).not.toBeInTheDocument()})it('should remain hidden after close button is clicked', () => {const { container, rerender } = render(<PublishToast />)- // The close button is a div with cursor-pointer, not a semantic buttonconst closeButton = container.querySelector('.cursor-pointer')fireEvent.click(closeButton!)rerender(<PublishToast />)- expect(screen.queryByText('publishToast.title')).not.toBeInTheDocument()+ expect(screen.queryByText('pipeline.publishToast.title')).not.toBeInTheDocument()})})@@ -115,14 +103,14 @@ describe('PublishToast', () => {it('should have correct toast width', () => {render(<PublishToast />)- const toastContainer = screen.getByText('publishToast.title').closest('.w-\\[420px\\]')+ const toastContainer = screen.getByText('pipeline.publishToast.title').closest('.w-\\[420px\\]')expect(toastContainer).toBeInTheDocument()})it('should have rounded border', () => {render(<PublishToast />)- const toastContainer = screen.getByText('publishToast.title').closest('.rounded-xl')+ const toastContainer = screen.getByText('pipeline.publishToast.title').closest('.rounded-xl')expect(toastContainer).toBeInTheDocument()})})diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-main.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsxsimilarity index 94%rename from web/app/components/rag-pipeline/components/rag-pipeline-main.spec.tsxrename to web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsxindex 3de3c3deeb9..22d38861dad 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-main.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsx@@ -2,10 +2,9 @@ import type { PropsWithChildren } from 'react'import type { Edge, Node, Viewport } from 'reactflow'import { cleanup, render, screen } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import RagPipelineMain from './rag-pipeline-main'+import RagPipelineMain from '../rag-pipeline-main'-// Mock hooks from ../hooks-vi.mock('../hooks', () => ({+vi.mock('../../hooks', () => ({useAvailableNodesMetaData: () => ({ nodes: [], nodesMap: {} }),useDSL: () => ({exportCheck: vi.fn(),@@ -34,8 +33,7 @@ vi.mock('../hooks', () => ({}),}))-// Mock useConfigsMap-vi.mock('../hooks/use-configs-map', () => ({+vi.mock('../../hooks/use-configs-map', () => ({useConfigsMap: () => ({flowId: 'test-flow-id',flowType: 'ragPipeline',@@ -43,8 +41,7 @@ vi.mock('../hooks/use-configs-map', () => ({}),}))-// Mock useInspectVarsCrud-vi.mock('../hooks/use-inspect-vars-crud', () => ({+vi.mock('../../hooks/use-inspect-vars-crud', () => ({useInspectVarsCrud: () => ({hasNodeInspectVars: vi.fn(),hasSetInspectVar: vi.fn(),@@ -63,7 +60,6 @@ vi.mock('../hooks/use-inspect-vars-crud', () => ({}),}))-// Mock workflow storeconst mockSetRagPipelineVariables = vi.fn()const mockSetEnvironmentVariables = vi.fn()vi.mock('@/app/components/workflow/store', () => ({@@ -75,14 +71,12 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock workflow hooksvi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({useSetWorkflowVarsWithValue: () => ({fetchInspectVars: vi.fn(),}),}))-// Mock WorkflowWithInnerContextvi.mock('@/app/components/workflow', () => ({WorkflowWithInnerContext: ({ children, onWorkflowDataUpdate }: PropsWithChildren<{ onWorkflowDataUpdate?: (payload: unknown) => void }>) => (<div data-testid="workflow-inner-context">@@ -108,8 +102,7 @@ vi.mock('@/app/components/workflow', () => ({),}))-// Mock RagPipelineChildren-vi.mock('./rag-pipeline-children', () => ({+vi.mock('../rag-pipeline-children', () => ({default: () => <div data-testid="rag-pipeline-children">Children</div>,}))@@ -201,7 +194,6 @@ describe('RagPipelineMain', () => {it('should use useNodesSyncDraft hook', () => {render(<RagPipelineMain {...defaultProps} />)- // If the component renders, the hook was called successfullyexpect(screen.getByTestId('workflow-inner-context')).toBeInTheDocument()})diff --git a/web/app/components/rag-pipeline/components/update-dsl-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsxsimilarity index 77%rename from web/app/components/rag-pipeline/components/update-dsl-modal.spec.tsxrename to web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsxindex addfa3dc532..2f9b2172bd3 100644--- a/web/app/components/rag-pipeline/components/update-dsl-modal.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx@@ -2,7 +2,7 @@ import type { PropsWithChildren } from 'react'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { DSLImportStatus } from '@/models/app'-import UpdateDSLModal from './update-dsl-modal'+import UpdateDSLModal from '../update-dsl-modal'class MockFileReader {onload: ((this: FileReader, event: ProgressEvent<FileReader>) => void) | null = null@@ -15,25 +15,15 @@ class MockFileReader {vi.stubGlobal('FileReader', MockFileReader as unknown as typeof FileReader)-// Mock react-i18next-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string) => key,- }),-}))--// Mock use-context-selectorconst mockNotify = vi.fn()vi.mock('use-context-selector', () => ({useContext: () => ({ notify: mockNotify }),}))-// Mock toast contextvi.mock('@/app/components/base/toast', () => ({ToastContext: { Provider: ({ children }: PropsWithChildren) => children },}))-// Mock event emitterconst mockEmit = vi.fn()vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({@@ -41,7 +31,6 @@ vi.mock('@/context/event-emitter', () => ({}),}))-// Mock workflow storevi.mock('@/app/components/workflow/store', () => ({useWorkflowStore: () => ({getState: () => ({@@ -50,13 +39,11 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock workflow utilsvi.mock('@/app/components/workflow/utils', () => ({initialNodes: (nodes: unknown[]) => nodes,initialEdges: (edges: unknown[]) => edges,}))-// Mock plugin dependenciesconst mockHandleCheckPluginDependencies = vi.fn()vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({usePluginDependencies: () => ({@@ -64,7 +51,6 @@ vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({}),}))-// Mock pipeline serviceconst mockImportDSL = vi.fn()const mockImportDSLConfirm = vi.fn()vi.mock('@/service/use-pipeline', () => ({@@ -72,7 +58,6 @@ vi.mock('@/service/use-pipeline', () => ({useImportPipelineDSLConfirm: () => ({ mutateAsync: mockImportDSLConfirm }),}))-// Mock workflow servicevi.mock('@/service/workflow', () => ({fetchWorkflowDraft: vi.fn().mockResolvedValue({graph: { nodes: [], edges: [], viewport: { x: 0, y: 0, zoom: 1 } },@@ -81,7 +66,6 @@ vi.mock('@/service/workflow', () => ({}),}))-// Mock Uploadervi.mock('@/app/components/app/create-from-dsl-modal/uploader', () => ({default: ({ updateFile }: { updateFile: (file?: File) => void }) => (<div data-testid="uploader">@@ -103,7 +87,6 @@ vi.mock('@/app/components/app/create-from-dsl-modal/uploader', () => ({),}))-// Mock Buttonvi.mock('@/app/components/base/button', () => ({default: ({ children, onClick, disabled, className, variant, loading }: {children: React.ReactNode@@ -125,7 +108,6 @@ vi.mock('@/app/components/base/button', () => ({),}))-// Mock Modalvi.mock('@/app/components/base/modal', () => ({default: ({ children, isShow, _onClose, className }: PropsWithChildren<{isShow: boolean@@ -140,7 +122,6 @@ vi.mock('@/app/components/base/modal', () => ({: null,}))-// Mock workflow constantsvi.mock('@/app/components/workflow/constants', () => ({WORKFLOW_DATA_UPDATE: 'WORKFLOW_DATA_UPDATE',}))@@ -176,15 +157,13 @@ describe('UpdateDSLModal', () => {it('should render title', () => {render(<UpdateDSLModal {...defaultProps} />)- // The component uses t('common.importDSL', { ns: 'workflow' }) which returns 'common.importDSL'- expect(screen.getByText('common.importDSL')).toBeInTheDocument()+ expect(screen.getByText('workflow.common.importDSL')).toBeInTheDocument()})it('should render warning tip', () => {render(<UpdateDSLModal {...defaultProps} />)- // The component uses t('common.importDSLTip', { ns: 'workflow' })- expect(screen.getByText('common.importDSLTip')).toBeInTheDocument()+ expect(screen.getByText('workflow.common.importDSLTip')).toBeInTheDocument()})it('should render uploader', () => {@@ -196,29 +175,25 @@ describe('UpdateDSLModal', () => {it('should render backup button', () => {render(<UpdateDSLModal {...defaultProps} />)- // The component uses t('common.backupCurrentDraft', { ns: 'workflow' })- expect(screen.getByText('common.backupCurrentDraft')).toBeInTheDocument()+ expect(screen.getByText('workflow.common.backupCurrentDraft')).toBeInTheDocument()})it('should render cancel button', () => {render(<UpdateDSLModal {...defaultProps} />)- // The component uses t('newApp.Cancel', { ns: 'app' })- expect(screen.getByText('newApp.Cancel')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.Cancel')).toBeInTheDocument()})it('should render import button', () => {render(<UpdateDSLModal {...defaultProps} />)- // The component uses t('common.overwriteAndImport', { ns: 'workflow' })- expect(screen.getByText('common.overwriteAndImport')).toBeInTheDocument()+ expect(screen.getByText('workflow.common.overwriteAndImport')).toBeInTheDocument()})it('should render choose DSL section', () => {render(<UpdateDSLModal {...defaultProps} />)- // The component uses t('common.chooseDSL', { ns: 'workflow' })- expect(screen.getByText('common.chooseDSL')).toBeInTheDocument()+ expect(screen.getByText('workflow.common.chooseDSL')).toBeInTheDocument()})})@@ -226,7 +201,7 @@ describe('UpdateDSLModal', () => {it('should call onCancel when cancel button is clicked', () => {render(<UpdateDSLModal {...defaultProps} />)- const cancelButton = screen.getByText('newApp.Cancel')+ const cancelButton = screen.getByText('app.newApp.Cancel')fireEvent.click(cancelButton)expect(mockOnCancel).toHaveBeenCalled()@@ -235,7 +210,7 @@ describe('UpdateDSLModal', () => {it('should call onBackup when backup button is clicked', () => {render(<UpdateDSLModal {...defaultProps} />)- const backupButton = screen.getByText('common.backupCurrentDraft')+ const backupButton = screen.getByText('workflow.common.backupCurrentDraft')fireEvent.click(backupButton)expect(mockOnBackup).toHaveBeenCalled()@@ -249,7 +224,6 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })- // File should be processedawait waitFor(() => {expect(screen.getByTestId('uploader')).toBeInTheDocument()})@@ -261,14 +235,12 @@ describe('UpdateDSLModal', () => {const clearButton = screen.getByTestId('clear-file')fireEvent.click(clearButton)- // File should be clearedexpect(screen.getByTestId('uploader')).toBeInTheDocument()})it('should call onCancel when close icon is clicked', () => {render(<UpdateDSLModal {...defaultProps} />)- // The close icon is in a div with onClick={onCancel}const closeIconContainer = document.querySelector('.cursor-pointer')if (closeIconContainer) {fireEvent.click(closeIconContainer)@@ -281,7 +253,7 @@ describe('UpdateDSLModal', () => {it('should show import button disabled when no file is selected', () => {render(<UpdateDSLModal {...defaultProps} />)- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).toBeDisabled()})@@ -294,7 +266,7 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})})@@ -302,22 +274,20 @@ describe('UpdateDSLModal', () => {it('should disable import button after file is cleared', async () => {render(<UpdateDSLModal {...defaultProps} />)- // First select a fileconst fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- // Clear the fileconst clearButton = screen.getByTestId('clear-file')fireEvent.click(clearButton)await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).toBeDisabled()})})@@ -344,15 +314,14 @@ describe('UpdateDSLModal', () => {it('should render import button with warning variant', () => {render(<UpdateDSLModal {...defaultProps} />)- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).toHaveAttribute('data-variant', 'warning')})it('should render backup button with secondary variant', () => {render(<UpdateDSLModal {...defaultProps} />)- // The backup button text is inside a nested div, so we need to find the closest button- const backupButtonText = screen.getByText('common.backupCurrentDraft')+ const backupButtonText = screen.getByText('workflow.common.backupCurrentDraft')const backupButton = backupButtonText.closest('button')expect(backupButton).toHaveAttribute('data-variant', 'secondary')})@@ -362,22 +331,18 @@ describe('UpdateDSLModal', () => {it('should call importDSL when import button is clicked with file content', async () => {render(<UpdateDSLModal {...defaultProps} />)- // Select a fileconst fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })fireEvent.change(fileInput, { target: { files: [file] } })- // Wait for FileReader to processawait waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- // Click import button- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)- // Wait for import to be calledawait waitFor(() => {expect(mockImportDSL).toHaveBeenCalled()})@@ -392,17 +357,16 @@ describe('UpdateDSLModal', () => {render(<UpdateDSLModal {...defaultProps} />)- // Select a file and click importconst fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -426,11 +390,11 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -452,11 +416,11 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()}, { timeout: 1000 })- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -478,11 +442,11 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -506,11 +470,11 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -533,13 +497,12 @@ describe('UpdateDSLModal', () => {const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })fireEvent.change(fileInput, { target: { files: [file] } })- // Wait for FileReader to process and button to be enabledawait waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -558,13 +521,12 @@ describe('UpdateDSLModal', () => {const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })fireEvent.change(fileInput, { target: { files: [file] } })- // Wait for FileReader to complete and button to be enabledawait waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -588,16 +550,15 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- // Flush the FileReader microtask to ensure fileContent is setawait act(async () => {await new Promise<void>(resolve => queueMicrotask(resolve))})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -619,11 +580,11 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {@@ -649,23 +610,20 @@ describe('UpdateDSLModal', () => {await act(async () => {fireEvent.change(fileInput, { target: { files: [file] } })- // Flush microtasks scheduled by the FileReader mock (which uses queueMicrotask)await new Promise<void>(resolve => queueMicrotask(resolve))})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()await act(async () => {fireEvent.click(importButton)- // Flush the promise resolution from mockImportDSLawait Promise.resolve()- // Advance past the 300ms setTimeout in the componentawait vi.advanceTimersByTimeAsync(350)})await waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()})vi.useRealTimers()@@ -687,14 +645,13 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)- // Wait for error modal with version infoawait waitFor(() => {expect(screen.getByText('1.0.0')).toBeInTheDocument()expect(screen.getByText('2.0.0')).toBeInTheDocument()@@ -717,20 +674,18 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)- // Wait for error modalawait waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })- // Find and click cancel button in error modal - it should be the one with secondary variant- const cancelButtons = screen.getAllByText('newApp.Cancel')+ const cancelButtons = screen.getAllByText('app.newApp.Cancel')const errorModalCancelButton = cancelButtons.find(btn =>btn.getAttribute('data-variant') === 'secondary',)@@ -738,9 +693,8 @@ describe('UpdateDSLModal', () => {fireEvent.click(errorModalCancelButton)}- // Modal should be closedawait waitFor(() => {- expect(screen.queryByText('newApp.appCreateDSLErrorTitle')).not.toBeInTheDocument()+ expect(screen.queryByText('app.newApp.appCreateDSLErrorTitle')).not.toBeInTheDocument()})})@@ -767,27 +721,23 @@ describe('UpdateDSLModal', () => {await act(async () => {fireEvent.change(fileInput, { target: { files: [file] } })- // Flush microtasks scheduled by the FileReader mock (which uses queueMicrotask)await new Promise<void>(resolve => queueMicrotask(resolve))})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()await act(async () => {fireEvent.click(importButton)- // Flush the promise resolution from mockImportDSLawait Promise.resolve()- // Advance past the 300ms setTimeout in the componentawait vi.advanceTimersByTimeAsync(350)})await waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })- // Click confirm button- const confirmButton = screen.getByText('newApp.Confirm')+ const confirmButton = screen.getByText('app.newApp.Confirm')fireEvent.click(confirmButton)await waitFor(() => {@@ -818,18 +768,18 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })- const confirmButton = screen.getByText('newApp.Confirm')+ const confirmButton = screen.getByText('app.newApp.Confirm')fireEvent.click(confirmButton)await waitFor(() => {@@ -860,18 +810,18 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })- const confirmButton = screen.getByText('newApp.Confirm')+ const confirmButton = screen.getByText('app.newApp.Confirm')fireEvent.click(confirmButton)await waitFor(() => {@@ -899,18 +849,18 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })- const confirmButton = screen.getByText('newApp.Confirm')+ const confirmButton = screen.getByText('app.newApp.Confirm')fireEvent.click(confirmButton)await waitFor(() => {@@ -941,18 +891,18 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })- const confirmButton = screen.getByText('newApp.Confirm')+ const confirmButton = screen.getByText('app.newApp.Confirm')fireEvent.click(confirmButton)await waitFor(() => {@@ -983,18 +933,18 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)await waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })- const confirmButton = screen.getByText('newApp.Confirm')+ const confirmButton = screen.getByText('app.newApp.Confirm')fireEvent.click(confirmButton)await waitFor(() => {@@ -1025,26 +975,23 @@ describe('UpdateDSLModal', () => {await act(async () => {fireEvent.change(fileInput, { target: { files: [file] } })- // Flush microtasks scheduled by the FileReader mock (which uses queueMicrotask)await new Promise<void>(resolve => queueMicrotask(resolve))})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()await act(async () => {fireEvent.click(importButton)- // Flush the promise resolution from mockImportDSLawait Promise.resolve()- // Advance past the 300ms setTimeout in the componentawait vi.advanceTimersByTimeAsync(350)})await waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })- const confirmButton = screen.getByText('newApp.Confirm')+ const confirmButton = screen.getByText('app.newApp.Confirm')fireEvent.click(confirmButton)await waitFor(() => {@@ -1070,25 +1017,21 @@ describe('UpdateDSLModal', () => {fireEvent.change(fileInput, { target: { files: [file] } })await waitFor(() => {- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).not.toBeDisabled()})- const importButton = screen.getByText('common.overwriteAndImport')+ const importButton = screen.getByText('workflow.common.overwriteAndImport')fireEvent.click(importButton)- // Should show error modal even with undefined versionsawait waitFor(() => {- expect(screen.getByText('newApp.appCreateDSLErrorTitle')).toBeInTheDocument()+ expect(screen.getByText('app.newApp.appCreateDSLErrorTitle')).toBeInTheDocument()}, { timeout: 1000 })})it('should not call importDSLConfirm when importId is not set', async () => {- // Render without triggering PENDING status firstrender(<UpdateDSLModal {...defaultProps} />)- // importId is not set, so confirm should not be called- // This is hard to test directly, but we can verify by checking the confirm flowexpect(mockImportDSLConfirm).not.toHaveBeenCalled()})})diff --git a/web/app/components/rag-pipeline/components/version-mismatch-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/version-mismatch-modal.spec.tsxsimilarity index 98%rename from web/app/components/rag-pipeline/components/version-mismatch-modal.spec.tsxrename to web/app/components/rag-pipeline/components/__tests__/version-mismatch-modal.spec.tsxindex b14cdcf9c1f..087f900f8a4 100644--- a/web/app/components/rag-pipeline/components/version-mismatch-modal.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/version-mismatch-modal.spec.tsx@@ -1,6 +1,6 @@import { fireEvent, render, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import VersionMismatchModal from './version-mismatch-modal'+import VersionMismatchModal from '../version-mismatch-modal'describe('VersionMismatchModal', () => {const mockOnClose = vi.fn()diff --git a/web/app/components/rag-pipeline/components/chunk-card-list/__tests__/chunk-card.spec.tsx b/web/app/components/rag-pipeline/components/chunk-card-list/__tests__/chunk-card.spec.tsxnew file mode 100644index 00000000000..59cd9613f34--- /dev/null+++ b/web/app/components/rag-pipeline/components/chunk-card-list/__tests__/chunk-card.spec.tsx@@ -0,0 +1,212 @@+import type { ParentChildChunk } from '../types'+import { render, screen } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { ChunkingMode } from '@/models/datasets'++import ChunkCard from '../chunk-card'++vi.mock('@/app/components/datasets/documents/detail/completed/common/dot', () => ({+ default: () => <span data-testid="dot" />,+}))++vi.mock('@/app/components/datasets/documents/detail/completed/common/segment-index-tag', () => ({+ default: ({ positionId, labelPrefix }: { positionId?: string | number, labelPrefix: string }) => (+ <span data-testid="segment-tag">+ {labelPrefix}+ -+ {positionId}+ </span>+ ),+}))++vi.mock('@/app/components/datasets/documents/detail/completed/common/summary-label', () => ({+ default: ({ summary }: { summary: string }) => <span data-testid="summary">{summary}</span>,+}))++vi.mock('@/app/components/datasets/formatted-text/flavours/preview-slice', () => ({+ PreviewSlice: ({ label, text }: { label: string, text: string }) => (+ <span data-testid="preview-slice">+ {label}+ :+ {' '}+ {text}+ </span>+ ),+}))++vi.mock('@/models/datasets', () => ({+ ChunkingMode: {+ text: 'text',+ parentChild: 'parent-child',+ qa: 'qa',+ },+}))++vi.mock('@/utils/format', () => ({+ formatNumber: (n: number) => String(n),+}))++vi.mock('../q-a-item', () => ({+ default: ({ type, text }: { type: string, text: string }) => (+ <span data-testid={`qa-${type}`}>{text}</span>+ ),+}))++vi.mock('../types', () => ({+ QAItemType: {+ Question: 'question',+ Answer: 'answer',+ },+}))++const makeParentChildContent = (overrides: Partial<ParentChildChunk> = {}): ParentChildChunk => ({+ child_contents: ['Child'],+ parent_content: '',+ parent_summary: '',+ parent_mode: 'paragraph',+ ...overrides,+})++describe('ChunkCard', () => {+ describe('Text mode', () => {+ it('should render text content', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.text}+ content={{ content: 'Hello world', summary: 'Summary text' }}+ positionId={1}+ wordCount={42}+ />,+ )++ expect(screen.getByText('Hello world')).toBeInTheDocument()+ })++ it('should render segment index tag with Chunk prefix', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.text}+ content={{ content: 'Test', summary: '' }}+ positionId={5}+ wordCount={10}+ />,+ )++ expect(screen.getByText('Chunk-5')).toBeInTheDocument()+ })++ it('should render word count', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.text}+ content={{ content: 'Test', summary: '' }}+ positionId={1}+ wordCount={100}+ />,+ )++ expect(screen.getByText(/100/)).toBeInTheDocument()+ })++ it('should render summary when available', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.text}+ content={{ content: 'Test', summary: 'A summary' }}+ positionId={1}+ wordCount={10}+ />,+ )++ expect(screen.getByTestId('summary')).toHaveTextContent('A summary')+ })+ })++ describe('Parent-Child mode (paragraph)', () => {+ it('should render child contents as preview slices', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.parentChild}+ parentMode="paragraph"+ content={makeParentChildContent({+ child_contents: ['Child 1', 'Child 2'],+ parent_summary: 'Parent summary',+ })}+ positionId={3}+ wordCount={50}+ />,+ )++ const slices = screen.getAllByTestId('preview-slice')+ expect(slices).toHaveLength(2)+ expect(slices[0]).toHaveTextContent('C-1: Child 1')+ expect(slices[1]).toHaveTextContent('C-2: Child 2')+ })++ it('should render Parent-Chunk prefix for paragraph mode', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.parentChild}+ parentMode="paragraph"+ content={makeParentChildContent()}+ positionId={2}+ wordCount={20}+ />,+ )++ expect(screen.getByText('Parent-Chunk-2')).toBeInTheDocument()+ })++ it('should render parent summary', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.parentChild}+ parentMode="paragraph"+ content={makeParentChildContent({+ child_contents: ['C1'],+ parent_summary: 'Overview',+ })}+ positionId={1}+ wordCount={10}+ />,+ )++ expect(screen.getByTestId('summary')).toHaveTextContent('Overview')+ })+ })++ describe('Parent-Child mode (full-doc)', () => {+ it('should hide segment tag in full-doc mode', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.parentChild}+ parentMode="full-doc"+ content={makeParentChildContent({+ child_contents: ['Full doc child'],+ parent_mode: 'full-doc',+ })}+ positionId={1}+ wordCount={300}+ />,+ )++ expect(screen.queryByTestId('segment-tag')).not.toBeInTheDocument()+ })+ })++ describe('QA mode', () => {+ it('should render question and answer items', () => {+ render(+ <ChunkCard+ chunkType={ChunkingMode.qa}+ content={{ question: 'What is X?', answer: 'X is Y' }}+ positionId={1}+ wordCount={15}+ />,+ )++ expect(screen.getByTestId('qa-question')).toHaveTextContent('What is X?')+ expect(screen.getByTestId('qa-answer')).toHaveTextContent('X is Y')+ })+ })+})diff --git a/web/app/components/rag-pipeline/components/chunk-card-list/index.spec.tsx b/web/app/components/rag-pipeline/components/chunk-card-list/__tests__/index.spec.tsxsimilarity index 83%rename from web/app/components/rag-pipeline/components/chunk-card-list/index.spec.tsxrename to web/app/components/rag-pipeline/components/chunk-card-list/__tests__/index.spec.tsxindex ca5fae25c72..2fab56f0eab 100644--- a/web/app/components/rag-pipeline/components/chunk-card-list/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/chunk-card-list/__tests__/index.spec.tsx@@ -1,14 +1,10 @@-import type { GeneralChunks, ParentChildChunk, ParentChildChunks, QAChunk, QAChunks } from './types'+import type { GeneralChunks, ParentChildChunk, ParentChildChunks, QAChunk, QAChunks } from '../types'import { render, screen } from '@testing-library/react'import { ChunkingMode } from '@/models/datasets'-import ChunkCard from './chunk-card'-import { ChunkCardList } from './index'-import QAItem from './q-a-item'-import { QAItemType } from './types'--// =============================================================================-// Test Data Factories-// =============================================================================+import ChunkCard from '../chunk-card'+import { ChunkCardList } from '../index'+import QAItem from '../q-a-item'+import { QAItemType } from '../types'const createGeneralChunks = (overrides: GeneralChunks = []): GeneralChunks => {if (overrides.length > 0)@@ -56,99 +52,71 @@ const createQAChunks = (overrides: Partial<QAChunks> = {}): QAChunks => ({...overrides,})-// =============================================================================-// QAItem Component Tests-// =============================================================================-describe('QAItem', () => {beforeEach(() => {vi.clearAllMocks()})- // Tests for basic rendering of QAItem componentdescribe('Rendering', () => {it('should render question type with Q prefix', () => {- // Arrange & Actrender(<QAItem type={QAItemType.Question} text="What is this?" />)- // Assertexpect(screen.getByText('Q')).toBeInTheDocument()expect(screen.getByText('What is this?')).toBeInTheDocument()})it('should render answer type with A prefix', () => {- // Arrange & Actrender(<QAItem type={QAItemType.Answer} text="This is the answer." />)- // Assertexpect(screen.getByText('A')).toBeInTheDocument()expect(screen.getByText('This is the answer.')).toBeInTheDocument()})})- // Tests for different prop variationsdescribe('Props', () => {it('should render with empty text', () => {- // Arrange & Actrender(<QAItem type={QAItemType.Question} text="" />)- // Assertexpect(screen.getByText('Q')).toBeInTheDocument()})it('should render with long text content', () => {- // Arrangeconst longText = 'A'.repeat(1000)- // Actrender(<QAItem type={QAItemType.Answer} text={longText} />)- // Assertexpect(screen.getByText(longText)).toBeInTheDocument()})it('should render with special characters in text', () => {- // Arrangeconst specialText = '<script>alert("xss")</script> & "quotes" \'apostrophe\''- // Actrender(<QAItem type={QAItemType.Question} text={specialText} />)- // Assertexpect(screen.getByText(specialText)).toBeInTheDocument()})})- // Tests for memoization behaviordescribe('Memoization', () => {it('should be memoized with React.memo', () => {- // Arrange & Actconst { rerender } = render(<QAItem type={QAItemType.Question} text="Test" />)- // Assert - component should render consistentlyexpect(screen.getByText('Q')).toBeInTheDocument()expect(screen.getByText('Test')).toBeInTheDocument()- // Rerender with same props - should not cause issuesrerender(<QAItem type={QAItemType.Question} text="Test" />)expect(screen.getByText('Q')).toBeInTheDocument()})})})-// =============================================================================-// ChunkCard Component Tests-// =============================================================================-describe('ChunkCard', () => {beforeEach(() => {vi.clearAllMocks()})- // Tests for basic rendering with different chunk typesdescribe('Rendering', () => {it('should render text chunk type correctly', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -158,19 +126,16 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText('This is the first chunk of text content.')).toBeInTheDocument()expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()})it('should render QA chunk type with question and answer', () => {- // Arrangeconst qaContent: QAChunk = {question: 'What is React?',answer: 'React is a JavaScript library.',}- // Actrender(<ChunkCardchunkType={ChunkingMode.qa}@@ -180,7 +145,6 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText('Q')).toBeInTheDocument()expect(screen.getByText('What is React?')).toBeInTheDocument()expect(screen.getByText('A')).toBeInTheDocument()@@ -188,10 +152,8 @@ describe('ChunkCard', () => {})it('should render parent-child chunk type with child contents', () => {- // Arrangeconst childContents = ['Child 1 content', 'Child 2 content']- // Actrender(<ChunkCardchunkType={ChunkingMode.parentChild}@@ -202,7 +164,6 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText('Child 1 content')).toBeInTheDocument()expect(screen.getByText('Child 2 content')).toBeInTheDocument()expect(screen.getByText('C-1')).toBeInTheDocument()@@ -210,10 +171,8 @@ describe('ChunkCard', () => {})})- // Tests for parent mode variationsdescribe('Parent Mode Variations', () => {it('should show Parent-Chunk label prefix for paragraph mode', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.parentChild}@@ -224,12 +183,10 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText(/Parent-Chunk-01/)).toBeInTheDocument()})it('should hide segment index tag for full-doc mode', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.parentChild}@@ -240,13 +197,11 @@ describe('ChunkCard', () => {/>,)- // Assert - should not show Chunk or Parent-Chunk labelexpect(screen.queryByText(/Chunk/)).not.toBeInTheDocument()expect(screen.queryByText(/Parent-Chunk/)).not.toBeInTheDocument()})it('should show Chunk label prefix for text mode', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -256,15 +211,12 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText(/Chunk-05/)).toBeInTheDocument()})})- // Tests for word count displaydescribe('Word Count Display', () => {it('should display formatted word count', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -274,12 +226,10 @@ describe('ChunkCard', () => {/>,)- // Assert - formatNumber(1234) returns '1,234'expect(screen.getByText(/1,234/)).toBeInTheDocument()})it('should display word count with character translation key', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -289,12 +239,10 @@ describe('ChunkCard', () => {/>,)- // Assert - translation key is returned as-is by mockexpect(screen.getByText(/100\s+(?:\S.*)?characters/)).toBeInTheDocument()})it('should not display word count info for full-doc mode', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.parentChild}@@ -305,15 +253,12 @@ describe('ChunkCard', () => {/>,)- // Assert - the header with word count should be hiddenexpect(screen.queryByText(/500/)).not.toBeInTheDocument()})})- // Tests for position ID variationsdescribe('Position ID', () => {it('should handle numeric position ID', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -323,12 +268,10 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText(/Chunk-42/)).toBeInTheDocument()})it('should handle string position ID', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -338,12 +281,10 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText(/Chunk-99/)).toBeInTheDocument()})it('should pad single digit position ID', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -353,15 +294,12 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText(/Chunk-03/)).toBeInTheDocument()})})- // Tests for memoization dependenciesdescribe('Memoization', () => {it('should update isFullDoc memo when parentMode changes', () => {- // Arrangeconst { rerender } = render(<ChunkCardchunkType={ChunkingMode.parentChild}@@ -372,10 +310,8 @@ describe('ChunkCard', () => {/>,)- // Assert - paragraph mode shows labelexpect(screen.getByText(/Parent-Chunk/)).toBeInTheDocument()- // Act - change to full-docrerender(<ChunkCardchunkType={ChunkingMode.parentChild}@@ -386,12 +322,10 @@ describe('ChunkCard', () => {/>,)- // Assert - full-doc mode hides labelexpect(screen.queryByText(/Parent-Chunk/)).not.toBeInTheDocument()})it('should update contentElement memo when content changes', () => {- // Arrangeconst initialContent = { content: 'Initial content' }const updatedContent = { content: 'Updated content' }@@ -404,10 +338,8 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText('Initial content')).toBeInTheDocument()- // Actrerender(<ChunkCardchunkType={ChunkingMode.text}@@ -417,13 +349,11 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText('Updated content')).toBeInTheDocument()expect(screen.queryByText('Initial content')).not.toBeInTheDocument()})it('should update contentElement memo when chunkType changes', () => {- // Arrangeconst textContent = { content: 'Text content' }const { rerender } = render(<ChunkCard@@ -434,10 +364,8 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText('Text content')).toBeInTheDocument()- // Act - change to QA typeconst qaContent: QAChunk = { question: 'Q?', answer: 'A.' }rerender(<ChunkCard@@ -448,16 +376,13 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText('Q')).toBeInTheDocument()expect(screen.getByText('Q?')).toBeInTheDocument()})})- // Tests for edge casesdescribe('Edge Cases', () => {it('should handle empty child contents array', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.parentChild}@@ -468,15 +393,12 @@ describe('ChunkCard', () => {/>,)- // Assert - should render without errorsexpect(screen.getByText(/Parent-Chunk-01/)).toBeInTheDocument()})it('should handle QA chunk with empty strings', () => {- // Arrangeconst emptyQA: QAChunk = { question: '', answer: '' }- // Actrender(<ChunkCardchunkType={ChunkingMode.qa}@@ -486,17 +408,14 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText('Q')).toBeInTheDocument()expect(screen.getByText('A')).toBeInTheDocument()})it('should handle very long content', () => {- // Arrangeconst longContent = 'A'.repeat(10000)const longContentChunk = { content: longContent }- // Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -506,12 +425,10 @@ describe('ChunkCard', () => {/>,)- // Assertexpect(screen.getByText(longContent)).toBeInTheDocument()})it('should handle zero word count', () => {- // Arrange & Actrender(<ChunkCardchunkType={ChunkingMode.text}@@ -521,28 +438,20 @@ describe('ChunkCard', () => {/>,)- // Assert - formatNumber returns falsy for 0, so it shows 0expect(screen.getByText(/0\s+(?:\S.*)?characters/)).toBeInTheDocument()})})})-// =============================================================================-// ChunkCardList Component Tests-// =============================================================================-describe('ChunkCardList', () => {beforeEach(() => {vi.clearAllMocks()})- // Tests for rendering with different chunk typesdescribe('Rendering', () => {it('should render text chunks correctly', () => {- // Arrangeconst chunks = createGeneralChunks()- // Actrender(<ChunkCardListchunkType={ChunkingMode.text}@@ -550,17 +459,14 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(screen.getByText(chunks[0].content)).toBeInTheDocument()expect(screen.getByText(chunks[1].content)).toBeInTheDocument()expect(screen.getByText(chunks[2].content)).toBeInTheDocument()})it('should render parent-child chunks correctly', () => {- // Arrangeconst chunks = createParentChildChunks()- // Actrender(<ChunkCardListchunkType={ChunkingMode.parentChild}@@ -569,17 +475,14 @@ describe('ChunkCardList', () => {/>,)- // Assert - should render child contents from parent-child chunksexpect(screen.getByText('Child content 1')).toBeInTheDocument()expect(screen.getByText('Child content 2')).toBeInTheDocument()expect(screen.getByText('Another child 1')).toBeInTheDocument()})it('should render QA chunks correctly', () => {- // Arrangeconst chunks = createQAChunks()- // Actrender(<ChunkCardListchunkType={ChunkingMode.qa}@@ -587,7 +490,6 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(screen.getByText('What is the answer to life?')).toBeInTheDocument()expect(screen.getByText('The answer is 42.')).toBeInTheDocument()expect(screen.getByText('How does this work?')).toBeInTheDocument()@@ -595,16 +497,13 @@ describe('ChunkCardList', () => {})})- // Tests for chunkList memoizationdescribe('Memoization - chunkList', () => {it('should extract chunks from GeneralChunks for text mode', () => {- // Arrangeconst chunks: GeneralChunks = [{ content: 'Chunk 1' },{ content: 'Chunk 2' },]- // Actrender(<ChunkCardListchunkType={ChunkingMode.text}@@ -612,20 +511,17 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(screen.getByText('Chunk 1')).toBeInTheDocument()expect(screen.getByText('Chunk 2')).toBeInTheDocument()})it('should extract parent_child_chunks from ParentChildChunks for parentChild mode', () => {- // Arrangeconst chunks = createParentChildChunks({parent_child_chunks: [createParentChildChunk({ child_contents: ['Specific child'] }),],})- // Actrender(<ChunkCardListchunkType={ChunkingMode.parentChild}@@ -634,19 +530,16 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(screen.getByText('Specific child')).toBeInTheDocument()})it('should extract qa_chunks from QAChunks for qa mode', () => {- // Arrangeconst chunks: QAChunks = {qa_chunks: [{ question: 'Specific Q', answer: 'Specific A' },],}- // Actrender(<ChunkCardListchunkType={ChunkingMode.qa}@@ -654,13 +547,11 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(screen.getByText('Specific Q')).toBeInTheDocument()expect(screen.getByText('Specific A')).toBeInTheDocument()})it('should update chunkList when chunkInfo changes', () => {- // Arrangeconst initialChunks = createGeneralChunks([{ content: 'Initial chunk' }])const { rerender } = render(@@ -670,10 +561,8 @@ describe('ChunkCardList', () => {/>,)- // Assert initial stateexpect(screen.getByText('Initial chunk')).toBeInTheDocument()- // Act - update chunksconst updatedChunks = createGeneralChunks([{ content: 'Updated chunk' }])rerender(<ChunkCardList@@ -682,19 +571,15 @@ describe('ChunkCardList', () => {/>,)- // Assert updated stateexpect(screen.getByText('Updated chunk')).toBeInTheDocument()expect(screen.queryByText('Initial chunk')).not.toBeInTheDocument()})})- // Tests for getWordCount functiondescribe('Word Count Calculation', () => {it('should calculate word count for text chunks using string length', () => {- // Arrange - "Hello" has 5 charactersconst chunks = createGeneralChunks([{ content: 'Hello' }])- // Actrender(<ChunkCardListchunkType={ChunkingMode.text}@@ -702,12 +587,10 @@ describe('ChunkCardList', () => {/>,)- // Assert - word count should be 5 (string length)expect(screen.getByText(/5\s+(?:\S.*)?characters/)).toBeInTheDocument()})it('should calculate word count for parent-child chunks using parent_content length', () => {- // Arrange - parent_content length determines word countconst chunks = createParentChildChunks({parent_child_chunks: [createParentChildChunk({@@ -717,7 +600,6 @@ describe('ChunkCardList', () => {],})- // Actrender(<ChunkCardListchunkType={ChunkingMode.parentChild}@@ -726,19 +608,16 @@ describe('ChunkCardList', () => {/>,)- // Assert - word count should be 6 (parent_content length)expect(screen.getByText(/6\s+(?:\S.*)?characters/)).toBeInTheDocument()})it('should calculate word count for QA chunks using question + answer length', () => {- // Arrange - "Hi" (2) + "Bye" (3) = 5const chunks: QAChunks = {qa_chunks: [{ question: 'Hi', answer: 'Bye' },],}- // Actrender(<ChunkCardListchunkType={ChunkingMode.qa}@@ -746,22 +625,18 @@ describe('ChunkCardList', () => {/>,)- // Assert - word count should be 5 (question.length + answer.length)expect(screen.getByText(/5\s+(?:\S.*)?characters/)).toBeInTheDocument()})})- // Tests for position ID assignmentdescribe('Position ID', () => {it('should assign 1-based position IDs to chunks', () => {- // Arrangeconst chunks = createGeneralChunks([{ content: 'First' },{ content: 'Second' },{ content: 'Third' },])- // Actrender(<ChunkCardListchunkType={ChunkingMode.text}@@ -769,20 +644,16 @@ describe('ChunkCardList', () => {/>,)- // Assert - position IDs should be 1, 2, 3expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()expect(screen.getByText(/Chunk-02/)).toBeInTheDocument()expect(screen.getByText(/Chunk-03/)).toBeInTheDocument()})})- // Tests for className propdescribe('Custom className', () => {it('should apply custom className to container', () => {- // Arrangeconst chunks = createGeneralChunks([{ content: 'Test' }])- // Actconst { container } = render(<ChunkCardListchunkType={ChunkingMode.text}@@ -791,15 +662,12 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(container.firstChild).toHaveClass('custom-class')})it('should merge custom className with default classes', () => {- // Arrangeconst chunks = createGeneralChunks([{ content: 'Test' }])- // Actconst { container } = render(<ChunkCardListchunkType={ChunkingMode.text}@@ -808,7 +676,6 @@ describe('ChunkCardList', () => {/>,)- // Assert - should have both default and custom classesexpect(container.firstChild).toHaveClass('flex')expect(container.firstChild).toHaveClass('w-full')expect(container.firstChild).toHaveClass('flex-col')@@ -816,10 +683,8 @@ describe('ChunkCardList', () => {})it('should render without className prop', () => {- // Arrangeconst chunks = createGeneralChunks([{ content: 'Test' }])- // Actconst { container } = render(<ChunkCardListchunkType={ChunkingMode.text}@@ -827,19 +692,15 @@ describe('ChunkCardList', () => {/>,)- // Assert - should have default classesexpect(container.firstChild).toHaveClass('flex')expect(container.firstChild).toHaveClass('w-full')})})- // Tests for parentMode propdescribe('Parent Mode', () => {it('should pass parentMode to ChunkCard for parent-child type', () => {- // Arrangeconst chunks = createParentChildChunks()- // Actrender(<ChunkCardListchunkType={ChunkingMode.parentChild}@@ -848,15 +709,12 @@ describe('ChunkCardList', () => {/>,)- // Assert - paragraph mode shows Parent-Chunk labelexpect(screen.getAllByText(/Parent-Chunk/).length).toBeGreaterThan(0)})it('should handle full-doc parentMode', () => {- // Arrangeconst chunks = createParentChildChunks()- // Actrender(<ChunkCardListchunkType={ChunkingMode.parentChild}@@ -865,16 +723,13 @@ describe('ChunkCardList', () => {/>,)- // Assert - full-doc mode hides chunk labelsexpect(screen.queryByText(/Parent-Chunk/)).not.toBeInTheDocument()expect(screen.queryByText(/Chunk-/)).not.toBeInTheDocument()})it('should not use parentMode for text type', () => {- // Arrangeconst chunks = createGeneralChunks([{ content: 'Text' }])- // Actrender(<ChunkCardListchunkType={ChunkingMode.text}@@ -883,18 +738,14 @@ describe('ChunkCardList', () => {/>,)- // Assert - should show Chunk label, not affected by parentModeexpect(screen.getByText(/Chunk-01/)).toBeInTheDocument()})})- // Tests for edge casesdescribe('Edge Cases', () => {it('should handle empty GeneralChunks array', () => {- // Arrangeconst chunks: GeneralChunks = []- // Actconst { container } = render(<ChunkCardListchunkType={ChunkingMode.text}@@ -902,19 +753,16 @@ describe('ChunkCardList', () => {/>,)- // Assert - should render empty containerexpect(container.firstChild).toBeInTheDocument()expect(container.firstChild?.childNodes.length).toBe(0)})it('should handle empty ParentChildChunks', () => {- // Arrangeconst chunks: ParentChildChunks = {parent_child_chunks: [],parent_mode: 'paragraph',}- // Actconst { container } = render(<ChunkCardListchunkType={ChunkingMode.parentChild}@@ -923,18 +771,15 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(container.firstChild).toBeInTheDocument()expect(container.firstChild?.childNodes.length).toBe(0)})it('should handle empty QAChunks', () => {- // Arrangeconst chunks: QAChunks = {qa_chunks: [],}- // Actconst { container } = render(<ChunkCardListchunkType={ChunkingMode.qa}@@ -942,16 +787,13 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(container.firstChild).toBeInTheDocument()expect(container.firstChild?.childNodes.length).toBe(0)})it('should handle single item in chunks', () => {- // Arrangeconst chunks = createGeneralChunks([{ content: 'Single chunk' }])- // Actrender(<ChunkCardListchunkType={ChunkingMode.text}@@ -959,16 +801,13 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(screen.getByText('Single chunk')).toBeInTheDocument()expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()})it('should handle large number of chunks', () => {- // Arrangeconst chunks = Array.from({ length: 100 }, (_, i) => ({ content: `Chunk number ${i + 1}` }))- // Actrender(<ChunkCardListchunkType={ChunkingMode.text}@@ -976,23 +815,19 @@ describe('ChunkCardList', () => {/>,)- // Assertexpect(screen.getByText('Chunk number 1')).toBeInTheDocument()expect(screen.getByText('Chunk number 100')).toBeInTheDocument()expect(screen.getByText(/Chunk-100/)).toBeInTheDocument()})})- // Tests for key uniquenessdescribe('Key Generation', () => {it('should generate unique keys for chunks', () => {- // Arrange - chunks with same contentconst chunks = createGeneralChunks([{ content: 'Same content' },{ content: 'Same content' },{ content: 'Same content' },])- // Actconst { container } = render(<ChunkCardListchunkType={ChunkingMode.text}@@ -1000,33 +835,25 @@ describe('ChunkCardList', () => {/>,)- // Assert - all three should render (keys are based on chunkType-index)const chunkCards = container.querySelectorAll('.bg-components-panel-bg')expect(chunkCards.length).toBe(3)})})})-// =============================================================================-// Integration Tests-// =============================================================================-describe('ChunkCardList Integration', () => {beforeEach(() => {vi.clearAllMocks()})- // Tests for complete workflow scenariosdescribe('Complete Workflows', () => {it('should render complete text chunking workflow', () => {- // Arrangeconst textChunks = createGeneralChunks([{ content: 'First paragraph of the document.' },{ content: 'Second paragraph with more information.' },{ content: 'Final paragraph concluding the content.' },])- // Actrender(<ChunkCardListchunkType={ChunkingMode.text}@@ -1034,10 +861,8 @@ describe('ChunkCardList Integration', () => {/>,)- // Assertexpect(screen.getByText('First paragraph of the document.')).toBeInTheDocument()expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()- // "First paragraph of the document." = 32 charactersexpect(screen.getByText(/32\s+(?:\S.*)?characters/)).toBeInTheDocument()expect(screen.getByText('Second paragraph with more information.')).toBeInTheDocument()@@ -1048,7 +873,6 @@ describe('ChunkCardList Integration', () => {})it('should render complete parent-child chunking workflow', () => {- // Arrangeconst parentChildChunks = createParentChildChunks({parent_child_chunks: [{@@ -1062,7 +886,6 @@ describe('ChunkCardList Integration', () => {],})- // Actrender(<ChunkCardListchunkType={ChunkingMode.parentChild}@@ -1071,7 +894,6 @@ describe('ChunkCardList Integration', () => {/>,)- // Assertexpect(screen.getByText('React components are building blocks.')).toBeInTheDocument()expect(screen.getByText('Lifecycle methods control component behavior.')).toBeInTheDocument()expect(screen.getByText('C-1')).toBeInTheDocument()@@ -1080,7 +902,6 @@ describe('ChunkCardList Integration', () => {})it('should render complete QA chunking workflow', () => {- // Arrangeconst qaChunks = createQAChunks({qa_chunks: [{@@ -1094,7 +915,6 @@ describe('ChunkCardList Integration', () => {],})- // Actrender(<ChunkCardListchunkType={ChunkingMode.qa}@@ -1102,7 +922,6 @@ describe('ChunkCardList Integration', () => {/>,)- // Assertconst qLabels = screen.getAllByText('Q')const aLabels = screen.getAllByText('A')expect(qLabels.length).toBe(2)@@ -1115,10 +934,8 @@ describe('ChunkCardList Integration', () => {})})- // Tests for type switching scenariosdescribe('Type Switching', () => {it('should handle switching from text to QA type', () => {- // Arrangeconst textChunks = createGeneralChunks([{ content: 'Text content' }])const qaChunks = createQAChunks()@@ -1129,10 +946,8 @@ describe('ChunkCardList Integration', () => {/>,)- // Assert initial text stateexpect(screen.getByText('Text content')).toBeInTheDocument()- // Act - switch to QArerender(<ChunkCardListchunkType={ChunkingMode.qa}@@ -1140,13 +955,11 @@ describe('ChunkCardList Integration', () => {/>,)- // Assert QA stateexpect(screen.queryByText('Text content')).not.toBeInTheDocument()expect(screen.getByText('What is the answer to life?')).toBeInTheDocument()})it('should handle switching from text to parent-child type', () => {- // Arrangeconst textChunks = createGeneralChunks([{ content: 'Simple text' }])const parentChildChunks = createParentChildChunks()@@ -1157,11 +970,9 @@ describe('ChunkCardList Integration', () => {/>,)- // Assert initial stateexpect(screen.getByText('Simple text')).toBeInTheDocument()expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()- // Act - switch to parent-childrerender(<ChunkCardListchunkType={ChunkingMode.parentChild}@@ -1170,9 +981,7 @@ describe('ChunkCardList Integration', () => {/>,)- // Assert parent-child stateexpect(screen.queryByText('Simple text')).not.toBeInTheDocument()- // Multiple Parent-Chunk elements exist, so use getAllByTextexpect(screen.getAllByText(/Parent-Chunk/).length).toBeGreaterThan(0)})})diff --git a/web/app/components/rag-pipeline/components/panel/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsxsimilarity index 76%rename from web/app/components/rag-pipeline/components/panel/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsxindex 11f9f8b2c4c..f651b16697a 100644--- a/web/app/components/rag-pipeline/components/panel/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx@@ -1,13 +1,8 @@import type { PanelProps } from '@/app/components/workflow/panel'import { render, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import RagPipelinePanel from './index'+import RagPipelinePanel from '../index'-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock reactflow to avoid zustand provider errorvi.mock('reactflow', () => ({useNodes: () => [],useStoreApi: () => ({@@ -26,20 +21,12 @@ vi.mock('reactflow', () => ({},}))-// Use vi.hoisted to create variables that can be used in vi.mockconst { dynamicMocks, mockInputFieldEditorProps } = vi.hoisted(() => {let counter = 0const mockInputFieldEditorProps = vi.fn()const createMockComponent = () => {const index = counter++- // Order matches the imports in index.tsx:- // 0: Record- // 1: TestRunPanel- // 2: InputFieldPanel- // 3: InputFieldEditorPanel- // 4: PreviewPanel- // 5: GlobalVariablePanelswitch (index) {case 0:return () => <div data-testid="record-panel">Record Panel</div>@@ -69,14 +56,12 @@ const { dynamicMocks, mockInputFieldEditorProps } = vi.hoisted(() => {return { dynamicMocks: { createMockComponent }, mockInputFieldEditorProps }})-// Mock next/dynamicvi.mock('next/dynamic', () => ({default: (_loader: () => Promise<{ default: React.ComponentType }>, _options?: Record<string, unknown>) => {return dynamicMocks.createMockComponent()},}))-// Mock workflow storelet mockHistoryWorkflowData: Record<string, unknown> | null = nulllet mockShowDebugAndPreviewPanel = falselet mockShowGlobalVariablePanel = false@@ -138,7 +123,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock Panel component to capture props and render childrenlet capturedPanelProps: PanelProps | null = nullvi.mock('@/app/components/workflow/panel', () => ({default: (props: PanelProps) => {@@ -152,10 +136,6 @@ vi.mock('@/app/components/workflow/panel', () => ({},}))-// ============================================================================-// Helper Functions-// ============================================================================-type SetupMockOptions = {historyWorkflowData?: Record<string, unknown> | nullshowDebugAndPreviewPanel?: boolean@@ -177,35 +157,24 @@ const setupMocks = (options?: SetupMockOptions) => {capturedPanelProps = null}-// ============================================================================-// RagPipelinePanel Component Tests-// ============================================================================-describe('RagPipelinePanel', () => {beforeEach(() => {vi.clearAllMocks()setupMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', async () => {- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('workflow-panel')).toBeInTheDocument()})})it('should render Panel component with correct structure', async () => {- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('panel-left')).toBeInTheDocument()expect(screen.getByTestId('panel-right')).toBeInTheDocument()@@ -213,13 +182,10 @@ describe('RagPipelinePanel', () => {})it('should pass versionHistoryPanelProps to Panel', async () => {- // ArrangesetupMocks({ pipelineId: 'my-pipeline-456' })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.versionHistoryPanelProps).toBeDefined()expect(capturedPanelProps?.versionHistoryPanelProps?.getVersionListUrl).toBe(@@ -229,18 +195,12 @@ describe('RagPipelinePanel', () => {})})- // -------------------------------------------------------------------------- // Memoization Tests - versionHistoryPanelProps- // -------------------------------------------------------------------------describe('Memoization - versionHistoryPanelProps', () => {it('should compute correct getVersionListUrl based on pipelineId', async () => {- // ArrangesetupMocks({ pipelineId: 'pipeline-abc' })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.versionHistoryPanelProps?.getVersionListUrl).toBe('/rag/pipelines/pipeline-abc/workflows',@@ -249,13 +209,10 @@ describe('RagPipelinePanel', () => {})it('should compute correct deleteVersionUrl function', async () => {- // ArrangesetupMocks({ pipelineId: 'pipeline-xyz' })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {const deleteUrl = capturedPanelProps?.versionHistoryPanelProps?.deleteVersionUrl?.('version-1')expect(deleteUrl).toBe('/rag/pipelines/pipeline-xyz/workflows/version-1')@@ -263,13 +220,10 @@ describe('RagPipelinePanel', () => {})it('should compute correct updateVersionUrl function', async () => {- // ArrangesetupMocks({ pipelineId: 'pipeline-def' })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {const updateUrl = capturedPanelProps?.versionHistoryPanelProps?.updateVersionUrl?.('version-2')expect(updateUrl).toBe('/rag/pipelines/pipeline-def/workflows/version-2')@@ -277,63 +231,46 @@ describe('RagPipelinePanel', () => {})it('should set latestVersionId to empty string', async () => {- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.versionHistoryPanelProps?.latestVersionId).toBe('')})})})- // -------------------------------------------------------------------------- // Memoization Tests - panelProps- // -------------------------------------------------------------------------describe('Memoization - panelProps', () => {it('should pass components.left to Panel', async () => {- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.components?.left).toBeDefined()})})it('should pass components.right to Panel', async () => {- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.components?.right).toBeDefined()})})it('should pass versionHistoryPanelProps to panelProps', async () => {- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.versionHistoryPanelProps).toBeDefined()})})})- // -------------------------------------------------------------------------- // Component Memoization Tests (React.memo)- // -------------------------------------------------------------------------describe('Component Memoization', () => {it('should be wrapped with React.memo', async () => {- // The component should not break when re-renderedconst { rerender } = render(<RagPipelinePanel />)- // Act - rerender without prop changesrerender(<RagPipelinePanel />)- // Assert - component should still render correctlyawait waitFor(() => {expect(screen.getByTestId('workflow-panel')).toBeInTheDocument()})@@ -341,138 +278,98 @@ describe('RagPipelinePanel', () => {})})-// ============================================================================-// RagPipelinePanelOnRight Component Tests-// ============================================================================-describe('RagPipelinePanelOnRight', () => {beforeEach(() => {vi.clearAllMocks()setupMocks()})- // -------------------------------------------------------------------------- // Conditional Rendering - Record Panel- // -------------------------------------------------------------------------describe('Record Panel Conditional Rendering', () => {it('should render Record panel when historyWorkflowData exists', async () => {- // ArrangesetupMocks({ historyWorkflowData: { id: 'history-1' } })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('record-panel')).toBeInTheDocument()})})it('should not render Record panel when historyWorkflowData is null', async () => {- // ArrangesetupMocks({ historyWorkflowData: null })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('record-panel')).not.toBeInTheDocument()})})it('should not render Record panel when historyWorkflowData is undefined', async () => {- // ArrangesetupMocks({ historyWorkflowData: undefined })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('record-panel')).not.toBeInTheDocument()})})})- // -------------------------------------------------------------------------- // Conditional Rendering - TestRun Panel- // -------------------------------------------------------------------------describe('TestRun Panel Conditional Rendering', () => {it('should render TestRun panel when showDebugAndPreviewPanel is true', async () => {- // ArrangesetupMocks({ showDebugAndPreviewPanel: true })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('test-run-panel')).toBeInTheDocument()})})it('should not render TestRun panel when showDebugAndPreviewPanel is false', async () => {- // ArrangesetupMocks({ showDebugAndPreviewPanel: false })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('test-run-panel')).not.toBeInTheDocument()})})})- // -------------------------------------------------------------------------- // Conditional Rendering - GlobalVariable Panel- // -------------------------------------------------------------------------describe('GlobalVariable Panel Conditional Rendering', () => {it('should render GlobalVariable panel when showGlobalVariablePanel is true', async () => {- // ArrangesetupMocks({ showGlobalVariablePanel: true })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('global-variable-panel')).toBeInTheDocument()})})it('should not render GlobalVariable panel when showGlobalVariablePanel is false', async () => {- // ArrangesetupMocks({ showGlobalVariablePanel: false })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('global-variable-panel')).not.toBeInTheDocument()})})})- // -------------------------------------------------------------------------- // Multiple Panels Rendering- // -------------------------------------------------------------------------describe('Multiple Panels Rendering', () => {it('should render all right panels when all conditions are true', async () => {- // ArrangesetupMocks({historyWorkflowData: { id: 'history-1' },showDebugAndPreviewPanel: true,showGlobalVariablePanel: true,})- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('record-panel')).toBeInTheDocument()expect(screen.getByTestId('test-run-panel')).toBeInTheDocument()@@ -481,17 +378,14 @@ describe('RagPipelinePanelOnRight', () => {})it('should render no right panels when all conditions are false', async () => {- // ArrangesetupMocks({historyWorkflowData: null,showDebugAndPreviewPanel: false,showGlobalVariablePanel: false,})- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('record-panel')).not.toBeInTheDocument()expect(screen.queryByTestId('test-run-panel')).not.toBeInTheDocument()@@ -500,17 +394,14 @@ describe('RagPipelinePanelOnRight', () => {})it('should render only Record and TestRun panels', async () => {- // ArrangesetupMocks({historyWorkflowData: { id: 'history-1' },showDebugAndPreviewPanel: true,showGlobalVariablePanel: false,})- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('record-panel')).toBeInTheDocument()expect(screen.getByTestId('test-run-panel')).toBeInTheDocument()@@ -520,53 +411,36 @@ describe('RagPipelinePanelOnRight', () => {})})-// ============================================================================-// RagPipelinePanelOnLeft Component Tests-// ============================================================================-describe('RagPipelinePanelOnLeft', () => {beforeEach(() => {vi.clearAllMocks()setupMocks()})- // -------------------------------------------------------------------------- // Conditional Rendering - Preview Panel- // -------------------------------------------------------------------------describe('Preview Panel Conditional Rendering', () => {it('should render Preview panel when showInputFieldPreviewPanel is true', async () => {- // ArrangesetupMocks({ showInputFieldPreviewPanel: true })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('preview-panel')).toBeInTheDocument()})})it('should not render Preview panel when showInputFieldPreviewPanel is false', async () => {- // ArrangesetupMocks({ showInputFieldPreviewPanel: false })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('preview-panel')).not.toBeInTheDocument()})})})- // -------------------------------------------------------------------------- // Conditional Rendering - InputFieldEditor Panel- // -------------------------------------------------------------------------describe('InputFieldEditor Panel Conditional Rendering', () => {it('should render InputFieldEditor panel when inputFieldEditPanelProps is provided', async () => {- // Arrangeconst editProps = {onClose: vi.fn(),onSubmit: vi.fn(),@@ -574,30 +448,24 @@ describe('RagPipelinePanelOnLeft', () => {}setupMocks({ inputFieldEditPanelProps: editProps })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('input-field-editor-panel')).toBeInTheDocument()})})it('should not render InputFieldEditor panel when inputFieldEditPanelProps is null', async () => {- // ArrangesetupMocks({ inputFieldEditPanelProps: null })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('input-field-editor-panel')).not.toBeInTheDocument()})})it('should pass props to InputFieldEditor panel', async () => {- // Arrangeconst editProps = {onClose: vi.fn(),onSubmit: vi.fn(),@@ -605,10 +473,8 @@ describe('RagPipelinePanelOnLeft', () => {}setupMocks({ inputFieldEditPanelProps: editProps })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(mockInputFieldEditorProps).toHaveBeenCalledWith(expect.objectContaining({@@ -621,53 +487,38 @@ describe('RagPipelinePanelOnLeft', () => {})})- // -------------------------------------------------------------------------- // Conditional Rendering - InputField Panel- // -------------------------------------------------------------------------describe('InputField Panel Conditional Rendering', () => {it('should render InputField panel when showInputFieldPanel is true', async () => {- // ArrangesetupMocks({ showInputFieldPanel: true })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('input-field-panel')).toBeInTheDocument()})})it('should not render InputField panel when showInputFieldPanel is false', async () => {- // ArrangesetupMocks({ showInputFieldPanel: false })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('input-field-panel')).not.toBeInTheDocument()})})})- // -------------------------------------------------------------------------- // Multiple Panels Rendering- // -------------------------------------------------------------------------describe('Multiple Left Panels Rendering', () => {it('should render all left panels when all conditions are true', async () => {- // ArrangesetupMocks({showInputFieldPreviewPanel: true,inputFieldEditPanelProps: { onClose: vi.fn(), onSubmit: vi.fn() },showInputFieldPanel: true,})- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('preview-panel')).toBeInTheDocument()expect(screen.getByTestId('input-field-editor-panel')).toBeInTheDocument()@@ -676,17 +527,14 @@ describe('RagPipelinePanelOnLeft', () => {})it('should render no left panels when all conditions are false', async () => {- // ArrangesetupMocks({showInputFieldPreviewPanel: false,inputFieldEditPanelProps: null,showInputFieldPanel: false,})- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.queryByTestId('preview-panel')).not.toBeInTheDocument()expect(screen.queryByTestId('input-field-editor-panel')).not.toBeInTheDocument()@@ -695,17 +543,14 @@ describe('RagPipelinePanelOnLeft', () => {})it('should render only Preview and InputField panels', async () => {- // ArrangesetupMocks({showInputFieldPreviewPanel: true,inputFieldEditPanelProps: null,showInputFieldPanel: true,})- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(screen.getByTestId('preview-panel')).toBeInTheDocument()expect(screen.queryByTestId('input-field-editor-panel')).not.toBeInTheDocument()@@ -715,28 +560,18 @@ describe('RagPipelinePanelOnLeft', () => {})})-// ============================================================================-// Edge Cases Tests-// ============================================================================-describe('Edge Cases', () => {beforeEach(() => {vi.clearAllMocks()setupMocks()})- // -------------------------------------------------------------------------- // Empty/Undefined Values- // -------------------------------------------------------------------------describe('Empty/Undefined Values', () => {it('should handle empty pipelineId gracefully', async () => {- // ArrangesetupMocks({ pipelineId: '' })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.versionHistoryPanelProps?.getVersionListUrl).toBe('/rag/pipelines//workflows',@@ -745,13 +580,10 @@ describe('Edge Cases', () => {})it('should handle special characters in pipelineId', async () => {- // ArrangesetupMocks({ pipelineId: 'pipeline-with-special_chars.123' })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.versionHistoryPanelProps?.getVersionListUrl).toBe('/rag/pipelines/pipeline-with-special_chars.123/workflows',@@ -760,12 +592,8 @@ describe('Edge Cases', () => {})})- // -------------------------------------------------------------------------- // Props Spreading Tests- // -------------------------------------------------------------------------describe('Props Spreading', () => {it('should correctly spread inputFieldEditPanelProps to editor component', async () => {- // Arrangeconst customProps = {onClose: vi.fn(),onSubmit: vi.fn(),@@ -778,10 +606,8 @@ describe('Edge Cases', () => {}setupMocks({ inputFieldEditPanelProps: customProps })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(mockInputFieldEditorProps).toHaveBeenCalledWith(expect.objectContaining({@@ -792,12 +618,8 @@ describe('Edge Cases', () => {})})- // -------------------------------------------------------------------------- // State Combinations- // -------------------------------------------------------------------------describe('State Combinations', () => {it('should handle all panels visible simultaneously', async () => {- // ArrangesetupMocks({historyWorkflowData: { id: 'h1' },showDebugAndPreviewPanel: true,@@ -807,10 +629,8 @@ describe('Edge Cases', () => {showInputFieldPanel: true,})- // Actrender(<RagPipelinePanel />)- // Assert - All panels should be visibleawait waitFor(() => {expect(screen.getByTestId('record-panel')).toBeInTheDocument()expect(screen.getByTestId('test-run-panel')).toBeInTheDocument()@@ -823,10 +643,6 @@ describe('Edge Cases', () => {})})-// ============================================================================-// URL Generator Functions Tests-// ============================================================================-describe('URL Generator Functions', () => {beforeEach(() => {vi.clearAllMocks()@@ -834,13 +650,10 @@ describe('URL Generator Functions', () => {})it('should return consistent URLs for same versionId', async () => {- // ArrangesetupMocks({ pipelineId: 'stable-pipeline' })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {const deleteUrl1 = capturedPanelProps?.versionHistoryPanelProps?.deleteVersionUrl?.('version-x')const deleteUrl2 = capturedPanelProps?.versionHistoryPanelProps?.deleteVersionUrl?.('version-x')@@ -849,13 +662,10 @@ describe('URL Generator Functions', () => {})it('should return different URLs for different versionIds', async () => {- // ArrangesetupMocks({ pipelineId: 'stable-pipeline' })- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {const deleteUrl1 = capturedPanelProps?.versionHistoryPanelProps?.deleteVersionUrl?.('version-1')const deleteUrl2 = capturedPanelProps?.versionHistoryPanelProps?.deleteVersionUrl?.('version-2')@@ -866,10 +676,6 @@ describe('URL Generator Functions', () => {})})-// ============================================================================-// Type Safety Tests-// ============================================================================-describe('Type Safety', () => {beforeEach(() => {vi.clearAllMocks()@@ -877,10 +683,8 @@ describe('Type Safety', () => {})it('should pass correct PanelProps structure', async () => {- // Actrender(<RagPipelinePanel />)- // Assert - Check structure matches PanelPropsawait waitFor(() => {expect(capturedPanelProps).toHaveProperty('components')expect(capturedPanelProps).toHaveProperty('versionHistoryPanelProps')@@ -890,10 +694,8 @@ describe('Type Safety', () => {})it('should pass correct versionHistoryPanelProps structure', async () => {- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.versionHistoryPanelProps).toHaveProperty('getVersionListUrl')expect(capturedPanelProps?.versionHistoryPanelProps).toHaveProperty('deleteVersionUrl')@@ -903,10 +705,6 @@ describe('Type Safety', () => {})})-// ============================================================================-// Performance Tests-// ============================================================================-describe('Performance', () => {beforeEach(() => {vi.clearAllMocks()@@ -914,24 +712,17 @@ describe('Performance', () => {})it('should handle multiple rerenders without issues', async () => {- // Arrangeconst { rerender } = render(<RagPipelinePanel />)- // Act - Multiple rerendersfor (let i = 0; i < 10; i++)rerender(<RagPipelinePanel />)- // Assert - Component should still workawait waitFor(() => {expect(screen.getByTestId('workflow-panel')).toBeInTheDocument()})})})-// ============================================================================-// Integration Tests-// ============================================================================-describe('Integration Tests', () => {beforeEach(() => {vi.clearAllMocks()@@ -939,28 +730,23 @@ describe('Integration Tests', () => {})it('should pass correct components to Panel', async () => {- // ArrangesetupMocks({historyWorkflowData: { id: 'h1' },showInputFieldPanel: true,})- // Actrender(<RagPipelinePanel />)- // Assertawait waitFor(() => {expect(capturedPanelProps?.components?.left).toBeDefined()expect(capturedPanelProps?.components?.right).toBeDefined()- // Check that the components are React elementsexpect(React.isValidElement(capturedPanelProps?.components?.left)).toBe(true)expect(React.isValidElement(capturedPanelProps?.components?.right)).toBe(true)})})it('should correctly consume all store selectors', async () => {- // ArrangesetupMocks({historyWorkflowData: { id: 'test-history' },showDebugAndPreviewPanel: true,@@ -971,10 +757,8 @@ describe('Integration Tests', () => {pipelineId: 'integration-test-pipeline',})- // Actrender(<RagPipelinePanel />)- // Assert - All store-dependent rendering should workawait waitFor(() => {expect(screen.getByTestId('record-panel')).toBeInTheDocument()expect(screen.getByTestId('test-run-panel')).toBeInTheDocument()diff --git a/web/app/components/rag-pipeline/components/panel/input-field/footer-tip.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/footer-tip.spec.tsxsimilarity index 94%rename from web/app/components/rag-pipeline/components/panel/input-field/footer-tip.spec.tsxrename to web/app/components/rag-pipeline/components/panel/input-field/__tests__/footer-tip.spec.tsxindex 5d5cde97351..f70b9a4a6f9 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/footer-tip.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/footer-tip.spec.tsx@@ -1,6 +1,6 @@import { cleanup, render, screen } from '@testing-library/react'import { afterEach, describe, expect, it, vi } from 'vitest'-import FooterTip from './footer-tip'+import FooterTip from '../footer-tip'afterEach(() => {cleanup()@@ -45,7 +45,6 @@ describe('FooterTip', () => {it('should render the drag icon', () => {const { container } = render(<FooterTip />)- // The RiDragDropLine icon should be renderedconst icon = container.querySelector('.size-4')expect(icon).toBeInTheDocument()})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/hooks.spec.ts b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/hooks.spec.tssimilarity index 87%rename from web/app/components/rag-pipeline/components/panel/input-field/hooks.spec.tsrename to web/app/components/rag-pipeline/components/panel/input-field/__tests__/hooks.spec.tsindex 452963ba7f5..9f7fb7e9020 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/hooks.spec.ts+++ b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/hooks.spec.ts@@ -1,8 +1,7 @@import { renderHook } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { useFloatingRight } from './hooks'+import { useFloatingRight } from '../hooks'-// Mock reactflowconst mockGetNodes = vi.fn()vi.mock('reactflow', () => ({useStore: (selector: (s: { getNodes: () => { id: string, data: { selected: boolean } }[] }) => unknown) => {@@ -10,12 +9,10 @@ vi.mock('reactflow', () => ({},}))-// Mock zustand/react/shallowvi.mock('zustand/react/shallow', () => ({useShallow: (fn: (...args: unknown[]) => unknown) => fn,}))-// Mock workflow storelet mockNodePanelWidth = 400let mockWorkflowCanvasWidth: number | undefined = 1200let mockOtherPanelWidth = 0@@ -67,8 +64,6 @@ describe('useFloatingRight', () => {const { result } = renderHook(() => useFloatingRight(400))- // leftWidth = 1000 - 0 (no selected node) - 0 - 400 - 4 = 596- // 596 >= 404 so floatingRight should be falseexpect(result.current.floatingRight).toBe(false)})})@@ -80,8 +75,6 @@ describe('useFloatingRight', () => {const { result } = renderHook(() => useFloatingRight(400))- // leftWidth = 1200 - 400 (node panel) - 0 - 400 - 4 = 396- // 396 < 404 so floatingRight should be trueexpect(result.current.floatingRight).toBe(true)})})@@ -103,7 +96,6 @@ describe('useFloatingRight', () => {const { result } = renderHook(() => useFloatingRight(600))- // When floating and no selected node, width = min(600, 0 + 200) = 200expect(result.current.floatingRightWidth).toBeLessThanOrEqual(600)})@@ -115,7 +107,6 @@ describe('useFloatingRight', () => {const { result } = renderHook(() => useFloatingRight(600))- // When floating with selected node, width = min(600, 300 + 100) = 400expect(result.current.floatingRightWidth).toBeLessThanOrEqual(600)})})@@ -127,7 +118,6 @@ describe('useFloatingRight', () => {const { result } = renderHook(() => useFloatingRight(400))- // Should not throw and should maintain initial stateexpect(result.current.floatingRight).toBe(false)})@@ -145,7 +135,6 @@ describe('useFloatingRight', () => {const { result } = renderHook(() => useFloatingRight(10000))- // Should be floating due to limited spaceexpect(result.current.floatingRight).toBe(true)})@@ -159,7 +148,6 @@ describe('useFloatingRight', () => {const { result } = renderHook(() => useFloatingRight(400))- // Should have selected node so node panel is consideredexpect(result.current).toBeDefined()})})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/index.spec.tsxsimilarity index 78%rename from web/app/components/rag-pipeline/components/panel/input-field/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/input-field/__tests__/index.spec.tsxindex 0ff7a06dae7..ab99a1eeefe 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/__tests__/index.spec.tsx@@ -5,19 +5,13 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { BlockEnum } from '@/app/components/workflow/types'import { PipelineInputVarType } from '@/models/pipeline'-import InputFieldPanel from './index'+import InputFieldPanel from '../index'-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock reactflow hooks - use getter to allow dynamic updateslet mockNodesData: Node<DataSourceNodeType>[] = []vi.mock('reactflow', () => ({useNodes: () => mockNodesData,}))-// Mock useInputFieldPanel hookconst mockCloseAllInputFieldPanels = vi.fn()const mockToggleInputFieldPreviewPanel = vi.fn()let mockIsPreviewing = false@@ -32,7 +26,6 @@ vi.mock('@/app/components/rag-pipeline/hooks', () => ({}),}))-// Mock useStore (workflow store)let mockRagPipelineVariables: RAGPipelineVariables = []const mockSetRagPipelineVariables = vi.fn()@@ -56,7 +49,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock useNodesSyncDraft hookconst mockHandleSyncWorkflowDraft = vi.fn()vi.mock('@/app/components/workflow/hooks', () => ({@@ -65,8 +57,7 @@ vi.mock('@/app/components/workflow/hooks', () => ({}),}))-// Mock FieldList component-vi.mock('./field-list', () => ({+vi.mock('../field-list', () => ({default: ({nodeId,LabelRightContent,@@ -124,13 +115,11 @@ vi.mock('./field-list', () => ({),}))-// Mock FooterTip component-vi.mock('./footer-tip', () => ({+vi.mock('../footer-tip', () => ({default: () => <div data-testid="footer-tip">Footer Tip</div>,}))-// Mock Datasource label component-vi.mock('./label-right-content/datasource', () => ({+vi.mock('../label-right-content/datasource', () => ({default: ({ nodeData }: { nodeData: DataSourceNodeType }) => (<div data-testid={`datasource-label-${nodeData.title}`}>{nodeData.title}@@ -138,15 +127,10 @@ vi.mock('./label-right-content/datasource', () => ({),}))-// Mock GlobalInputs label component-vi.mock('./label-right-content/global-inputs', () => ({+vi.mock('../label-right-content/global-inputs', () => ({default: () => <div data-testid="global-inputs-label">Global Inputs</div>,}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createInputVar = (overrides?: Partial<InputVar>): InputVar => ({type: PipelineInputVarType.textInput,label: 'Test Label',@@ -189,10 +173,6 @@ const createDataSourceNode = (} as DataSourceNodeType,})-// ============================================================================-// Helper Functions-// ============================================================================-const setupMocks = (options?: {nodes?: Node<DataSourceNodeType>[]ragPipelineVariables?: RAGPipelineVariables@@ -205,148 +185,110 @@ const setupMocks = (options?: {mockIsEditing = options?.isEditing || false}-// ============================================================================-// InputFieldPanel Component Tests-// ============================================================================-describe('InputFieldPanel', () => {beforeEach(() => {vi.clearAllMocks()setupMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render panel without crashing', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.title'),).toBeInTheDocument()})it('should render panel title correctly', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.title'),).toBeInTheDocument()})it('should render panel description', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.description'),).toBeInTheDocument()})it('should render preview button', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByText('datasetPipeline.operations.preview'),).toBeInTheDocument()})it('should render close button', () => {- // Actrender(<InputFieldPanel />)- // Assertconst closeButton = screen.getByRole('button', { name: '' })expect(closeButton).toBeInTheDocument()})it('should render footer tip component', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('footer-tip')).toBeInTheDocument()})it('should render unique inputs section title', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.uniqueInputs.title'),).toBeInTheDocument()})it('should render global inputs field list', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-shared')).toBeInTheDocument()expect(screen.getByTestId('global-inputs-label')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // DataSource Node Rendering Tests- // -------------------------------------------------------------------------describe('DataSource Node Rendering', () => {it('should render field list for each datasource node', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1'),createDataSourceNode('node-2', 'DataSource 2'),]setupMocks({ nodes })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-node-1')).toBeInTheDocument()expect(screen.getByTestId('field-list-node-2')).toBeInTheDocument()})it('should render datasource label for each node', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'My DataSource')]setupMocks({ nodes })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('datasource-label-My DataSource'),).toBeInTheDocument()})it('should not render any datasource field lists when no nodes exist', () => {- // ArrangesetupMocks({ nodes: [] })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.queryByTestId('field-list-node-1')).not.toBeInTheDocument()- // Global inputs should still renderexpect(screen.getByTestId('field-list-shared')).toBeInTheDocument()})it('should filter only DataSource type nodes', () => {- // Arrangeconst dataSourceNode = createDataSourceNode('ds-node', 'DataSource Node')- // Create a non-datasource node to verify filteringconst otherNode = {id: 'other-node',type: 'custom',@@ -359,10 +301,8 @@ describe('InputFieldPanel', () => {} as Node<DataSourceNodeType>mockNodesData = [dataSourceNode, otherNode]- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-ds-node')).toBeInTheDocument()expect(screen.queryByTestId('field-list-other-node'),@@ -370,12 +310,8 @@ describe('InputFieldPanel', () => {})})- // -------------------------------------------------------------------------- // Input Fields Map Tests- // -------------------------------------------------------------------------describe('Input Fields Map', () => {it('should correctly distribute variables to their nodes', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]const variables = [createRAGPipelineVariable('node-1', { variable: 'var1' }),@@ -384,28 +320,22 @@ describe('InputFieldPanel', () => {]setupMocks({ nodes, ragPipelineVariables: variables })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-fields-count-node-1')).toHaveTextContent('2')expect(screen.getByTestId('field-list-fields-count-shared')).toHaveTextContent('1')})it('should show zero fields for nodes without variables', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]setupMocks({ nodes, ragPipelineVariables: [] })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-fields-count-node-1')).toHaveTextContent('0')})it('should pass all variable names to field lists', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]const variables = [createRAGPipelineVariable('node-1', { variable: 'var1' }),@@ -413,10 +343,8 @@ describe('InputFieldPanel', () => {]setupMocks({ nodes, ragPipelineVariables: variables })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-all-vars-node-1')).toHaveTextContent('var1,var2',)@@ -426,48 +354,35 @@ describe('InputFieldPanel', () => {})})- // -------------------------------------------------------------------------- // User Interactions Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {- // Helper to identify close button by its classconst isCloseButton = (btn: HTMLElement) =>btn.classList.contains('size-6')|| btn.className.includes('shrink-0 items-center justify-center p-0.5')it('should call closeAllInputFieldPanels when close button is clicked', () => {- // Arrangerender(<InputFieldPanel />)const buttons = screen.getAllByRole('button')const closeButton = buttons.find(isCloseButton)- // ActfireEvent.click(closeButton!)- // Assertexpect(mockCloseAllInputFieldPanels).toHaveBeenCalledTimes(1)})it('should call toggleInputFieldPreviewPanel when preview button is clicked', () => {- // Arrangerender(<InputFieldPanel />)const previewButton = screen.getByText('datasetPipeline.operations.preview')- // ActfireEvent.click(previewButton)- // Assertexpect(mockToggleInputFieldPreviewPanel).toHaveBeenCalledTimes(1)})it('should disable preview button when editing', () => {- // ArrangesetupMocks({ isEditing: true })- // Actrender(<InputFieldPanel />)- // Assertconst previewButton = screen.getByText('datasetPipeline.operations.preview').closest('button')@@ -475,13 +390,10 @@ describe('InputFieldPanel', () => {})it('should not disable preview button when not editing', () => {- // ArrangesetupMocks({ isEditing: false })- // Actrender(<InputFieldPanel />)- // Assertconst previewButton = screen.getByText('datasetPipeline.operations.preview').closest('button')@@ -489,18 +401,12 @@ describe('InputFieldPanel', () => {})})- // -------------------------------------------------------------------------- // Preview State Tests- // -------------------------------------------------------------------------describe('Preview State', () => {it('should apply active styling when previewing', () => {- // ArrangesetupMocks({ isPreviewing: true })- // Actrender(<InputFieldPanel />)- // Assertconst previewButton = screen.getByText('datasetPipeline.operations.preview').closest('button')@@ -509,81 +415,62 @@ describe('InputFieldPanel', () => {})it('should set readonly to true when previewing', () => {- // ArrangesetupMocks({ isPreviewing: true })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-readonly-shared')).toHaveTextContent('true',)})it('should set readonly to true when editing', () => {- // ArrangesetupMocks({ isEditing: true })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-readonly-shared')).toHaveTextContent('true',)})it('should set readonly to false when not previewing or editing', () => {- // ArrangesetupMocks({ isPreviewing: false, isEditing: false })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-readonly-shared')).toHaveTextContent('false',)})})- // -------------------------------------------------------------------------- // Input Fields Change Handler Tests- // -------------------------------------------------------------------------describe('Input Fields Change Handler', () => {it('should update rag pipeline variables when input fields change', async () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]setupMocks({ nodes })render(<InputFieldPanel />)- // ActfireEvent.click(screen.getByTestId('trigger-change-node-1'))- // Assertawait waitFor(() => {expect(mockSetRagPipelineVariables).toHaveBeenCalled()})})it('should call handleSyncWorkflowDraft when fields change', async () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]setupMocks({ nodes })render(<InputFieldPanel />)- // ActfireEvent.click(screen.getByTestId('trigger-change-node-1'))- // Assertawait waitFor(() => {expect(mockHandleSyncWorkflowDraft).toHaveBeenCalled()})})it('should place datasource node fields before global fields', async () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]const variables = [createRAGPipelineVariable('shared', { variable: 'shared_var' }),@@ -591,15 +478,12 @@ describe('InputFieldPanel', () => {setupMocks({ nodes, ragPipelineVariables: variables })render(<InputFieldPanel />)- // ActfireEvent.click(screen.getByTestId('trigger-change-node-1'))- // Assertawait waitFor(() => {expect(mockSetRagPipelineVariables).toHaveBeenCalled()})- // Verify datasource fields come before shared fieldsconst setVarsCall = mockSetRagPipelineVariables.mock.calls[0][0] as RAGPipelineVariablesconst isNotShared = (v: RAGPipelineVariable) => v.belong_to_node_id !== 'shared'const isShared = (v: RAGPipelineVariable) => v.belong_to_node_id === 'shared'@@ -614,7 +498,6 @@ describe('InputFieldPanel', () => {})it('should handle removing all fields from a node', async () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]const variables = [createRAGPipelineVariable('node-1', { variable: 'var1' }),@@ -623,24 +506,19 @@ describe('InputFieldPanel', () => {setupMocks({ nodes, ragPipelineVariables: variables })render(<InputFieldPanel />)- // ActfireEvent.click(screen.getByTestId('trigger-remove-node-1'))- // Assertawait waitFor(() => {expect(mockSetRagPipelineVariables).toHaveBeenCalled()})})it('should update global input fields correctly', async () => {- // ArrangesetupMocks()render(<InputFieldPanel />)- // ActfireEvent.click(screen.getByTestId('trigger-change-shared'))- // Assertawait waitFor(() => {expect(mockSetRagPipelineVariables).toHaveBeenCalled()})@@ -652,54 +530,39 @@ describe('InputFieldPanel', () => {})})- // -------------------------------------------------------------------------- // Label Class Name Tests- // -------------------------------------------------------------------------describe('Label Class Names', () => {it('should pass correct className to datasource field lists', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]setupMocks({ nodes })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-classname-node-1'),).toHaveTextContent('pt-1 pb-1')})it('should pass correct className to global inputs field list', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-classname-shared')).toHaveTextContent('pt-2 pb-1',)})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should memoize datasourceNodeDataMap based on nodes', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]setupMocks({ nodes })const { rerender } = render(<InputFieldPanel />)- // Act - rerender with same nodes referencererender(<InputFieldPanel />)- // Assert - component should not break and should render correctlyexpect(screen.getByTestId('field-list-node-1')).toBeInTheDocument()})it('should compute allVariableNames correctly', () => {- // Arrangeconst variables = [createRAGPipelineVariable('node-1', { variable: 'alpha' }),createRAGPipelineVariable('node-1', { variable: 'beta' }),@@ -707,21 +570,15 @@ describe('InputFieldPanel', () => {]setupMocks({ ragPipelineVariables: variables })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-all-vars-shared')).toHaveTextContent('alpha,beta,gamma',)})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {- // Helper to find close button - moved outside test to reduce nestingconst findCloseButton = (buttons: HTMLElement[]) => {const isCloseButton = (btn: HTMLElement) =>btn.classList.contains('size-6')@@ -730,10 +587,8 @@ describe('InputFieldPanel', () => {}it('should maintain closePanel callback reference', () => {- // Arrangeconst { rerender } = render(<InputFieldPanel />)- // Actconst buttons1 = screen.getAllByRole('button')fireEvent.click(findCloseButton(buttons1)!)const callCount1 = mockCloseAllInputFieldPanels.mock.calls.length@@ -742,126 +597,97 @@ describe('InputFieldPanel', () => {const buttons2 = screen.getAllByRole('button')fireEvent.click(findCloseButton(buttons2)!)- // Assertexpect(mockCloseAllInputFieldPanels.mock.calls.length).toBe(callCount1 + 1)})it('should maintain togglePreviewPanel callback reference', () => {- // Arrangeconst { rerender } = render(<InputFieldPanel />)- // ActfireEvent.click(screen.getByText('datasetPipeline.operations.preview'))const callCount1 = mockToggleInputFieldPreviewPanel.mock.calls.lengthrerender(<InputFieldPanel />)fireEvent.click(screen.getByText('datasetPipeline.operations.preview'))- // Assertexpect(mockToggleInputFieldPreviewPanel.mock.calls.length).toBe(callCount1 + 1,)})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle empty ragPipelineVariables', () => {- // ArrangesetupMocks({ ragPipelineVariables: [] })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-all-vars-shared')).toHaveTextContent('',)})it('should handle undefined ragPipelineVariables', () => {- // Arrange - intentionally testing undefined case// @ts-expect-error Testing edge case with undefined valuemockRagPipelineVariables = undefined- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-shared')).toBeInTheDocument()})it('should handle null variable names in allVariableNames', () => {- // Arrange - intentionally testing edge case with empty variable nameconst variables = [createRAGPipelineVariable('node-1', { variable: 'valid_var' }),createRAGPipelineVariable('node-1', { variable: '' }),]setupMocks({ ragPipelineVariables: variables })- // Actrender(<InputFieldPanel />)- // Assert - should not crashexpect(screen.getByTestId('field-list-shared')).toBeInTheDocument()})it('should handle large number of datasource nodes', () => {- // Arrangeconst nodes = Array.from({ length: 10 }, (_, i) =>createDataSourceNode(`node-${i}`, `DataSource ${i}`))setupMocks({ nodes })- // Actrender(<InputFieldPanel />)- // Assertnodes.forEach((_, i) => {expect(screen.getByTestId(`field-list-node-${i}`)).toBeInTheDocument()})})it('should handle large number of variables', () => {- // Arrangeconst variables = Array.from({ length: 100 }, (_, i) =>createRAGPipelineVariable('shared', { variable: `var_${i}` }))setupMocks({ ragPipelineVariables: variables })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-fields-count-shared')).toHaveTextContent('100',)})it('should handle special characters in variable names', () => {- // Arrangeconst variables = [createRAGPipelineVariable('shared', { variable: 'var_with_underscore' }),createRAGPipelineVariable('shared', { variable: 'varWithCamelCase' }),]setupMocks({ ragPipelineVariables: variables })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-all-vars-shared')).toHaveTextContent('var_with_underscore,varWithCamelCase',)})})- // -------------------------------------------------------------------------- // Multiple Nodes Interaction Tests- // -------------------------------------------------------------------------describe('Multiple Nodes Interaction', () => {it('should handle changes to multiple nodes sequentially', async () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1'),createDataSourceNode('node-2', 'DataSource 2'),@@ -869,18 +695,15 @@ describe('InputFieldPanel', () => {setupMocks({ nodes })render(<InputFieldPanel />)- // ActfireEvent.click(screen.getByTestId('trigger-change-node-1'))fireEvent.click(screen.getByTestId('trigger-change-node-2'))- // Assertawait waitFor(() => {expect(mockSetRagPipelineVariables).toHaveBeenCalledTimes(2)})})it('should maintain separate field lists for different nodes', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1'),createDataSourceNode('node-2', 'DataSource 2'),@@ -892,42 +715,31 @@ describe('InputFieldPanel', () => {]setupMocks({ nodes, ragPipelineVariables: variables })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-fields-count-node-1')).toHaveTextContent('1')expect(screen.getByTestId('field-list-fields-count-node-2')).toHaveTextContent('2')})})- // -------------------------------------------------------------------------- // Component Structure Tests- // -------------------------------------------------------------------------describe('Component Structure', () => {it('should have correct panel width class', () => {- // Actconst { container } = render(<InputFieldPanel />)- // Assertconst panel = container.firstChild as HTMLElementexpect(panel).toHaveClass('w-[400px]')})it('should have overflow scroll on content area', () => {- // Actconst { container } = render(<InputFieldPanel />)- // Assertconst scrollContainer = container.querySelector('.overflow-y-auto')expect(scrollContainer).toBeInTheDocument()})it('should render header section with proper spacing', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.title'),).toBeInTheDocument()@@ -937,12 +749,8 @@ describe('InputFieldPanel', () => {})})- // -------------------------------------------------------------------------- // Integration with FieldList Component Tests- // -------------------------------------------------------------------------describe('Integration with FieldList Component', () => {it('should pass correct props to FieldList for datasource nodes', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]const variables = [createRAGPipelineVariable('node-1', { variable: 'test_var' }),@@ -953,38 +761,29 @@ describe('InputFieldPanel', () => {isPreviewing: true,})- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-node-1')).toBeInTheDocument()expect(screen.getByTestId('field-list-readonly-node-1')).toHaveTextContent('true')expect(screen.getByTestId('field-list-fields-count-node-1')).toHaveTextContent('1')})it('should pass correct props to FieldList for shared node', () => {- // Arrangeconst variables = [createRAGPipelineVariable('shared', { variable: 'shared_var' }),]setupMocks({ ragPipelineVariables: variables, isEditing: true })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-shared')).toBeInTheDocument()expect(screen.getByTestId('field-list-readonly-shared')).toHaveTextContent('true')expect(screen.getByTestId('field-list-fields-count-shared')).toHaveTextContent('1')})})- // -------------------------------------------------------------------------- // Variable Ordering Tests- // -------------------------------------------------------------------------describe('Variable Ordering', () => {it('should maintain correct variable order in allVariableNames', () => {- // Arrangeconst variables = [createRAGPipelineVariable('node-1', { variable: 'first' }),createRAGPipelineVariable('node-1', { variable: 'second' }),@@ -992,10 +791,8 @@ describe('InputFieldPanel', () => {]setupMocks({ ragPipelineVariables: variables })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('field-list-all-vars-shared')).toHaveTextContent('first,second,third',)@@ -1003,13 +800,8 @@ describe('InputFieldPanel', () => {})})-// ============================================================================-// useFloatingRight Hook Integration Tests (via InputFieldPanel)-// ============================================================================-describe('useFloatingRight Hook Integration', () => {// Note: The hook is tested indirectly through the InputFieldPanel component- // as it's used internally. Direct hook tests are in hooks.spec.tsx if exists.beforeEach(() => {vi.clearAllMocks()@@ -1017,16 +809,11 @@ describe('useFloatingRight Hook Integration', () => {})it('should render panel correctly with default floating state', () => {- // The hook is mocked via the component's behaviorrender(<InputFieldPanel />)expect(screen.getByTestId('field-list-shared')).toBeInTheDocument()})})-// ============================================================================-// FooterTip Component Integration Tests-// ============================================================================-describe('FooterTip Integration', () => {beforeEach(() => {vi.clearAllMocks()@@ -1034,18 +821,12 @@ describe('FooterTip Integration', () => {})it('should render footer tip at the bottom of the panel', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('footer-tip')).toBeInTheDocument()})})-// ============================================================================-// Label Components Integration Tests-// ============================================================================-describe('Label Components Integration', () => {beforeEach(() => {vi.clearAllMocks()@@ -1053,25 +834,20 @@ describe('Label Components Integration', () => {})it('should render GlobalInputs label for shared field list', () => {- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('global-inputs-label')).toBeInTheDocument()})it('should render Datasource label for each datasource node', () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'First DataSource'),createDataSourceNode('node-2', 'Second DataSource'),]setupMocks({ nodes })- // Actrender(<InputFieldPanel />)- // Assertexpect(screen.getByTestId('datasource-label-First DataSource'),).toBeInTheDocument()@@ -1081,10 +857,6 @@ describe('Label Components Integration', () => {})})-// ============================================================================-// Component Memo Tests-// ============================================================================-describe('Component Memo Behavior', () => {beforeEach(() => {vi.clearAllMocks()@@ -1092,14 +864,10 @@ describe('Component Memo Behavior', () => {})it('should be wrapped with React.memo', () => {- // InputFieldPanel is exported as memo(InputFieldPanel)- // This test ensures the component doesn't break memoizationconst { rerender } = render(<InputFieldPanel />)- // Act - rerender without prop changesrerender(<InputFieldPanel />)- // Assert - component should still render correctlyexpect(screen.getByTestId('field-list-shared')).toBeInTheDocument()expect(screen.getByText('datasetPipeline.inputFieldPanel.title'),@@ -1107,15 +875,12 @@ describe('Component Memo Behavior', () => {})it('should handle state updates correctly with memo', async () => {- // Arrangeconst nodes = [createDataSourceNode('node-1', 'DataSource 1')]setupMocks({ nodes })render(<InputFieldPanel />)- // Act - trigger a state changefireEvent.click(screen.getByTestId('trigger-change-node-1'))- // Assertawait waitFor(() => {expect(mockSetRagPipelineVariables).toHaveBeenCalled()})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/editor/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/editor/__tests__/index.spec.tsxsimilarity index 82%rename from web/app/components/rag-pipeline/components/panel/input-field/editor/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/input-field/editor/__tests__/index.spec.tsxindex 4e7f4f504d9..d8feea44c63 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/editor/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/editor/__tests__/index.spec.tsx@@ -1,5 +1,5 @@-import type { FormData } from './form/types'-import type { InputFieldEditorProps } from './index'+import type { FormData } from '../form/types'+import type { InputFieldEditorProps } from '../index'import type { SupportUploadFileTypes } from '@/app/components/workflow/types'import type { InputVar } from '@/models/pipeline'import type { TransferMethod } from '@/types/app'@@ -7,28 +7,22 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen } from '@testing-library/react'import * as React from 'react'import { PipelineInputVarType } from '@/models/pipeline'-import InputFieldEditorPanel from './index'+import InputFieldEditorPanel from '../index'import {convertFormDataToINputField,convertToInputFieldFormData,-} from './utils'+} from '../utils'-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock useFloatingRight hookconst mockUseFloatingRight = vi.fn(() => ({floatingRight: false,floatingRightWidth: 400,}))-vi.mock('../hooks', () => ({+vi.mock('../../hooks', () => ({useFloatingRight: () => mockUseFloatingRight(),}))-// Mock InputFieldForm component-vi.mock('./form', () => ({+vi.mock('../form', () => ({default: ({initialData,supportFile,@@ -57,7 +51,6 @@ vi.mock('./form', () => ({),}))-// Mock file upload config servicevi.mock('@/service/use-common', () => ({useFileUploadConfig: () => ({data: {@@ -72,10 +65,6 @@ vi.mock('@/service/use-common', () => ({}),}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createInputVar = (overrides?: Partial<InputVar>): InputVar => ({type: PipelineInputVarType.textInput,label: 'Test Label',@@ -120,10 +109,6 @@ const createInputFieldEditorProps = (...overrides,})-// ============================================================================-// Test Wrapper Component-// ============================================================================-const createTestQueryClient = () =>new QueryClient({defaultOptions: {@@ -145,10 +130,6 @@ const renderWithProviders = (ui: React.ReactElement) => {return render(ui, { wrapper: TestWrapper })}-// ============================================================================-// InputFieldEditorPanel Component Tests-// ============================================================================-describe('InputFieldEditorPanel', () => {beforeEach(() => {vi.clearAllMocks()@@ -158,103 +139,75 @@ describe('InputFieldEditorPanel', () => {})})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render panel without crashing', () => {- // Arrangeconst props = createInputFieldEditorProps()- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByTestId('input-field-form')).toBeInTheDocument()})it('should render close button', () => {- // Arrangeconst props = createInputFieldEditorProps()- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertconst closeButton = screen.getByRole('button', { name: '' })expect(closeButton).toBeInTheDocument()})it('should render "Add Input Field" title when no initialData', () => {- // Arrangeconst props = createInputFieldEditorProps({ initialData: undefined })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.addInputField'),).toBeInTheDocument()})it('should render "Edit Input Field" title when initialData is provided', () => {- // Arrangeconst props = createInputFieldEditorProps({initialData: createInputVar(),})- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.editInputField'),).toBeInTheDocument()})it('should pass supportFile=true to form', () => {- // Arrangeconst props = createInputFieldEditorProps()- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByTestId('form-support-file').textContent).toBe('true')})it('should pass isEditMode=false when no initialData', () => {- // Arrangeconst props = createInputFieldEditorProps({ initialData: undefined })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByTestId('form-is-edit-mode').textContent).toBe('false')})it('should pass isEditMode=true when initialData is provided', () => {- // Arrangeconst props = createInputFieldEditorProps({initialData: createInputVar(),})- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByTestId('form-is-edit-mode').textContent).toBe('true')})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should handle different input types in initialData', () => {- // Arrangeconst typesToTest = [PipelineInputVarType.textInput,PipelineInputVarType.paragraph,@@ -269,19 +222,16 @@ describe('InputFieldEditorPanel', () => {const initialData = createInputVar({ type })const props = createInputFieldEditorProps({ initialData })- // Actconst { unmount } = renderWithProviders(<InputFieldEditorPanel {...props} />,)- // Assertexpect(screen.getByTestId('input-field-form')).toBeInTheDocument()unmount()})})it('should handle initialData with all optional fields populated', () => {- // Arrangeconst initialData = createInputVar({default_value: 'default',tooltips: 'tooltip text',@@ -294,15 +244,12 @@ describe('InputFieldEditorPanel', () => {})const props = createInputFieldEditorProps({ initialData })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByTestId('input-field-form')).toBeInTheDocument()})it('should handle initialData with minimal fields', () => {- // Arrangeconst initialData: InputVar = {type: PipelineInputVarType.textInput,label: 'Min',@@ -311,54 +258,40 @@ describe('InputFieldEditorPanel', () => {}const props = createInputFieldEditorProps({ initialData })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByTestId('input-field-form')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onClose when close button is clicked', () => {- // Arrangeconst onClose = vi.fn()const props = createInputFieldEditorProps({ onClose })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)fireEvent.click(screen.getByTestId('input-field-editor-close-btn'))- // Assertexpect(onClose).toHaveBeenCalledTimes(1)})it('should call onClose when form cancel is triggered', () => {- // Arrangeconst onClose = vi.fn()const props = createInputFieldEditorProps({ onClose })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)fireEvent.click(screen.getByTestId('form-cancel-btn'))- // Assertexpect(onClose).toHaveBeenCalledTimes(1)})it('should call onSubmit with converted data when form submits', () => {- // Arrangeconst onSubmit = vi.fn()const props = createInputFieldEditorProps({ onSubmit })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)fireEvent.click(screen.getByTestId('form-submit-btn'))- // Assertexpect(onSubmit).toHaveBeenCalledTimes(1)expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({@@ -370,35 +303,26 @@ describe('InputFieldEditorPanel', () => {})})- // -------------------------------------------------------------------------- // Floating Right Behavior Tests- // -------------------------------------------------------------------------describe('Floating Right Behavior', () => {it('should call useFloatingRight hook', () => {- // Arrangeconst props = createInputFieldEditorProps()- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(mockUseFloatingRight).toHaveBeenCalled()})it('should apply floating right styles when floatingRight is true', () => {- // ArrangemockUseFloatingRight.mockReturnValue({floatingRight: true,floatingRightWidth: 300,})const props = createInputFieldEditorProps()- // Actconst { container } = renderWithProviders(<InputFieldEditorPanel {...props} />,)- // Assertconst panel = container.firstChild as HTMLElementexpect(panel.className).toContain('absolute')expect(panel.className).toContain('right-0')@@ -406,35 +330,27 @@ describe('InputFieldEditorPanel', () => {})it('should not apply floating right styles when floatingRight is false', () => {- // ArrangemockUseFloatingRight.mockReturnValue({floatingRight: false,floatingRightWidth: 400,})const props = createInputFieldEditorProps()- // Actconst { container } = renderWithProviders(<InputFieldEditorPanel {...props} />,)- // Assertconst panel = container.firstChild as HTMLElementexpect(panel.className).not.toContain('absolute')expect(panel.style.width).toBe('400px')})})- // -------------------------------------------------------------------------- // Callback Stability and Memoization Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain stable onClose callback reference', () => {- // Arrangeconst onClose = vi.fn()const props = createInputFieldEditorProps({ onClose })- // Actconst { rerender } = renderWithProviders(<InputFieldEditorPanel {...props} />,)@@ -447,16 +363,13 @@ describe('InputFieldEditorPanel', () => {)fireEvent.click(screen.getByTestId('form-cancel-btn'))- // Assertexpect(onClose).toHaveBeenCalledTimes(2)})it('should maintain stable onSubmit callback reference', () => {- // Arrangeconst onSubmit = vi.fn()const props = createInputFieldEditorProps({ onSubmit })- // Actconst { rerender } = renderWithProviders(<InputFieldEditorPanel {...props} />,)@@ -469,21 +382,15 @@ describe('InputFieldEditorPanel', () => {)fireEvent.click(screen.getByTestId('form-submit-btn'))- // Assertexpect(onSubmit).toHaveBeenCalledTimes(2)})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should memoize formData when initialData does not change', () => {- // Arrangeconst initialData = createInputVar()const props = createInputFieldEditorProps({ initialData })- // Actconst { rerender } = renderWithProviders(<InputFieldEditorPanel {...props} />,)@@ -496,18 +403,15 @@ describe('InputFieldEditorPanel', () => {)const secondFormData = screen.getByTestId('form-initial-data').textContent- // Assertexpect(firstFormData).toBe(secondFormData)})it('should recompute formData when initialData changes', () => {- // Arrangeconst initialData1 = createInputVar({ variable: 'var1' })const initialData2 = createInputVar({ variable: 'var2' })const props1 = createInputFieldEditorProps({ initialData: initialData1 })const props2 = createInputFieldEditorProps({ initialData: initialData2 })- // Actconst { rerender } = renderWithProviders(<InputFieldEditorPanel {...props1} />,)@@ -520,33 +424,25 @@ describe('InputFieldEditorPanel', () => {)const secondFormData = screen.getByTestId('form-initial-data').textContent- // Assertexpect(firstFormData).not.toBe(secondFormData)expect(firstFormData).toContain('var1')expect(secondFormData).toContain('var2')})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle undefined initialData gracefully', () => {- // Arrangeconst props = createInputFieldEditorProps({ initialData: undefined })- // Act & Assertexpect(() =>renderWithProviders(<InputFieldEditorPanel {...props} />),).not.toThrow()})it('should handle rapid close button clicks', () => {- // Arrangeconst onClose = vi.fn()const props = createInputFieldEditorProps({ onClose })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)const closeButtons = screen.getAllByRole('button')const closeButton = closeButtons.find(btn => btn.querySelector('svg'))@@ -557,12 +453,10 @@ describe('InputFieldEditorPanel', () => {fireEvent.click(closeButton)}- // Assertexpect(onClose).toHaveBeenCalledTimes(3)})it('should handle special characters in initialData', () => {- // Arrangeconst initialData = createInputVar({label: 'Test <script>alert("xss")</script>',variable: 'test_var',@@ -570,15 +464,12 @@ describe('InputFieldEditorPanel', () => {})const props = createInputFieldEditorProps({ initialData })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByTestId('input-field-form')).toBeInTheDocument()})it('should handle empty string values in initialData', () => {- // Arrangeconst initialData = createInputVar({label: '',variable: '',@@ -588,26 +479,16 @@ describe('InputFieldEditorPanel', () => {})const props = createInputFieldEditorProps({ initialData })- // ActrenderWithProviders(<InputFieldEditorPanel {...props} />)- // Assertexpect(screen.getByTestId('input-field-form')).toBeInTheDocument()})})})-// ============================================================================-// Utils Tests - convertToInputFieldFormData-// ============================================================================-describe('convertToInputFieldFormData', () => {- // -------------------------------------------------------------------------- // Basic Conversion Tests- // -------------------------------------------------------------------------describe('Basic Conversion', () => {it('should convert InputVar to FormData with all fields', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.textInput,label: 'Test',@@ -621,10 +502,8 @@ describe('convertToInputFieldFormData', () => {unit: 'kg',})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.type).toBe(PipelineInputVarType.textInput)expect(result.label).toBe('Test')expect(result.variable).toBe('test_var')@@ -638,7 +517,6 @@ describe('convertToInputFieldFormData', () => {})it('should convert file-related fields correctly', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.singleFile,allowed_file_upload_methods: ['local_file', 'remote_url'] as TransferMethod[],@@ -646,10 +524,8 @@ describe('convertToInputFieldFormData', () => {allowed_file_extensions: ['.jpg', '.pdf'],})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.allowedFileUploadMethods).toEqual(['local_file','remote_url',@@ -661,10 +537,8 @@ describe('convertToInputFieldFormData', () => {})it('should return default template when data is undefined', () => {- // Actconst result = convertToInputFieldFormData(undefined)- // Assertexpect(result.type).toBe(PipelineInputVarType.textInput)expect(result.variable).toBe('')expect(result.label).toBe('')@@ -672,183 +546,140 @@ describe('convertToInputFieldFormData', () => {})})- // -------------------------------------------------------------------------- // Optional Fields Handling Tests- // -------------------------------------------------------------------------describe('Optional Fields Handling', () => {it('should not include default when default_value is undefined', () => {- // Arrangeconst inputVar = createInputVar({default_value: undefined,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.default).toBeUndefined()})it('should not include default when default_value is null', () => {- // Arrangeconst inputVar: InputVar = {...createInputVar(),default_value: null as unknown as string,}- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.default).toBeUndefined()})it('should include default when default_value is empty string', () => {- // Arrangeconst inputVar = createInputVar({default_value: '',})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.default).toBe('')})it('should not include tooltips when undefined', () => {- // Arrangeconst inputVar = createInputVar({tooltips: undefined,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.tooltips).toBeUndefined()})it('should not include placeholder when undefined', () => {- // Arrangeconst inputVar = createInputVar({placeholder: undefined,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.placeholder).toBeUndefined()})it('should not include unit when undefined', () => {- // Arrangeconst inputVar = createInputVar({unit: undefined,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.unit).toBeUndefined()})it('should not include file settings when allowed_file_upload_methods is undefined', () => {- // Arrangeconst inputVar = createInputVar({allowed_file_upload_methods: undefined,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.allowedFileUploadMethods).toBeUndefined()})it('should not include allowedTypesAndExtensions details when file types/extensions are missing', () => {- // Arrangeconst inputVar = createInputVar({allowed_file_types: undefined,allowed_file_extensions: undefined,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.allowedTypesAndExtensions).toEqual({})})})- // -------------------------------------------------------------------------- // Type-Specific Tests- // -------------------------------------------------------------------------describe('Type-Specific Handling', () => {it('should handle textInput type', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.textInput,max_length: 256,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.type).toBe(PipelineInputVarType.textInput)expect(result.maxLength).toBe(256)})it('should handle paragraph type', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.paragraph,max_length: 1000,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.type).toBe(PipelineInputVarType.paragraph)expect(result.maxLength).toBe(1000)})it('should handle number type with unit', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.number,unit: 'meters',})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.type).toBe(PipelineInputVarType.number)expect(result.unit).toBe('meters')})it('should handle select type with options', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.select,options: ['Option A', 'Option B', 'Option C'],})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.type).toBe(PipelineInputVarType.select)expect(result.options).toEqual(['Option A', 'Option B', 'Option C'])})it('should handle singleFile type', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.singleFile,allowed_file_upload_methods: ['local_file'] as TransferMethod[],@@ -856,16 +687,13 @@ describe('convertToInputFieldFormData', () => {allowed_file_extensions: ['.jpg'],})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.type).toBe(PipelineInputVarType.singleFile)expect(result.allowedFileUploadMethods).toEqual(['local_file'])})it('should handle multiFiles type', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.multiFiles,max_length: 5,@@ -874,42 +702,29 @@ describe('convertToInputFieldFormData', () => {allowed_file_extensions: ['.pdf', '.doc'],})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.type).toBe(PipelineInputVarType.multiFiles)expect(result.maxLength).toBe(5)})it('should handle checkbox type', () => {- // Arrangeconst inputVar = createInputVar({type: PipelineInputVarType.checkbox,default_value: 'true',})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.type).toBe(PipelineInputVarType.checkbox)expect(result.default).toBe('true')})})})-// ============================================================================-// Utils Tests - convertFormDataToINputField-// ============================================================================-describe('convertFormDataToINputField', () => {- // -------------------------------------------------------------------------- // Basic Conversion Tests- // -------------------------------------------------------------------------describe('Basic Conversion', () => {it('should convert FormData to InputVar with all fields', () => {- // Arrangeconst formData = createFormData({type: PipelineInputVarType.textInput,label: 'Test',@@ -928,10 +743,8 @@ describe('convertFormDataToINputField', () => {},})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(PipelineInputVarType.textInput)expect(result.label).toBe('Test')expect(result.variable).toBe('test_var')@@ -948,7 +761,6 @@ describe('convertFormDataToINputField', () => {})it('should handle undefined optional fields', () => {- // Arrangeconst formData = createFormData({default: undefined,tooltips: undefined,@@ -961,10 +773,8 @@ describe('convertFormDataToINputField', () => {},})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.default_value).toBeUndefined()expect(result.tooltips).toBeUndefined()expect(result.placeholder).toBeUndefined()@@ -975,42 +785,30 @@ describe('convertFormDataToINputField', () => {})})- // -------------------------------------------------------------------------- // Field Mapping Tests- // -------------------------------------------------------------------------describe('Field Mapping', () => {it('should map maxLength to max_length', () => {- // Arrangeconst formData = createFormData({ maxLength: 256 })- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.max_length).toBe(256)})it('should map default to default_value', () => {- // Arrangeconst formData = createFormData({ default: 'my default' })- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.default_value).toBe('my default')})it('should map allowedFileUploadMethods to allowed_file_upload_methods', () => {- // Arrangeconst formData = createFormData({allowedFileUploadMethods: ['local_file', 'remote_url'] as TransferMethod[],})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.allowed_file_upload_methods).toEqual(['local_file','remote_url',@@ -1018,7 +816,6 @@ describe('convertFormDataToINputField', () => {})it('should map allowedTypesAndExtensions to separate fields', () => {- // Arrangeconst formData = createFormData({allowedTypesAndExtensions: {allowedFileTypes: ['image', 'document'] as SupportUploadFileTypes[],@@ -1026,119 +823,88 @@ describe('convertFormDataToINputField', () => {},})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.allowed_file_types).toEqual(['image', 'document'])expect(result.allowed_file_extensions).toEqual(['.jpg', '.pdf'])})})- // -------------------------------------------------------------------------- // Type-Specific Tests- // -------------------------------------------------------------------------describe('Type-Specific Handling', () => {it('should preserve textInput type', () => {- // Arrangeconst formData = createFormData({ type: PipelineInputVarType.textInput })- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(PipelineInputVarType.textInput)})it('should preserve paragraph type', () => {- // Arrangeconst formData = createFormData({ type: PipelineInputVarType.paragraph })- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(PipelineInputVarType.paragraph)})it('should preserve select type with options', () => {- // Arrangeconst formData = createFormData({type: PipelineInputVarType.select,options: ['A', 'B', 'C'],})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(PipelineInputVarType.select)expect(result.options).toEqual(['A', 'B', 'C'])})it('should preserve number type with unit', () => {- // Arrangeconst formData = createFormData({type: PipelineInputVarType.number,unit: 'kg',})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(PipelineInputVarType.number)expect(result.unit).toBe('kg')})it('should preserve singleFile type', () => {- // Arrangeconst formData = createFormData({type: PipelineInputVarType.singleFile,})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(PipelineInputVarType.singleFile)})it('should preserve multiFiles type with maxLength', () => {- // Arrangeconst formData = createFormData({type: PipelineInputVarType.multiFiles,maxLength: 10,})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(PipelineInputVarType.multiFiles)expect(result.max_length).toBe(10)})it('should preserve checkbox type', () => {- // Arrangeconst formData = createFormData({ type: PipelineInputVarType.checkbox })- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(PipelineInputVarType.checkbox)})})})-// ============================================================================-// Round-Trip Conversion Tests-// ============================================================================-describe('Round-Trip Conversion', () => {it('should preserve data through round-trip conversion for textInput', () => {- // Arrangeconst original = createInputVar({type: PipelineInputVarType.textInput,label: 'Test Label',@@ -1150,11 +916,9 @@ describe('Round-Trip Conversion', () => {placeholder: 'placeholder',})- // Actconst formData = convertToInputFieldFormData(original)const result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(original.type)expect(result.label).toBe(original.label)expect(result.variable).toBe(original.variable)@@ -1166,25 +930,21 @@ describe('Round-Trip Conversion', () => {})it('should preserve data through round-trip conversion for select', () => {- // Arrangeconst original = createInputVar({type: PipelineInputVarType.select,options: ['Option A', 'Option B', 'Option C'],default_value: 'Option A',})- // Actconst formData = convertToInputFieldFormData(original)const result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(original.type)expect(result.options).toEqual(original.options)expect(result.default_value).toBe(original.default_value)})it('should preserve data through round-trip conversion for file types', () => {- // Arrangeconst original = createInputVar({type: PipelineInputVarType.multiFiles,max_length: 5,@@ -1193,11 +953,9 @@ describe('Round-Trip Conversion', () => {allowed_file_extensions: ['.jpg', '.pdf'],})- // Actconst formData = convertToInputFieldFormData(original)const result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(original.type)expect(result.max_length).toBe(original.max_length)expect(result.allowed_file_upload_methods).toEqual(@@ -1210,7 +968,6 @@ describe('Round-Trip Conversion', () => {})it('should handle all input types through round-trip', () => {- // Arrangeconst typesToTest = [PipelineInputVarType.textInput,PipelineInputVarType.paragraph,@@ -1224,54 +981,39 @@ describe('Round-Trip Conversion', () => {typesToTest.forEach((type) => {const original = createInputVar({ type })- // Actconst formData = convertToInputFieldFormData(original)const result = convertFormDataToINputField(formData)- // Assertexpect(result.type).toBe(original.type)})})})-// ============================================================================-// Edge Cases Tests-// ============================================================================-describe('Edge Cases', () => {describe('convertToInputFieldFormData edge cases', () => {it('should handle zero maxLength', () => {- // Arrangeconst inputVar = createInputVar({ max_length: 0 })- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.maxLength).toBe(0)})it('should handle empty options array', () => {- // Arrangeconst inputVar = createInputVar({ options: [] })- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.options).toEqual([])})it('should handle options with special characters', () => {- // Arrangeconst inputVar = createInputVar({options: ['<script>', '"quoted"', '\'apostrophe\'', '&'],})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.options).toEqual(['<script>','"quoted"',@@ -1281,33 +1023,27 @@ describe('Edge Cases', () => {})it('should handle very long strings', () => {- // Arrangeconst longString = 'a'.repeat(10000)const inputVar = createInputVar({label: longString,tooltips: longString,})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.label).toBe(longString)expect(result.tooltips).toBe(longString)})it('should handle unicode characters', () => {- // Arrangeconst inputVar = createInputVar({label: '测试标签 🎉',tooltips: 'ツールチップ 😀',placeholder: 'Platzhalter ñ é',})- // Actconst result = convertToInputFieldFormData(inputVar)- // Assertexpect(result.label).toBe('测试标签 🎉')expect(result.tooltips).toBe('ツールチップ 😀')expect(result.placeholder).toBe('Platzhalter ñ é')@@ -1316,18 +1052,14 @@ describe('Edge Cases', () => {describe('convertFormDataToINputField edge cases', () => {it('should handle zero maxLength', () => {- // Arrangeconst formData = createFormData({ maxLength: 0 })- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.max_length).toBe(0)})it('should handle empty allowedTypesAndExtensions', () => {- // Arrangeconst formData = createFormData({allowedTypesAndExtensions: {allowedFileTypes: [],@@ -1335,51 +1067,38 @@ describe('Edge Cases', () => {},})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.allowed_file_types).toEqual([])expect(result.allowed_file_extensions).toEqual([])})it('should handle boolean default value (checkbox)', () => {- // Arrangeconst formData = createFormData({type: PipelineInputVarType.checkbox,default: 'true',})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.default_value).toBe('true')})it('should handle numeric default value (number type)', () => {- // Arrangeconst formData = createFormData({type: PipelineInputVarType.number,default: '42',})- // Actconst result = convertFormDataToINputField(formData)- // Assertexpect(result.default_value).toBe('42')})})})-// ============================================================================-// Hook Memoization Tests-// ============================================================================-describe('Hook Memoization', () => {it('should return stable callback reference for handleSubmit', () => {- // Arrangeconst onSubmit = vi.fn()let handleSubmitRef1: ((value: FormData) => void) | undefinedlet handleSubmitRef2: ((value: FormData) => void) | undefined@@ -1402,7 +1121,6 @@ describe('Hook Memoization', () => {return null}- // Actconst { rerender } = render(<TestComponent capture={(ref) => { handleSubmitRef1 = ref }} submitFn={onSubmit} />,)@@ -1410,12 +1128,10 @@ describe('Hook Memoization', () => {<TestComponent capture={(ref) => { handleSubmitRef2 = ref }} submitFn={onSubmit} />,)- // Assert - callback should be same reference due to useCallbackexpect(handleSubmitRef1).toBe(handleSubmitRef2)})it('should return stable formData when initialData is unchanged', () => {- // Arrangeconst initialData = createInputVar()let formData1: FormData | undefinedlet formData2: FormData | undefined@@ -1435,7 +1151,6 @@ describe('Hook Memoization', () => {return null}- // Actconst { rerender } = render(<TestComponentdata={initialData}@@ -1449,7 +1164,6 @@ describe('Hook Memoization', () => {/>,)- // Assert - formData should be same reference due to useMemoexpect(formData1).toBe(formData2)})})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/hooks.spec.ts b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/hooks.spec.tsnew file mode 100644index 00000000000..d07a7052526--- /dev/null+++ b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/hooks.spec.ts@@ -0,0 +1,366 @@+import { renderHook } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { PipelineInputVarType } from '@/models/pipeline'+import { useConfigurations, useHiddenConfigurations, useHiddenFieldNames } from '../hooks'++vi.mock('@/app/components/base/file-uploader/hooks', () => ({+ useFileSizeLimit: () => ({+ imgSizeLimit: 10 * 1024 * 1024,+ docSizeLimit: 15 * 1024 * 1024,+ audioSizeLimit: 50 * 1024 * 1024,+ videoSizeLimit: 100 * 1024 * 1024,+ }),+}))++vi.mock('@/service/use-common', () => ({+ useFileUploadConfig: () => ({ data: {} }),+}))++vi.mock('@/app/components/workflow/constants', () => ({+ DEFAULT_FILE_UPLOAD_SETTING: {+ allowed_file_upload_methods: ['local_file', 'remote_url'],+ allowed_file_types: ['image', 'document'],+ allowed_file_extensions: ['.jpg', '.png', '.pdf'],+ max_length: 5,+ },+}))++vi.mock('../schema', () => ({+ TEXT_MAX_LENGTH: 256,+}))++vi.mock('@/utils/format', () => ({+ formatFileSize: (size: number) => `${Math.round(size / 1024 / 1024)}MB`,+}))++describe('useHiddenFieldNames', () => {+ afterEach(() => {+ vi.clearAllMocks()+ })++ it('should return field names for textInput type', () => {+ const { result } = renderHook(() => useHiddenFieldNames(PipelineInputVarType.textInput))++ expect(result.current).toContain('variableconfig.defaultvalue')+ expect(result.current).toContain('variableconfig.placeholder')+ expect(result.current).toContain('variableconfig.tooltips')+ })++ it('should return field names for paragraph type', () => {+ const { result } = renderHook(() => useHiddenFieldNames(PipelineInputVarType.paragraph))++ expect(result.current).toContain('variableconfig.defaultvalue')+ expect(result.current).toContain('variableconfig.placeholder')+ expect(result.current).toContain('variableconfig.tooltips')+ })++ it('should return field names for number type including unit', () => {+ const { result } = renderHook(() => useHiddenFieldNames(PipelineInputVarType.number))++ expect(result.current).toContain('appdebug.variableconfig.defaultvalue')+ expect(result.current).toContain('appdebug.variableconfig.unit')+ expect(result.current).toContain('appdebug.variableconfig.placeholder')+ expect(result.current).toContain('appdebug.variableconfig.tooltips')+ })++ it('should return field names for select type', () => {+ const { result } = renderHook(() => useHiddenFieldNames(PipelineInputVarType.select))++ expect(result.current).toContain('appdebug.variableconfig.defaultvalue')+ expect(result.current).toContain('appdebug.variableconfig.tooltips')+ })++ it('should return field names for singleFile type', () => {+ const { result } = renderHook(() => useHiddenFieldNames(PipelineInputVarType.singleFile))++ expect(result.current).toContain('appdebug.variableconfig.uploadmethod')+ expect(result.current).toContain('appdebug.variableconfig.tooltips')+ })++ it('should return field names for multiFiles type including max number', () => {+ const { result } = renderHook(() => useHiddenFieldNames(PipelineInputVarType.multiFiles))++ expect(result.current).toContain('appdebug.variableconfig.uploadmethod')+ expect(result.current).toContain('appdebug.variableconfig.maxnumberofuploads')+ expect(result.current).toContain('appdebug.variableconfig.tooltips')+ })++ it('should return field names for checkbox type', () => {+ const { result } = renderHook(() => useHiddenFieldNames(PipelineInputVarType.checkbox))++ expect(result.current).toContain('appdebug.variableconfig.startchecked')+ expect(result.current).toContain('appdebug.variableconfig.tooltips')+ })++ it('should return only tooltips for unknown type', () => {+ const { result } = renderHook(() => useHiddenFieldNames('unknown-type' as PipelineInputVarType))++ expect(result.current).toBe('appdebug.variableconfig.tooltips')+ })++ it('should return comma-separated lowercase string', () => {+ const { result } = renderHook(() => useHiddenFieldNames(PipelineInputVarType.textInput))++ expect(result.current).toMatch(/,/)+ expect(result.current).toBe(result.current.toLowerCase())+ })+})++describe('useConfigurations', () => {+ let mockGetFieldValue: ReturnType<typeof vi.fn<(...args: unknown[]) => unknown>>+ let mockSetFieldValue: ReturnType<typeof vi.fn<(...args: unknown[]) => void>>++ beforeEach(() => {+ mockGetFieldValue = vi.fn()+ mockSetFieldValue = vi.fn()+ vi.clearAllMocks()+ })++ it('should return array of configurations', () => {+ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ expect(Array.isArray(result.current)).toBe(true)+ expect(result.current.length).toBeGreaterThan(0)+ })++ it('should include field type select configuration', () => {+ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const typeConfig = result.current.find(c => c.variable === 'type')+ expect(typeConfig).toBeDefined()+ expect(typeConfig?.required).toBe(true)+ })++ it('should include variable name configuration', () => {+ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const varConfig = result.current.find(c => c.variable === 'variable')+ expect(varConfig).toBeDefined()+ expect(varConfig?.required).toBe(true)+ })++ it('should include display name configuration', () => {+ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const labelConfig = result.current.find(c => c.variable === 'label')+ expect(labelConfig).toBeDefined()+ expect(labelConfig?.required).toBe(false)+ })++ it('should include required checkbox configuration', () => {+ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const requiredConfig = result.current.find(c => c.variable === 'required')+ expect(requiredConfig).toBeDefined()+ })++ it('should set file defaults when type changes to singleFile', () => {+ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const typeConfig = result.current.find(c => c.variable === 'type')+ typeConfig?.listeners?.onChange?.({ value: PipelineInputVarType.singleFile, fieldApi: {} as never })++ expect(mockSetFieldValue).toHaveBeenCalledWith('allowedFileUploadMethods', ['local_file', 'remote_url'])+ expect(mockSetFieldValue).toHaveBeenCalledWith('allowedTypesAndExtensions', {+ allowedFileTypes: ['image', 'document'],+ allowedFileExtensions: ['.jpg', '.png', '.pdf'],+ })+ })++ it('should set maxLength when type changes to multiFiles', () => {+ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const typeConfig = result.current.find(c => c.variable === 'type')+ typeConfig?.listeners?.onChange?.({ value: PipelineInputVarType.multiFiles, fieldApi: {} as never })++ expect(mockSetFieldValue).toHaveBeenCalledWith('maxLength', 5)+ })++ it('should not set file defaults when type changes to text', () => {+ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const typeConfig = result.current.find(c => c.variable === 'type')+ typeConfig?.listeners?.onChange?.({ value: PipelineInputVarType.textInput, fieldApi: {} as never })++ expect(mockSetFieldValue).not.toHaveBeenCalled()+ })++ it('should auto-fill label from variable name on blur', () => {+ mockGetFieldValue.mockReturnValue('')++ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const varConfig = result.current.find(c => c.variable === 'variable')+ varConfig?.listeners?.onBlur?.({ value: 'myVariable', fieldApi: {} as never })++ expect(mockSetFieldValue).toHaveBeenCalledWith('label', 'myVariable')+ })++ it('should not auto-fill label if label already exists', () => {+ mockGetFieldValue.mockReturnValue('Existing Label')++ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const varConfig = result.current.find(c => c.variable === 'variable')+ varConfig?.listeners?.onBlur?.({ value: 'myVariable', fieldApi: {} as never })++ expect(mockSetFieldValue).not.toHaveBeenCalled()+ })++ it('should reset label to variable name when display name is cleared', () => {+ mockGetFieldValue.mockReturnValue('existingVar')++ const { result } = renderHook(() =>+ useConfigurations({+ getFieldValue: mockGetFieldValue,+ setFieldValue: mockSetFieldValue,+ supportFile: true,+ }),+ )++ const labelConfig = result.current.find(c => c.variable === 'label')+ labelConfig?.listeners?.onBlur?.({ value: '', fieldApi: {} as never })++ expect(mockSetFieldValue).toHaveBeenCalledWith('label', 'existingVar')+ })+})++describe('useHiddenConfigurations', () => {+ afterEach(() => {+ vi.clearAllMocks()+ })++ it('should return array of hidden configurations', () => {+ const { result } = renderHook(() =>+ useHiddenConfigurations({ options: undefined }),+ )++ expect(Array.isArray(result.current)).toBe(true)+ expect(result.current.length).toBeGreaterThan(0)+ })++ it('should include default value config for textInput', () => {+ const { result } = renderHook(() =>+ useHiddenConfigurations({ options: undefined }),+ )++ const defaultConfigs = result.current.filter(c => c.variable === 'default')+ expect(defaultConfigs.length).toBeGreaterThan(0)+ })++ it('should include tooltips configuration for all types', () => {+ const { result } = renderHook(() =>+ useHiddenConfigurations({ options: undefined }),+ )++ const tooltipsConfig = result.current.find(c => c.variable === 'tooltips')+ expect(tooltipsConfig).toBeDefined()+ expect(tooltipsConfig?.showConditions).toEqual([])+ })++ it('should build select options from provided options', () => {+ const { result } = renderHook(() =>+ useHiddenConfigurations({ options: ['opt1', 'opt2'] }),+ )++ const selectDefault = result.current.find(+ c => c.variable === 'default' && c.showConditions?.some(sc => sc.value === PipelineInputVarType.select),+ )+ expect(selectDefault?.options).toBeDefined()+ expect(selectDefault?.options?.[0]?.value).toBe('')+ expect(selectDefault?.options?.[1]?.value).toBe('opt1')+ expect(selectDefault?.options?.[2]?.value).toBe('opt2')+ })++ it('should return empty options when options prop is undefined', () => {+ const { result } = renderHook(() =>+ useHiddenConfigurations({ options: undefined }),+ )++ const selectDefault = result.current.find(+ c => c.variable === 'default' && c.showConditions?.some(sc => sc.value === PipelineInputVarType.select),+ )+ expect(selectDefault?.options).toEqual([])+ })++ it('should include upload method configs for file types', () => {+ const { result } = renderHook(() =>+ useHiddenConfigurations({ options: undefined }),+ )++ const uploadMethods = result.current.filter(c => c.variable === 'allowedFileUploadMethods')+ expect(uploadMethods.length).toBe(2) // singleFile + multiFiles+ })++ it('should include maxLength slider for multiFiles', () => {+ const { result } = renderHook(() =>+ useHiddenConfigurations({ options: undefined }),+ )++ const maxLength = result.current.find(+ c => c.variable === 'maxLength' && c.showConditions?.some(sc => sc.value === PipelineInputVarType.multiFiles),+ )+ expect(maxLength).toBeDefined()+ expect(maxLength?.description).toBeDefined()+ })+})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/editor/form/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/index.spec.tsxsimilarity index 77%rename from web/app/components/rag-pipeline/components/panel/input-field/editor/form/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/index.spec.tsxindex 48df13acb20..adc249a88d7 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/editor/form/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/index.spec.tsx@@ -1,21 +1,14 @@-import type { FormData, InputFieldFormProps } from './types'+import type { FormData, InputFieldFormProps } from '../types'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { PipelineInputVarType } from '@/models/pipeline'-import { useConfigurations, useHiddenConfigurations, useHiddenFieldNames } from './hooks'-import InputFieldForm from './index'-import { createInputFieldSchema, TEXT_MAX_LENGTH } from './schema'+import { useConfigurations, useHiddenConfigurations, useHiddenFieldNames } from '../hooks'+import InputFieldForm from '../index'+import { createInputFieldSchema, TEXT_MAX_LENGTH } from '../schema'-// Type helper for partial listener event parameters in tests-// Using double assertion for test mocks with incomplete event objectsconst createMockEvent = <T,>(value: T) => ({ value }) as unknown as Parameters<NonNullable<NonNullable<ReturnType<typeof useConfigurations>[number]['listeners']>['onChange']>>[0]-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock file upload config serviceconst mockFileUploadConfig = {image_file_size_limit: 10,file_size_limit: 15,@@ -32,17 +25,12 @@ vi.mock('@/service/use-common', () => ({}),}))-// Mock Toast static methodvi.mock('@/app/components/base/toast', () => ({default: {notify: vi.fn(),},}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createFormData = (overrides?: Partial<FormData>): FormData => ({type: PipelineInputVarType.textInput,label: 'Test Label',@@ -71,10 +59,6 @@ const createInputFieldFormProps = (overrides?: Partial<InputFieldFormProps>): In...overrides,})-// ============================================================================-// Test Wrapper Component-// ============================================================================-const createTestQueryClient = () => new QueryClient({defaultOptions: {queries: {@@ -101,107 +85,75 @@ const renderHookWithProviders = <TResult,>(hook: () => TResult) => {return renderHook(hook, { wrapper: TestWrapper })}-// ============================================================================-// InputFieldForm Component Tests-// ============================================================================-describe('InputFieldForm', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render form without crashing', () => {- // Arrangeconst props = createInputFieldFormProps()- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})it('should render cancel button', () => {- // Arrangeconst props = createInputFieldFormProps()- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument()})it('should render form with initial values', () => {- // Arrangeconst initialData = createFormData({variable: 'custom_var',label: 'Custom Label',})const props = createInputFieldFormProps({ initialData })- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should handle supportFile=true prop', () => {- // Arrangeconst props = createInputFieldFormProps({ supportFile: true })- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})it('should handle supportFile=false (default) prop', () => {- // Arrangeconst props = createInputFieldFormProps({ supportFile: false })- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})it('should handle isEditMode=true prop', () => {- // Arrangeconst props = createInputFieldFormProps({ isEditMode: true })- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})it('should handle isEditMode=false prop', () => {- // Arrangeconst props = createInputFieldFormProps({ isEditMode: false })- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})it('should handle different initial data types', () => {- // Arrangeconst typesToTest = [PipelineInputVarType.textInput,PipelineInputVarType.paragraph,@@ -214,49 +166,37 @@ describe('InputFieldForm', () => {const initialData = createFormData({ type })const props = createInputFieldFormProps({ initialData })- // Actconst { container, unmount } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()unmount()})})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onCancel when cancel button is clicked', async () => {- // Arrangeconst onCancel = vi.fn()const props = createInputFieldFormProps({ onCancel })- // ActrenderWithProviders(<InputFieldForm {...props} />)fireEvent.click(screen.getByRole('button', { name: /cancel/i }))- // Assertexpect(onCancel).toHaveBeenCalledTimes(1)})it('should prevent default on form submit', async () => {- // Arrangeconst props = createInputFieldFormProps()const { container } = renderWithProviders(<InputFieldForm {...props} />)const form = container.querySelector('form')!const submitEvent = new Event('submit', { bubbles: true, cancelable: true })- // Actform.dispatchEvent(submitEvent)- // Assertexpect(submitEvent.defaultPrevented).toBe(true)})it('should show Toast error when form validation fails on submit', async () => {- // Arrange - Create invalid form data with empty variable name (validation should fail)const Toast = await import('@/app/components/base/toast')const initialData = createFormData({variable: '', // Empty variable should fail validation@@ -265,12 +205,10 @@ describe('InputFieldForm', () => {const onSubmit = vi.fn()const props = createInputFieldFormProps({ initialData, onSubmit })- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)const form = container.querySelector('form')!fireEvent.submit(form)- // Assert - Toast should be called with error message when validation failsawait waitFor(() => {expect(Toast.default.notify).toHaveBeenCalledWith(expect.objectContaining({@@ -279,12 +217,10 @@ describe('InputFieldForm', () => {}),)})- // onSubmit should not be called when validation failsexpect(onSubmit).not.toHaveBeenCalled()})it('should call onSubmit with moreInfo when variable name changes in edit mode', async () => {- // Arrange - Initial variable name is 'original_var', we change it to 'new_var'const initialData = createFormData({variable: 'original_var',label: 'Test Label',@@ -296,18 +232,14 @@ describe('InputFieldForm', () => {isEditMode: true,})- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Find and change the variable input by labelconst variableInput = screen.getByLabelText('appDebug.variableConfig.varName')fireEvent.change(variableInput, { target: { value: 'new_var' } })- // Submit the formconst form = document.querySelector('form')!fireEvent.submit(form)- // Assert - onSubmit should be called with moreInfo containing variable name change infoawait waitFor(() => {expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({@@ -325,7 +257,6 @@ describe('InputFieldForm', () => {})it('should call onSubmit without moreInfo when variable name does not change in edit mode', async () => {- // Arrange - Variable name stays the sameconst initialData = createFormData({variable: 'same_var',label: 'Test Label',@@ -337,14 +268,11 @@ describe('InputFieldForm', () => {isEditMode: true,})- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Submit without changing variable nameconst form = document.querySelector('form')!fireEvent.submit(form)- // Assert - onSubmit should be called without moreInfo (undefined)await waitFor(() => {expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({@@ -356,7 +284,6 @@ describe('InputFieldForm', () => {})it('should call onSubmit without moreInfo when not in edit mode', async () => {- // Arrangeconst initialData = createFormData({variable: 'test_var',label: 'Test Label',@@ -368,14 +295,11 @@ describe('InputFieldForm', () => {isEditMode: false,})- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Submit the formconst form = document.querySelector('form')!fireEvent.submit(form)- // Assert - onSubmit should be called without moreInfo since not in edit modeawait waitFor(() => {expect(onSubmit).toHaveBeenCalledWith(expect.any(Object),@@ -385,76 +309,55 @@ describe('InputFieldForm', () => {})})- // -------------------------------------------------------------------------- // State Management Tests- // -------------------------------------------------------------------------describe('State Management', () => {it('should initialize showAllSettings state as false', () => {- // Arrangeconst props = createInputFieldFormProps()- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Assert - ShowAllSettings component should be visible when showAllSettings is falseexpect(screen.queryByText(/appDebug.variableConfig.showAllSettings/i)).toBeInTheDocument()})it('should toggle showAllSettings state when clicking show all settings', async () => {- // Arrangeconst props = createInputFieldFormProps()renderWithProviders(<InputFieldForm {...props} />)- // Act - Find and click the show all settings elementconst showAllSettingsElement = screen.getByText(/appDebug.variableConfig.showAllSettings/i)const clickableParent = showAllSettingsElement.closest('.cursor-pointer')if (clickableParent) {fireEvent.click(clickableParent)}- // Assert - After clicking, ShowAllSettings should be hidden and HiddenFields should be visibleawait waitFor(() => {expect(screen.queryByText(/appDebug.variableConfig.showAllSettings/i)).not.toBeInTheDocument()})})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain stable onCancel callback reference', () => {- // Arrangeconst onCancel = vi.fn()const props = createInputFieldFormProps({ onCancel })- // ActrenderWithProviders(<InputFieldForm {...props} />)const cancelButton = screen.getByRole('button', { name: /cancel/i })fireEvent.click(cancelButton)fireEvent.click(cancelButton)- // Assertexpect(onCancel).toHaveBeenCalledTimes(2)})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle empty initial data gracefully', () => {- // Arrangeconst props = createInputFieldFormProps({initialData: {} as Record<string, unknown>,})- // Act & Assert - should not crashexpect(() => renderWithProviders(<InputFieldForm {...props} />)).not.toThrow()})it('should handle undefined optional fields', () => {- // Arrangeconst initialData = {type: PipelineInputVarType.textInput,label: 'Test',@@ -464,75 +367,57 @@ describe('InputFieldForm', () => {allowedFileTypes: [],allowedFileExtensions: [],},- // Other fields are undefined}const props = createInputFieldFormProps({ initialData })- // Act & Assertexpect(() => renderWithProviders(<InputFieldForm {...props} />)).not.toThrow()})it('should handle special characters in variable name', () => {- // Arrangeconst initialData = createFormData({variable: 'test_var_123',label: 'Test Label <script>',})const props = createInputFieldFormProps({ initialData })- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})})})-// ============================================================================-// useHiddenFieldNames Hook Tests-// ============================================================================-describe('useHiddenFieldNames', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Return Value Tests for Different Types- // -------------------------------------------------------------------------describe('Return Values by Type', () => {it('should return correct field names for textInput type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenFieldNames(PipelineInputVarType.textInput),)- // Assert - should include default value, placeholder, tooltipsexpect(result.current).toContain('appDebug.variableConfig.defaultValue'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.placeholder'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())})it('should return correct field names for paragraph type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenFieldNames(PipelineInputVarType.paragraph),)- // Assertexpect(result.current).toContain('appDebug.variableConfig.defaultValue'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.placeholder'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())})it('should return correct field names for number type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenFieldNames(PipelineInputVarType.number),)- // Assert - should include unit fieldexpect(result.current).toContain('appDebug.variableConfig.defaultValue'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.unit'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.placeholder'.toLowerCase())@@ -540,86 +425,64 @@ describe('useHiddenFieldNames', () => {})it('should return correct field names for select type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenFieldNames(PipelineInputVarType.select),)- // Assertexpect(result.current).toContain('appDebug.variableConfig.defaultValue'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())})it('should return correct field names for singleFile type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenFieldNames(PipelineInputVarType.singleFile),)- // Assertexpect(result.current).toContain('appDebug.variableConfig.uploadMethod'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())})it('should return correct field names for multiFiles type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenFieldNames(PipelineInputVarType.multiFiles),)- // Assertexpect(result.current).toContain('appDebug.variableConfig.uploadMethod'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.maxNumberOfUploads'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())})it('should return correct field names for checkbox type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenFieldNames(PipelineInputVarType.checkbox),)- // Assertexpect(result.current).toContain('appDebug.variableConfig.startChecked'.toLowerCase())expect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())})})- // -------------------------------------------------------------------------- // Edge Cases- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should return tooltips only for unknown type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenFieldNames('unknown_type' as PipelineInputVarType),)- // Assert - should only contain tooltips for unknown typesexpect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())})})})-// ============================================================================-// useConfigurations Hook Tests-// ============================================================================-describe('useConfigurations', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Configuration Generation Tests- // -------------------------------------------------------------------------describe('Configuration Generation', () => {it('should return array of configurations', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()- // Actconst { result } = renderHookWithProviders(() =>useConfigurations({getFieldValue: mockGetFieldValue,@@ -628,17 +491,14 @@ describe('useConfigurations', () => {}),)- // Assertexpect(Array.isArray(result.current)).toBe(true)expect(result.current.length).toBeGreaterThan(0)})it('should include type field configuration', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()- // Actconst { result } = renderHookWithProviders(() =>useConfigurations({getFieldValue: mockGetFieldValue,@@ -647,18 +507,15 @@ describe('useConfigurations', () => {}),)- // Assertconst typeConfig = result.current.find(config => config.variable === 'type')expect(typeConfig).toBeDefined()expect(typeConfig?.required).toBe(true)})it('should include variable field configuration', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()- // Actconst { result } = renderHookWithProviders(() =>useConfigurations({getFieldValue: mockGetFieldValue,@@ -667,18 +524,15 @@ describe('useConfigurations', () => {}),)- // Assertconst variableConfig = result.current.find(config => config.variable === 'variable')expect(variableConfig).toBeDefined()expect(variableConfig?.required).toBe(true)})it('should include label field configuration', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()- // Actconst { result } = renderHookWithProviders(() =>useConfigurations({getFieldValue: mockGetFieldValue,@@ -687,18 +541,15 @@ describe('useConfigurations', () => {}),)- // Assertconst labelConfig = result.current.find(config => config.variable === 'label')expect(labelConfig).toBeDefined()expect(labelConfig?.required).toBe(false)})it('should include required field configuration', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()- // Actconst { result } = renderHookWithProviders(() =>useConfigurations({getFieldValue: mockGetFieldValue,@@ -707,17 +558,14 @@ describe('useConfigurations', () => {}),)- // Assertconst requiredConfig = result.current.find(config => config.variable === 'required')expect(requiredConfig).toBeDefined()})it('should pass supportFile prop to type configuration', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()- // Actconst { result } = renderHookWithProviders(() =>useConfigurations({getFieldValue: mockGetFieldValue,@@ -726,18 +574,13 @@ describe('useConfigurations', () => {}),)- // Assertconst typeConfig = result.current.find(config => config.variable === 'type')expect(typeConfig?.supportFile).toBe(true)})})- // -------------------------------------------------------------------------- // Callback Tests- // -------------------------------------------------------------------------describe('Callbacks', () => {it('should call setFieldValue when type changes to singleFile', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()@@ -749,17 +592,14 @@ describe('useConfigurations', () => {}),)- // Actconst typeConfig = result.current.find(config => config.variable === 'type')typeConfig?.listeners?.onChange?.(createMockEvent(PipelineInputVarType.singleFile))- // Assertexpect(mockSetFieldValue).toHaveBeenCalledWith('allowedFileUploadMethods', expect.any(Array))expect(mockSetFieldValue).toHaveBeenCalledWith('allowedTypesAndExtensions', expect.any(Object))})it('should call setFieldValue when type changes to multiFiles', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()@@ -771,16 +611,13 @@ describe('useConfigurations', () => {}),)- // Actconst typeConfig = result.current.find(config => config.variable === 'type')typeConfig?.listeners?.onChange?.(createMockEvent(PipelineInputVarType.multiFiles))- // Assertexpect(mockSetFieldValue).toHaveBeenCalledWith('maxLength', expect.any(Number))})it('should set label from variable name on blur when label is empty', () => {- // Arrangeconst mockGetFieldValue = vi.fn().mockReturnValue('')const mockSetFieldValue = vi.fn()@@ -792,16 +629,13 @@ describe('useConfigurations', () => {}),)- // Actconst variableConfig = result.current.find(config => config.variable === 'variable')variableConfig?.listeners?.onBlur?.(createMockEvent('test_variable'))- // Assertexpect(mockSetFieldValue).toHaveBeenCalledWith('label', 'test_variable')})it('should not set label from variable name on blur when label is not empty', () => {- // Arrangeconst mockGetFieldValue = vi.fn().mockReturnValue('Existing Label')const mockSetFieldValue = vi.fn()@@ -813,16 +647,13 @@ describe('useConfigurations', () => {}),)- // Actconst variableConfig = result.current.find(config => config.variable === 'variable')variableConfig?.listeners?.onBlur?.(createMockEvent('test_variable'))- // Assertexpect(mockSetFieldValue).not.toHaveBeenCalled()})it('should reset label to variable name when display name is cleared', () => {- // Arrangeconst mockGetFieldValue = vi.fn().mockReturnValue('original_var')const mockSetFieldValue = vi.fn()@@ -834,25 +665,18 @@ describe('useConfigurations', () => {}),)- // Actconst labelConfig = result.current.find(config => config.variable === 'label')labelConfig?.listeners?.onBlur?.(createMockEvent(''))- // Assertexpect(mockSetFieldValue).toHaveBeenCalledWith('label', 'original_var')})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should return configurations array with correct length', () => {- // Arrangeconst mockGetFieldValue = vi.fn()const mockSetFieldValue = vi.fn()- // Actconst { result } = renderHookWithProviders(() =>useConfigurations({getFieldValue: mockGetFieldValue,@@ -861,77 +685,59 @@ describe('useConfigurations', () => {}),)- // Assert - should have all expected field configurationsexpect(result.current.length).toBe(8) // type, variable, label, maxLength, options, fileTypes x2, required})})})-// ============================================================================-// useHiddenConfigurations Hook Tests-// ============================================================================-describe('useHiddenConfigurations', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Configuration Generation Tests- // -------------------------------------------------------------------------describe('Configuration Generation', () => {it('should return array of hidden configurations', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertexpect(Array.isArray(result.current)).toBe(true)expect(result.current.length).toBeGreaterThan(0)})it('should include default value configurations for different types', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertconst defaultConfigs = result.current.filter(config => config.variable === 'default')expect(defaultConfigs.length).toBeGreaterThan(0)})it('should include tooltips configuration', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertconst tooltipsConfig = result.current.find(config => config.variable === 'tooltips')expect(tooltipsConfig).toBeDefined()expect(tooltipsConfig?.showConditions).toEqual([])})it('should include placeholder configurations', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertconst placeholderConfigs = result.current.filter(config => config.variable === 'placeholder')expect(placeholderConfigs.length).toBeGreaterThan(0)})it('should include unit configuration for number type', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertconst unitConfig = result.current.find(config => config.variable === 'unit')expect(unitConfig).toBeDefined()expect(unitConfig?.showConditions).toContainEqual({@@ -941,12 +747,10 @@ describe('useHiddenConfigurations', () => {})it('should include upload method configurations for file types', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertconst uploadMethodConfigs = result.current.filter(config => config.variable === 'allowedFileUploadMethods',)@@ -954,12 +758,10 @@ describe('useHiddenConfigurations', () => {})it('should include maxLength configuration for multiFiles', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertconst maxLengthConfig = result.current.find(config => config.variable === 'maxLength'&& config.showConditions?.some(c => c.value === PipelineInputVarType.multiFiles),@@ -968,20 +770,14 @@ describe('useHiddenConfigurations', () => {})})- // -------------------------------------------------------------------------- // Options Handling Tests- // -------------------------------------------------------------------------describe('Options Handling', () => {it('should generate select options from provided options array', () => {- // Arrangeconst options = ['Option A', 'Option B', 'Option C']- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options }),)- // Assertconst selectConfig = result.current.find(config => config.variable === 'default'&& config.showConditions?.some(c => c.value === PipelineInputVarType.select),@@ -991,15 +787,12 @@ describe('useHiddenConfigurations', () => {})it('should include "no default selected" option', () => {- // Arrangeconst options = ['Option A']- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options }),)- // Assertconst selectConfig = result.current.find(config => config.variable === 'default'&& config.showConditions?.some(c => c.value === PipelineInputVarType.select),@@ -1009,12 +802,10 @@ describe('useHiddenConfigurations', () => {})it('should return empty options when options is undefined', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertconst selectConfig = result.current.find(config => config.variable === 'default'&& config.showConditions?.some(c => c.value === PipelineInputVarType.select),@@ -1023,17 +814,12 @@ describe('useHiddenConfigurations', () => {})})- // -------------------------------------------------------------------------- // File Size Limit Integration Tests- // -------------------------------------------------------------------------describe('File Size Limit Integration', () => {it('should include file size description in maxLength config', () => {- // Actconst { result } = renderHookWithProviders(() =>useHiddenConfigurations({ options: undefined }),)- // Assertconst maxLengthConfig = result.current.find(config => config.variable === 'maxLength'&& config.showConditions?.some(c => c.value === PipelineInputVarType.multiFiles),@@ -1043,36 +829,24 @@ describe('useHiddenConfigurations', () => {})})-// ============================================================================-// Schema Validation Tests-// ============================================================================-describe('createInputFieldSchema', () => {- // Mock translation function - cast to any to satisfy TFunction type requirementsconst mockT = ((key: string) => key) as unknown as Parameters<typeof createInputFieldSchema>[1]beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Common Schema Tests- // -------------------------------------------------------------------------describe('Common Schema Validation', () => {it('should validate required variable field', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const invalidData = { variable: '', label: 'Test', required: true, type: 'text-input' }- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})it('should validate variable max length', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const invalidData = {variable: 'a'.repeat(100),@@ -1082,15 +856,12 @@ describe('createInputFieldSchema', () => {maxLength: 48,}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})it('should validate variable does not start with number', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const invalidData = {variable: '123var',@@ -1100,15 +871,12 @@ describe('createInputFieldSchema', () => {maxLength: 48,}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})it('should validate variable format (alphanumeric and underscore)', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const invalidData = {variable: 'var-name',@@ -1118,15 +886,12 @@ describe('createInputFieldSchema', () => {maxLength: 48,}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})it('should accept valid variable name', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'valid_var_123',@@ -1136,15 +901,12 @@ describe('createInputFieldSchema', () => {maxLength: 48,}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})it('should validate required label field', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const invalidData = {variable: 'test_var',@@ -1154,20 +916,14 @@ describe('createInputFieldSchema', () => {maxLength: 48,}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})})- // -------------------------------------------------------------------------- // Text Input Schema Tests- // -------------------------------------------------------------------------describe('Text Input Schema', () => {it('should validate maxLength within bounds', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1177,15 +933,12 @@ describe('createInputFieldSchema', () => {maxLength: 100,}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})it('should reject maxLength exceeding TEXT_MAX_LENGTH', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const invalidData = {variable: 'test_var',@@ -1195,15 +948,12 @@ describe('createInputFieldSchema', () => {maxLength: TEXT_MAX_LENGTH + 1,}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})it('should reject maxLength less than 1', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const invalidData = {variable: 'test_var',@@ -1213,15 +963,12 @@ describe('createInputFieldSchema', () => {maxLength: 0,}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})it('should allow optional default value', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1232,20 +979,14 @@ describe('createInputFieldSchema', () => {default: 'default value',}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})})- // -------------------------------------------------------------------------- // Paragraph Schema Tests- // -------------------------------------------------------------------------describe('Paragraph Schema', () => {it('should validate paragraph type similar to textInput', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.paragraph, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1255,20 +996,14 @@ describe('createInputFieldSchema', () => {maxLength: 100,}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})})- // -------------------------------------------------------------------------- // Number Schema Tests- // -------------------------------------------------------------------------describe('Number Schema', () => {it('should allow optional default number', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.number, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1278,15 +1013,12 @@ describe('createInputFieldSchema', () => {default: 42,}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})it('should allow optional unit', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.number, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1296,20 +1028,14 @@ describe('createInputFieldSchema', () => {unit: 'kg',}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})})- // -------------------------------------------------------------------------- // Select Schema Tests- // -------------------------------------------------------------------------describe('Select Schema', () => {it('should require non-empty options array', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.select, mockT, { maxFileUploadLimit: 10 })const invalidData = {variable: 'test_var',@@ -1319,15 +1045,12 @@ describe('createInputFieldSchema', () => {options: [],}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})it('should accept valid options array', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.select, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1337,15 +1060,12 @@ describe('createInputFieldSchema', () => {options: ['Option 1', 'Option 2'],}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})it('should reject duplicate options', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.select, mockT, { maxFileUploadLimit: 10 })const invalidData = {variable: 'test_var',@@ -1355,20 +1075,14 @@ describe('createInputFieldSchema', () => {options: ['Option 1', 'Option 1'],}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})})- // -------------------------------------------------------------------------- // Single File Schema Tests- // -------------------------------------------------------------------------describe('Single File Schema', () => {it('should validate allowedFileUploadMethods', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.singleFile, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1381,15 +1095,12 @@ describe('createInputFieldSchema', () => {},}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})it('should validate allowedTypesAndExtensions', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.singleFile, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1403,20 +1114,14 @@ describe('createInputFieldSchema', () => {},}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})})- // -------------------------------------------------------------------------- // Multi Files Schema Tests- // -------------------------------------------------------------------------describe('Multi Files Schema', () => {it('should validate maxLength within file upload limit', () => {- // Arrangeconst maxFileUploadLimit = 10const schema = createInputFieldSchema(PipelineInputVarType.multiFiles, mockT, { maxFileUploadLimit })const validData = {@@ -1431,15 +1136,12 @@ describe('createInputFieldSchema', () => {maxLength: 5,}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})it('should reject maxLength exceeding file upload limit', () => {- // Arrangeconst maxFileUploadLimit = 10const schema = createInputFieldSchema(PipelineInputVarType.multiFiles, mockT, { maxFileUploadLimit })const invalidData = {@@ -1454,20 +1156,14 @@ describe('createInputFieldSchema', () => {maxLength: 15,}- // Actconst result = schema.safeParse(invalidData)- // Assertexpect(result.success).toBe(false)})})- // -------------------------------------------------------------------------- // Default Schema Tests (for checkbox and other types)- // -------------------------------------------------------------------------describe('Default Schema', () => {it('should validate checkbox type with common schema', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.checkbox, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1476,15 +1172,12 @@ describe('createInputFieldSchema', () => {type: 'checkbox',}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)})it('should allow passthrough of additional fields', () => {- // Arrangeconst schema = createInputFieldSchema(PipelineInputVarType.checkbox, mockT, { maxFileUploadLimit: 10 })const validData = {variable: 'test_var',@@ -1494,10 +1187,8 @@ describe('createInputFieldSchema', () => {extraField: 'extra value',}- // Actconst result = schema.safeParse(validData)- // Assertexpect(result.success).toBe(true)if (result.success) {expect((result.data as Record<string, unknown>).extraField).toBe('extra value')@@ -1506,14 +1197,9 @@ describe('createInputFieldSchema', () => {})})-// ============================================================================-// Types Tests-// ============================================================================-describe('Types', () => {describe('FormData type', () => {it('should have correct structure', () => {- // This is a compile-time check, but we can verify at runtime tooconst formData: FormData = {type: PipelineInputVarType.textInput,label: 'Test',@@ -1584,10 +1270,6 @@ describe('Types', () => {})})-// ============================================================================-// TEXT_MAX_LENGTH Constant Tests-// ============================================================================-describe('TEXT_MAX_LENGTH', () => {it('should be a positive number', () => {expect(TEXT_MAX_LENGTH).toBeGreaterThan(0)@@ -1598,78 +1280,55 @@ describe('TEXT_MAX_LENGTH', () => {})})-// ============================================================================-// InitialFields Component Tests-// ============================================================================-describe('InitialFields', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render InitialFields component without crashing', () => {- // Arrangeconst initialData = createFormData()const props = createInputFieldFormProps({ initialData })- // Actconst { container } = renderWithProviders(<InputFieldForm {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // getFieldValue and setFieldValue Callbacks Tests- // -------------------------------------------------------------------------describe('getFieldValue and setFieldValue Callbacks', () => {it('should trigger getFieldValue when variable name blur event fires with empty label', async () => {- // Arrange - Create initial data with empty labelconst initialData = createFormData({variable: '',label: '', // Empty label to trigger the condition})const props = createInputFieldFormProps({ initialData })- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Find the variable input and trigger blur with a valueconst variableInput = screen.getByLabelText('appDebug.variableConfig.varName')fireEvent.change(variableInput, { target: { value: 'test_var' } })fireEvent.blur(variableInput)- // Assert - The label field should be updated via setFieldValue when variable blurs- // The getFieldValue is called to check if label is emptyawait waitFor(() => {const labelInput = screen.getByLabelText('appDebug.variableConfig.displayName')- // Label should be set to the variable value when it was emptyexpect(labelInput).toHaveValue('test_var')})})it('should not update label when it already has a value on variable blur', async () => {- // Arrange - Create initial data with existing labelconst initialData = createFormData({variable: '',label: 'Existing Label', // Label already has value})const props = createInputFieldFormProps({ initialData })- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Find the variable input and trigger blur with a valueconst variableInput = screen.getByLabelText('appDebug.variableConfig.varName')fireEvent.change(variableInput, { target: { value: 'new_var' } })fireEvent.blur(variableInput)- // Assert - The label field should remain unchanged because it already has a valueawait waitFor(() => {const labelInput = screen.getByLabelText('appDebug.variableConfig.displayName')expect(labelInput).toHaveValue('Existing Label')@@ -1677,44 +1336,36 @@ describe('InitialFields', () => {})it('should trigger setFieldValue when display name blur event fires with empty value', async () => {- // Arrange - Create initial data with a variable but we will clear the labelconst initialData = createFormData({variable: 'original_var',label: 'Some Label',})const props = createInputFieldFormProps({ initialData })- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Find the label input, clear it, and trigger blurconst labelInput = screen.getByLabelText('appDebug.variableConfig.displayName')fireEvent.change(labelInput, { target: { value: '' } })fireEvent.blur(labelInput)- // Assert - When label is cleared and blurred, it should be reset to variable nameawait waitFor(() => {expect(labelInput).toHaveValue('original_var')})})it('should keep label value when display name blur event fires with non-empty value', async () => {- // Arrangeconst initialData = createFormData({variable: 'test_var',label: 'Original Label',})const props = createInputFieldFormProps({ initialData })- // ActrenderWithProviders(<InputFieldForm {...props} />)- // Find the label input, change it to a new value, and trigger blurconst labelInput = screen.getByLabelText('appDebug.variableConfig.displayName')fireEvent.change(labelInput, { target: { value: 'New Label' } })fireEvent.blur(labelInput)- // Assert - Label should keep the new non-empty valueawait waitFor(() => {expect(labelInput).toHaveValue('New Label')})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/schema.spec.ts b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/schema.spec.tsnew file mode 100644index 00000000000..d554f9653e0--- /dev/null+++ b/web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/schema.spec.ts@@ -0,0 +1,260 @@+import type { TFunction } from 'i18next'+import { describe, expect, it, vi } from 'vitest'+import { PipelineInputVarType } from '@/models/pipeline'+import { createInputFieldSchema, TEXT_MAX_LENGTH } from '../schema'++vi.mock('@/config', () => ({+ MAX_VAR_KEY_LENGTH: 30,+}))++const t: TFunction = ((key: string) => key) as unknown as TFunction++const defaultOptions = { maxFileUploadLimit: 10 }++describe('TEXT_MAX_LENGTH', () => {+ it('should be 256', () => {+ expect(TEXT_MAX_LENGTH).toBe(256)+ })+})++describe('createInputFieldSchema', () => {+ describe('common schema validation', () => {+ it('should reject empty variable name', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.textInput, t, defaultOptions)+ const result = schema.safeParse({+ type: 'text-input',+ variable: '',+ label: 'Test',+ required: false,+ maxLength: 48,+ })++ expect(result.success).toBe(false)+ })++ it('should reject variable starting with number', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.textInput, t, defaultOptions)+ const result = schema.safeParse({+ type: 'text-input',+ variable: '123abc',+ label: 'Test',+ required: false,+ maxLength: 48,+ })++ expect(result.success).toBe(false)+ })++ it('should accept valid variable name', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.textInput, t, defaultOptions)+ const result = schema.safeParse({+ type: 'text-input',+ variable: 'valid_var',+ label: 'Test',+ required: false,+ maxLength: 48,+ })++ expect(result.success).toBe(true)+ })++ it('should reject empty label', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.textInput, t, defaultOptions)+ const result = schema.safeParse({+ type: 'text-input',+ variable: 'my_var',+ label: '',+ required: false,+ maxLength: 48,+ })++ expect(result.success).toBe(false)+ })+ })++ describe('text input type', () => {+ it('should validate maxLength within range', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.textInput, t, defaultOptions)++ const valid = schema.safeParse({+ type: 'text-input',+ variable: 'text_var',+ label: 'Text',+ required: false,+ maxLength: 100,+ })+ expect(valid.success).toBe(true)++ const tooLow = schema.safeParse({+ type: 'text-input',+ variable: 'text_var',+ label: 'Text',+ required: false,+ maxLength: 0,+ })+ expect(tooLow.success).toBe(false)+ })++ it('should allow optional default and tooltips', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.textInput, t, defaultOptions)+ const result = schema.safeParse({+ type: 'text-input',+ variable: 'text_var',+ label: 'Text',+ required: false,+ maxLength: 48,+ default: 'default value',+ tooltips: 'Some help text',+ })++ expect(result.success).toBe(true)+ })+ })++ describe('paragraph type', () => {+ it('should use same schema as text input', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.paragraph, t, defaultOptions)+ const result = schema.safeParse({+ type: 'paragraph',+ variable: 'para_var',+ label: 'Paragraph',+ required: false,+ maxLength: 100,+ })++ expect(result.success).toBe(true)+ })+ })++ describe('number type', () => {+ it('should allow optional unit and placeholder', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.number, t, defaultOptions)+ const result = schema.safeParse({+ type: 'number',+ variable: 'num_var',+ label: 'Number',+ required: false,+ default: 42,+ unit: 'kg',+ placeholder: 'Enter weight',+ })++ expect(result.success).toBe(true)+ })+ })++ describe('select type', () => {+ it('should require non-empty options array', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.select, t, defaultOptions)++ const empty = schema.safeParse({+ type: 'select',+ variable: 'sel_var',+ label: 'Select',+ required: false,+ options: [],+ })+ expect(empty.success).toBe(false)++ const valid = schema.safeParse({+ type: 'select',+ variable: 'sel_var',+ label: 'Select',+ required: false,+ options: ['opt1', 'opt2'],+ })+ expect(valid.success).toBe(true)+ })++ it('should reject duplicate options', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.select, t, defaultOptions)+ const result = schema.safeParse({+ type: 'select',+ variable: 'sel_var',+ label: 'Select',+ required: false,+ options: ['opt1', 'opt1'],+ })++ expect(result.success).toBe(false)+ })+ })++ describe('singleFile type', () => {+ it('should require file upload methods and types', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.singleFile, t, defaultOptions)+ const result = schema.safeParse({+ type: 'file',+ variable: 'file_var',+ label: 'File',+ required: false,+ allowedFileUploadMethods: ['local_file'],+ allowedTypesAndExtensions: {+ allowedFileTypes: ['document'],+ },+ })++ expect(result.success).toBe(true)+ })+ })++ describe('multiFiles type', () => {+ it('should validate maxLength against maxFileUploadLimit', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.multiFiles, t, { maxFileUploadLimit: 5 })++ const valid = schema.safeParse({+ type: 'file-list',+ variable: 'files_var',+ label: 'Files',+ required: false,+ allowedFileUploadMethods: ['local_file'],+ allowedTypesAndExtensions: {+ allowedFileTypes: ['image'],+ },+ maxLength: 3,+ })+ expect(valid.success).toBe(true)++ const tooMany = schema.safeParse({+ type: 'file-list',+ variable: 'files_var',+ label: 'Files',+ required: false,+ allowedFileUploadMethods: ['local_file'],+ allowedTypesAndExtensions: {+ allowedFileTypes: ['image'],+ },+ maxLength: 10,+ })+ expect(tooMany.success).toBe(false)+ })+ })++ describe('checkbox / default type', () => {+ it('should use common schema for checkbox type', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.checkbox, t, defaultOptions)+ const result = schema.safeParse({+ type: 'checkbox',+ variable: 'check_var',+ label: 'Agree',+ required: true,+ })++ expect(result.success).toBe(true)+ })++ it('should allow passthrough of extra fields', () => {+ const schema = createInputFieldSchema(PipelineInputVarType.checkbox, t, defaultOptions)+ const result = schema.safeParse({+ type: 'checkbox',+ variable: 'check_var',+ label: 'Agree',+ required: true,+ default: true,+ extraField: 'should pass through',+ })++ expect(result.success).toBe(true)+ })+ })+})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/hooks.spec.ts b/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/hooks.spec.tsnew file mode 100644index 00000000000..f53222c7d5c--- /dev/null+++ b/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/hooks.spec.ts@@ -0,0 +1,371 @@+import type { InputVar } from '@/models/pipeline'+import { renderHook } from '@testing-library/react'+import { act } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { useFieldList } from '../hooks'++const mockToggleInputFieldEditPanel = vi.fn()+vi.mock('@/app/components/rag-pipeline/hooks', () => ({+ useInputFieldPanel: () => ({+ toggleInputFieldEditPanel: mockToggleInputFieldEditPanel,+ }),+}))++const mockHandleInputVarRename = vi.fn()+const mockIsVarUsedInNodes = vi.fn()+const mockRemoveUsedVarInNodes = vi.fn()+vi.mock('../../../../../hooks/use-pipeline', () => ({+ usePipeline: () => ({+ handleInputVarRename: mockHandleInputVarRename,+ isVarUsedInNodes: mockIsVarUsedInNodes,+ removeUsedVarInNodes: mockRemoveUsedVarInNodes,+ }),+}))++const mockToastNotify = vi.fn()+vi.mock('@/app/components/base/toast', () => ({+ default: {+ notify: (...args: unknown[]) => mockToastNotify(...args),+ },+}))++vi.mock('@/app/components/workflow/types', () => ({+ ChangeType: {+ changeVarName: 'changeVarName',+ remove: 'remove',+ },+}))++function createInputVar(overrides?: Partial<InputVar>): InputVar {+ return {+ type: 'text-input',+ variable: 'test_var',+ label: 'Test Var',+ required: false,+ ...overrides,+ } as InputVar+}++function createDefaultProps(overrides?: Partial<Parameters<typeof useFieldList>[0]>) {+ return {+ initialInputFields: [] as InputVar[],+ onInputFieldsChange: vi.fn(),+ nodeId: 'node-1',+ allVariableNames: [] as string[],+ ...overrides,+ }+}++describe('useFieldList', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockIsVarUsedInNodes.mockReturnValue(false)+ })++ afterEach(() => {+ vi.clearAllMocks()+ })++ describe('initialization', () => {+ it('should return inputFields from initialInputFields', () => {+ const fields = [createInputVar({ variable: 'var1' })]+ const { result } = renderHook(() => useFieldList(createDefaultProps({ initialInputFields: fields })))++ expect(result.current.inputFields).toEqual(fields)+ })++ it('should return empty inputFields when initialized with empty array', () => {+ const { result } = renderHook(() => useFieldList(createDefaultProps()))++ expect(result.current.inputFields).toEqual([])+ })++ it('should return all expected functions', () => {+ const { result } = renderHook(() => useFieldList(createDefaultProps()))++ expect(typeof result.current.handleListSortChange).toBe('function')+ expect(typeof result.current.handleRemoveField).toBe('function')+ expect(typeof result.current.handleOpenInputFieldEditor).toBe('function')+ expect(typeof result.current.hideRemoveVarConfirm).toBe('function')+ expect(typeof result.current.onRemoveVarConfirm).toBe('function')+ })++ it('should have isShowRemoveVarConfirm as false initially', () => {+ const { result } = renderHook(() => useFieldList(createDefaultProps()))++ expect(result.current.isShowRemoveVarConfirm).toBe(false)+ })+ })++ describe('handleListSortChange', () => {+ it('should reorder input fields and notify parent', () => {+ const var1 = createInputVar({ variable: 'var1', label: 'V1' })+ const var2 = createInputVar({ variable: 'var2', label: 'V2' })+ const onInputFieldsChange = vi.fn()+ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({+ initialInputFields: [var1, var2],+ onInputFieldsChange,+ })),+ )++ act(() => {+ result.current.handleListSortChange([+ { ...var2, id: '1', chosen: false, selected: false },+ { ...var1, id: '0', chosen: false, selected: false },+ ])+ })++ expect(onInputFieldsChange).toHaveBeenCalledWith([var2, var1])+ })++ it('should strip sortable metadata (id, chosen, selected) from items', () => {+ const var1 = createInputVar({ variable: 'var1' })+ const onInputFieldsChange = vi.fn()+ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({+ initialInputFields: [var1],+ onInputFieldsChange,+ })),+ )++ act(() => {+ result.current.handleListSortChange([+ { ...var1, id: '0', chosen: true, selected: true },+ ])+ })++ const updatedFields = onInputFieldsChange.mock.calls[0][0]+ expect(updatedFields[0]).not.toHaveProperty('id')+ expect(updatedFields[0]).not.toHaveProperty('chosen')+ expect(updatedFields[0]).not.toHaveProperty('selected')+ })+ })++ describe('handleRemoveField', () => {+ it('should remove field when variable is not used in nodes', () => {+ const var1 = createInputVar({ variable: 'var1' })+ const var2 = createInputVar({ variable: 'var2' })+ const onInputFieldsChange = vi.fn()+ mockIsVarUsedInNodes.mockReturnValue(false)++ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({+ initialInputFields: [var1, var2],+ onInputFieldsChange,+ })),+ )++ act(() => {+ result.current.handleRemoveField(0)+ })++ expect(onInputFieldsChange).toHaveBeenCalledWith([var2])+ })++ it('should show confirmation when variable is used in other nodes', () => {+ const var1 = createInputVar({ variable: 'used_var' })+ const onInputFieldsChange = vi.fn()+ mockIsVarUsedInNodes.mockReturnValue(true)++ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({+ initialInputFields: [var1],+ onInputFieldsChange,+ })),+ )++ act(() => {+ result.current.handleRemoveField(0)+ })++ expect(result.current.isShowRemoveVarConfirm).toBe(true)+ expect(onInputFieldsChange).not.toHaveBeenCalled()+ })+ })++ describe('onRemoveVarConfirm', () => {+ it('should remove field and clean up variable references after confirmation', () => {+ const var1 = createInputVar({ variable: 'used_var' })+ const onInputFieldsChange = vi.fn()+ mockIsVarUsedInNodes.mockReturnValue(true)++ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({+ initialInputFields: [var1],+ onInputFieldsChange,+ nodeId: 'node-1',+ })),+ )++ act(() => {+ result.current.handleRemoveField(0)+ })++ expect(result.current.isShowRemoveVarConfirm).toBe(true)++ act(() => {+ result.current.onRemoveVarConfirm()+ })++ expect(onInputFieldsChange).toHaveBeenCalledWith([])+ expect(mockRemoveUsedVarInNodes).toHaveBeenCalledWith(['rag', 'node-1', 'used_var'])+ expect(result.current.isShowRemoveVarConfirm).toBe(false)+ })+ })++ describe('handleOpenInputFieldEditor', () => {+ it('should open editor with existing field data when id matches', () => {+ const var1 = createInputVar({ variable: 'var1', label: 'Label 1' })+ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({ initialInputFields: [var1] })),+ )++ act(() => {+ result.current.handleOpenInputFieldEditor('var1')+ })++ expect(mockToggleInputFieldEditPanel).toHaveBeenCalledWith(+ expect.objectContaining({+ initialData: var1,+ }),+ )+ })++ it('should open editor for new field when id does not match', () => {+ const { result } = renderHook(() =>+ useFieldList(createDefaultProps()),+ )++ act(() => {+ result.current.handleOpenInputFieldEditor('non-existent')+ })++ expect(mockToggleInputFieldEditPanel).toHaveBeenCalledWith(+ expect.objectContaining({+ initialData: undefined,+ }),+ )+ })++ it('should open editor for new field when no id provided', () => {+ const { result } = renderHook(() =>+ useFieldList(createDefaultProps()),+ )++ act(() => {+ result.current.handleOpenInputFieldEditor()+ })++ expect(mockToggleInputFieldEditPanel).toHaveBeenCalledWith(+ expect.objectContaining({+ initialData: undefined,+ }),+ )+ })+ })++ describe('field submission (via editor)', () => {+ it('should add new field when editingFieldIndex is -1', () => {+ const onInputFieldsChange = vi.fn()+ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({ onInputFieldsChange })),+ )++ act(() => {+ result.current.handleOpenInputFieldEditor()+ })++ const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]+ const newField = createInputVar({ variable: 'new_var', label: 'New' })++ act(() => {+ editorProps.onSubmit(newField)+ })++ expect(onInputFieldsChange).toHaveBeenCalledWith([newField])+ })++ it('should show error toast for duplicate variable names', () => {+ const var1 = createInputVar({ variable: 'existing_var' })+ const onInputFieldsChange = vi.fn()+ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({+ initialInputFields: [var1],+ onInputFieldsChange,+ allVariableNames: ['existing_var'],+ })),+ )++ act(() => {+ result.current.handleOpenInputFieldEditor()+ })++ const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]+ const duplicateField = createInputVar({ variable: 'existing_var' })++ act(() => {+ editorProps.onSubmit(duplicateField)+ })++ expect(mockToastNotify).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'error' }),+ )+ expect(onInputFieldsChange).not.toHaveBeenCalled()+ })++ it('should trigger variable rename when ChangeType is changeVarName', () => {+ const var1 = createInputVar({ variable: 'old_name' })+ const onInputFieldsChange = vi.fn()+ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({+ initialInputFields: [var1],+ onInputFieldsChange,+ nodeId: 'node-1',+ allVariableNames: ['old_name'],+ })),+ )++ act(() => {+ result.current.handleOpenInputFieldEditor('old_name')+ })++ const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]+ const updatedField = createInputVar({ variable: 'new_name' })++ act(() => {+ editorProps.onSubmit(updatedField, {+ type: 'changeVarName',+ payload: { beforeKey: 'old_name', afterKey: 'new_name' },+ })+ })++ expect(mockHandleInputVarRename).toHaveBeenCalledWith(+ 'node-1',+ ['rag', 'node-1', 'old_name'],+ ['rag', 'node-1', 'new_name'],+ )+ })+ })++ describe('hideRemoveVarConfirm', () => {+ it('should hide the confirmation dialog', () => {+ const var1 = createInputVar({ variable: 'used_var' })+ mockIsVarUsedInNodes.mockReturnValue(true)++ const { result } = renderHook(() =>+ useFieldList(createDefaultProps({ initialInputFields: [var1] })),+ )++ act(() => {+ result.current.handleRemoveField(0)+ })+ expect(result.current.isShowRemoveVarConfirm).toBe(true)++ act(() => {+ result.current.hideRemoveVarConfirm()+ })+ expect(result.current.isShowRemoveVarConfirm).toBe(false)+ })+ })+})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/field-list/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/index.spec.tsxsimilarity index 80%rename from web/app/components/rag-pipeline/components/panel/input-field/field-list/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/index.spec.tsxindex f28173d2f13..b4332781a60 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/field-list/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/index.spec.tsx@@ -1,17 +1,12 @@-import type { SortableItem } from './types'+import type { SortableItem } from '../types'import type { InputVar } from '@/models/pipeline'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { PipelineInputVarType } from '@/models/pipeline'-import FieldItem from './field-item'-import FieldListContainer from './field-list-container'-import FieldList from './index'+import FieldItem from '../field-item'+import FieldListContainer from '../field-list-container'+import FieldList from '../index'-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock ahooks useHoverlet mockIsHovering = falseconst getMockIsHovering = () => mockIsHovering@@ -23,7 +18,6 @@ vi.mock('ahooks', async (importOriginal) => {}})-// Mock react-sortablejsvi.mock('react-sortablejs', () => ({ReactSortable: ({ children, list, setList, disabled, className }: {children: React.ReactNode@@ -42,7 +36,6 @@ vi.mock('react-sortablejs', () => ({data-testid="trigger-sort"onClick={() => {if (!disabled && list.length > 1) {- // Simulate reorder: swap first two itemsconst newList = [...list]const temp = newList[0]newList[0] = newList[1]@@ -56,7 +49,6 @@ vi.mock('react-sortablejs', () => ({<buttondata-testid="trigger-same-sort"onClick={() => {- // Trigger setList with same list (no actual change)setList([...list])}}>@@ -66,12 +58,11 @@ vi.mock('react-sortablejs', () => ({),}))-// Mock usePipeline hookconst mockHandleInputVarRename = vi.fn()const mockIsVarUsedInNodes = vi.fn(() => false)const mockRemoveUsedVarInNodes = vi.fn()-vi.mock('../../../../hooks/use-pipeline', () => ({+vi.mock('../../../../../hooks/use-pipeline', () => ({usePipeline: () => ({handleInputVarRename: mockHandleInputVarRename,isVarUsedInNodes: mockIsVarUsedInNodes,@@ -79,7 +70,6 @@ vi.mock('../../../../hooks/use-pipeline', () => ({}),}))-// Mock useInputFieldPanel hookconst mockToggleInputFieldEditPanel = vi.fn()vi.mock('@/app/components/rag-pipeline/hooks', () => ({@@ -88,14 +78,12 @@ vi.mock('@/app/components/rag-pipeline/hooks', () => ({}),}))-// Mock Toastvi.mock('@/app/components/base/toast', () => ({default: {notify: vi.fn(),},}))-// Mock RemoveEffectVarConfirmvi.mock('@/app/components/workflow/nodes/_base/components/remove-effect-var-confirm', () => ({default: ({isShow,@@ -115,10 +103,6 @@ vi.mock('@/app/components/workflow/nodes/_base/components/remove-effect-var-conf: null,}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createInputVar = (overrides?: Partial<InputVar>): InputVar => ({type: PipelineInputVarType.textInput,label: 'Test Label',@@ -155,25 +139,16 @@ const createSortableItem = (...overrides,})-// ============================================================================-// FieldItem Component Tests-// ============================================================================-describe('FieldItem', () => {beforeEach(() => {vi.clearAllMocks()mockIsHovering = false})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render field item with variable name', () => {- // Arrangeconst payload = createInputVar({ variable: 'my_field' })- // Actrender(<FieldItempayload={payload}@@ -183,15 +158,12 @@ describe('FieldItem', () => {/>,)- // Assertexpect(screen.getByText('my_field')).toBeInTheDocument()})it('should render field item with label when provided', () => {- // Arrangeconst payload = createInputVar({ variable: 'field', label: 'Field Label' })- // Actrender(<FieldItempayload={payload}@@ -201,15 +173,12 @@ describe('FieldItem', () => {/>,)- // Assertexpect(screen.getByText('Field Label')).toBeInTheDocument()})it('should not render label when empty', () => {- // Arrangeconst payload = createInputVar({ variable: 'field', label: '' })- // Actrender(<FieldItempayload={payload}@@ -219,16 +188,13 @@ describe('FieldItem', () => {/>,)- // Assertexpect(screen.queryByText('·')).not.toBeInTheDocument()})it('should render required badge when not hovering and required is true', () => {- // ArrangemockIsHovering = falseconst payload = createInputVar({ required: true })- // Actrender(<FieldItempayload={payload}@@ -238,16 +204,13 @@ describe('FieldItem', () => {/>,)- // Assertexpect(screen.getByText(/required/i)).toBeInTheDocument()})it('should not render required badge when required is false', () => {- // ArrangemockIsHovering = falseconst payload = createInputVar({ required: false })- // Actrender(<FieldItempayload={payload}@@ -257,16 +220,13 @@ describe('FieldItem', () => {/>,)- // Assertexpect(screen.queryByText(/required/i)).not.toBeInTheDocument()})it('should render InputField icon when not hovering', () => {- // ArrangemockIsHovering = falseconst payload = createInputVar()- // Actconst { container } = render(<FieldItempayload={payload}@@ -276,17 +236,14 @@ describe('FieldItem', () => {/>,)- // Assert - InputField icon should be present (not RiDraggable)const icons = container.querySelectorAll('svg')expect(icons.length).toBeGreaterThan(0)})it('should render drag icon when hovering and not readonly', () => {- // ArrangemockIsHovering = trueconst payload = createInputVar()- // Actconst { container } = render(<FieldItempayload={payload}@@ -297,17 +254,14 @@ describe('FieldItem', () => {/>,)- // Assert - RiDraggable icon should be presentconst icons = container.querySelectorAll('svg')expect(icons.length).toBeGreaterThan(0)})it('should render edit and delete buttons when hovering and not readonly', () => {- // ArrangemockIsHovering = trueconst payload = createInputVar()- // Actrender(<FieldItempayload={payload}@@ -318,17 +272,14 @@ describe('FieldItem', () => {/>,)- // Assertconst buttons = screen.getAllByRole('button')expect(buttons.length).toBe(2) // Edit and Delete buttons})it('should not render edit and delete buttons when readonly', () => {- // ArrangemockIsHovering = trueconst payload = createInputVar()- // Actrender(<FieldItempayload={payload}@@ -339,23 +290,17 @@ describe('FieldItem', () => {/>,)- // Assertconst buttons = screen.queryAllByRole('button')expect(buttons.length).toBe(0)})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onClickEdit with variable when edit button is clicked', () => {- // ArrangemockIsHovering = trueconst onClickEdit = vi.fn()const payload = createInputVar({ variable: 'test_var' })- // Actrender(<FieldItempayload={payload}@@ -367,17 +312,14 @@ describe('FieldItem', () => {const buttons = screen.getAllByRole('button')fireEvent.click(buttons[0]) // Edit button- // Assertexpect(onClickEdit).toHaveBeenCalledWith('test_var')})it('should call onRemove with index when delete button is clicked', () => {- // ArrangemockIsHovering = trueconst onRemove = vi.fn()const payload = createInputVar()- // Actrender(<FieldItempayload={payload}@@ -389,17 +331,14 @@ describe('FieldItem', () => {const buttons = screen.getAllByRole('button')fireEvent.click(buttons[1]) // Delete button- // Assertexpect(onRemove).toHaveBeenCalledWith(5)})it('should not call onClickEdit when readonly', () => {- // ArrangemockIsHovering = trueconst onClickEdit = vi.fn()const payload = createInputVar()- // Render without readonly to get buttons, then check behaviorconst { rerender } = render(<FieldItempayload={payload}@@ -410,7 +349,6 @@ describe('FieldItem', () => {/>,)- // Re-render with readonly but buttons still exist from previous state checkrerender(<FieldItempayload={payload}@@ -421,18 +359,15 @@ describe('FieldItem', () => {/>,)- // Assert - no buttons should be rendered when readonlyexpect(screen.queryAllByRole('button').length).toBe(0)})it('should stop event propagation when edit button is clicked', () => {- // ArrangemockIsHovering = trueconst onClickEdit = vi.fn()const parentClick = vi.fn()const payload = createInputVar()- // Actrender(<div onClick={parentClick}><FieldItem@@ -446,19 +381,16 @@ describe('FieldItem', () => {const buttons = screen.getAllByRole('button')fireEvent.click(buttons[0])- // Assert - parent click should not be called due to stopPropagationexpect(onClickEdit).toHaveBeenCalled()expect(parentClick).not.toHaveBeenCalled()})it('should stop event propagation when delete button is clicked', () => {- // ArrangemockIsHovering = trueconst onRemove = vi.fn()const parentClick = vi.fn()const payload = createInputVar()- // Actrender(<div onClick={parentClick}><FieldItem@@ -472,23 +404,17 @@ describe('FieldItem', () => {const buttons = screen.getAllByRole('button')fireEvent.click(buttons[1])- // Assertexpect(onRemove).toHaveBeenCalled()expect(parentClick).not.toHaveBeenCalled()})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain stable handleOnClickEdit when props dont change', () => {- // ArrangemockIsHovering = trueconst onClickEdit = vi.fn()const payload = createInputVar()- // Actconst { rerender } = render(<FieldItempayload={payload}@@ -511,21 +437,15 @@ describe('FieldItem', () => {const buttonsAfterRerender = screen.getAllByRole('button')fireEvent.click(buttonsAfterRerender[0])- // Assertexpect(onClickEdit).toHaveBeenCalledTimes(2)})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle very long variable names with truncation', () => {- // Arrangeconst longVariable = 'a'.repeat(200)const payload = createInputVar({ variable: longVariable })- // Actrender(<FieldItempayload={payload}@@ -535,17 +455,14 @@ describe('FieldItem', () => {/>,)- // Assertconst varElement = screen.getByTitle(longVariable)expect(varElement).toHaveClass('truncate')})it('should handle very long label names with truncation', () => {- // Arrangeconst longLabel = 'b'.repeat(200)const payload = createInputVar({ label: longLabel })- // Actrender(<FieldItempayload={payload}@@ -555,19 +472,16 @@ describe('FieldItem', () => {/>,)- // Assertconst labelElement = screen.getByTitle(longLabel)expect(labelElement).toHaveClass('truncate')})it('should handle special characters in variable and label', () => {- // Arrangeconst payload = createInputVar({variable: '<test>&"var\'',label: '<label>&"test\'',})- // Actrender(<FieldItempayload={payload}@@ -577,19 +491,16 @@ describe('FieldItem', () => {/>,)- // Assertexpect(screen.getByText('<test>&"var\'')).toBeInTheDocument()expect(screen.getByText('<label>&"test\'')).toBeInTheDocument()})it('should handle unicode characters', () => {- // Arrangeconst payload = createInputVar({variable: '变量_🎉',label: '标签_😀',})- // Actrender(<FieldItempayload={payload}@@ -599,13 +510,11 @@ describe('FieldItem', () => {/>,)- // Assertexpect(screen.getByText('变量_🎉')).toBeInTheDocument()expect(screen.getByText('标签_😀')).toBeInTheDocument()})it('should render different input types correctly', () => {- // Arrangeconst types = [PipelineInputVarType.textInput,PipelineInputVarType.paragraph,@@ -619,7 +528,6 @@ describe('FieldItem', () => {types.forEach((type) => {const payload = createInputVar({ type })- // Actconst { unmount } = render(<FieldItempayload={payload}@@ -629,24 +537,18 @@ describe('FieldItem', () => {/>,)- // Assertexpect(screen.getByText('test_variable')).toBeInTheDocument()unmount()})})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be memoized with React.memo', () => {- // Arrangeconst payload = createInputVar()const onClickEdit = vi.fn()const onRemove = vi.fn()- // Actconst { rerender } = render(<FieldItempayload={payload}@@ -656,7 +558,6 @@ describe('FieldItem', () => {/>,)- // Rerender with same propsrerender(<FieldItempayload={payload}@@ -666,21 +567,15 @@ describe('FieldItem', () => {/>,)- // Assert - component should still render correctlyexpect(screen.getByText('test_variable')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Readonly Mode Behavior Tests- // -------------------------------------------------------------------------describe('Readonly Mode Behavior', () => {it('should not render action buttons in readonly mode even when hovering', () => {- // ArrangemockIsHovering = trueconst payload = createInputVar()- // Actrender(<FieldItempayload={payload}@@ -691,16 +586,13 @@ describe('FieldItem', () => {/>,)- // Assert - no action buttons should be renderedexpect(screen.queryAllByRole('button')).toHaveLength(0)})it('should render type icon and required badge in readonly mode when hovering', () => {- // ArrangemockIsHovering = trueconst payload = createInputVar({ required: true })- // Actrender(<FieldItempayload={payload}@@ -711,15 +603,12 @@ describe('FieldItem', () => {/>,)- // Assert - required badge should be visible instead of action buttonsexpect(screen.getByText(/required/i)).toBeInTheDocument()})it('should apply cursor-default class when readonly', () => {- // Arrangeconst payload = createInputVar()- // Actconst { container } = render(<FieldItempayload={payload}@@ -730,17 +619,14 @@ describe('FieldItem', () => {/>,)- // Assertconst fieldItem = container.firstChild as HTMLElementexpect(fieldItem.className).toContain('cursor-default')})it('should apply cursor-all-scroll class when hovering and not readonly', () => {- // ArrangemockIsHovering = trueconst payload = createInputVar()- // Actconst { container } = render(<FieldItempayload={payload}@@ -751,32 +637,22 @@ describe('FieldItem', () => {/>,)- // Assertconst fieldItem = container.firstChild as HTMLElementexpect(fieldItem.className).toContain('cursor-all-scroll')})})})-// ============================================================================-// FieldListContainer Component Tests-// ============================================================================-describe('FieldListContainer', () => {beforeEach(() => {vi.clearAllMocks()mockIsHovering = false})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render sortable container', () => {- // Arrangeconst inputFields = createInputVarList(2)- // Actrender(<FieldListContainerinputFields={inputFields}@@ -786,15 +662,12 @@ describe('FieldListContainer', () => {/>,)- // Assertexpect(screen.getByTestId('sortable-container')).toBeInTheDocument()})it('should render all field items', () => {- // Arrangeconst inputFields = createInputVarList(3)- // Actrender(<FieldListContainerinputFields={inputFields}@@ -804,14 +677,12 @@ describe('FieldListContainer', () => {/>,)- // Assertexpect(screen.getByText('var_0')).toBeInTheDocument()expect(screen.getByText('var_1')).toBeInTheDocument()expect(screen.getByText('var_2')).toBeInTheDocument()})it('should render empty list without errors', () => {- // Actrender(<FieldListContainerinputFields={[]}@@ -821,15 +692,12 @@ describe('FieldListContainer', () => {/>,)- // Assertexpect(screen.getByTestId('sortable-container')).toBeInTheDocument()})it('should apply custom className', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actrender(<FieldListContainerclassName="custom-class"@@ -840,16 +708,13 @@ describe('FieldListContainer', () => {/>,)- // Assertconst container = screen.getByTestId('sortable-container')expect(container.className).toContain('custom-class')})it('should disable sorting when readonly is true', () => {- // Arrangeconst inputFields = createInputVarList(2)- // Actrender(<FieldListContainerinputFields={inputFields}@@ -860,22 +725,16 @@ describe('FieldListContainer', () => {/>,)- // Assertconst container = screen.getByTestId('sortable-container')expect(container.dataset.disabled).toBe('true')})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onListSortChange when items are reordered', () => {- // Arrangeconst inputFields = createInputVarList(2)const onListSortChange = vi.fn()- // Actrender(<FieldListContainerinputFields={inputFields}@@ -886,16 +745,13 @@ describe('FieldListContainer', () => {)fireEvent.click(screen.getByTestId('trigger-sort'))- // Assertexpect(onListSortChange).toHaveBeenCalled()})it('should not call onListSortChange when list hasnt changed', () => {- // Arrangeconst inputFields = [createInputVar()]const onListSortChange = vi.fn()- // Actrender(<FieldListContainerinputFields={inputFields}@@ -906,16 +762,13 @@ describe('FieldListContainer', () => {)fireEvent.click(screen.getByTestId('trigger-sort'))- // Assert - with only one item, no reorder happensexpect(onListSortChange).not.toHaveBeenCalled()})it('should not call onListSortChange when disabled', () => {- // Arrangeconst inputFields = createInputVarList(2)const onListSortChange = vi.fn()- // Actrender(<FieldListContainerinputFields={inputFields}@@ -927,16 +780,13 @@ describe('FieldListContainer', () => {)fireEvent.click(screen.getByTestId('trigger-sort'))- // Assertexpect(onListSortChange).not.toHaveBeenCalled()})it('should not call onListSortChange when list order is unchanged (isEqual check)', () => {- // Arrange - This tests line 42 in field-list-container.tsxconst inputFields = createInputVarList(2)const onListSortChange = vi.fn()- // Actrender(<FieldListContainerinputFields={inputFields}@@ -945,20 +795,16 @@ describe('FieldListContainer', () => {onEditField={vi.fn()}/>,)- // Trigger same sort - passes same list to setListfireEvent.click(screen.getByTestId('trigger-same-sort'))- // Assert - onListSortChange should NOT be called due to isEqual checkexpect(onListSortChange).not.toHaveBeenCalled()})it('should pass onEditField to FieldItem', () => {- // ArrangemockIsHovering = trueconst inputFields = createInputVarList(1)const onEditField = vi.fn()- // Actrender(<FieldListContainerinputFields={inputFields}@@ -970,17 +816,14 @@ describe('FieldListContainer', () => {const buttons = screen.getAllByRole('button')fireEvent.click(buttons[0]) // Edit button- // Assertexpect(onEditField).toHaveBeenCalledWith('var_0')})it('should pass onRemoveField to FieldItem', () => {- // ArrangemockIsHovering = trueconst inputFields = createInputVarList(1)const onRemoveField = vi.fn()- // Actrender(<FieldListContainerinputFields={inputFields}@@ -992,24 +835,18 @@ describe('FieldListContainer', () => {const buttons = screen.getAllByRole('button')fireEvent.click(buttons[1]) // Delete button- // Assertexpect(onRemoveField).toHaveBeenCalledWith(0)})})- // -------------------------------------------------------------------------- // List Conversion Tests- // -------------------------------------------------------------------------describe('List Conversion', () => {it('should convert InputVar[] to SortableItem[]', () => {- // Arrangeconst inputFields = [createInputVar({ variable: 'var1' }),createInputVar({ variable: 'var2' }),]const onListSortChange = vi.fn()- // Actrender(<FieldListContainerinputFields={inputFields}@@ -1020,7 +857,6 @@ describe('FieldListContainer', () => {)fireEvent.click(screen.getByTestId('trigger-sort'))- // Assert - onListSortChange should receive SortableItem[]expect(onListSortChange).toHaveBeenCalled()const calledWith = onListSortChange.mock.calls[0][0]expect(calledWith[0]).toHaveProperty('id')@@ -1029,16 +865,11 @@ describe('FieldListContainer', () => {})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should memoize list transformation', () => {- // Arrangeconst inputFields = createInputVarList(2)const onListSortChange = vi.fn()- // Actconst { rerender } = render(<FieldListContainerinputFields={inputFields}@@ -1057,15 +888,12 @@ describe('FieldListContainer', () => {/>,)- // Assert - component should still render correctlyexpect(screen.getByText('var_0')).toBeInTheDocument()})it('should be memoized with React.memo', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actconst { rerender } = render(<FieldListContainerinputFields={inputFields}@@ -1075,7 +903,6 @@ describe('FieldListContainer', () => {/>,)- // Rerender with same propsrerender(<FieldListContainerinputFields={inputFields}@@ -1085,20 +912,14 @@ describe('FieldListContainer', () => {/>,)- // Assertexpect(screen.getByText('var_0')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle large list of items', () => {- // Arrangeconst inputFields = createInputVarList(100)- // Actrender(<FieldListContainerinputFields={inputFields}@@ -1108,14 +929,11 @@ describe('FieldListContainer', () => {/>,)- // Assertexpect(screen.getByText('var_0')).toBeInTheDocument()expect(screen.getByText('var_99')).toBeInTheDocument()})it('should throw error when inputFields is undefined', () => {- // This test documents that undefined inputFields will cause an error- // In production, this should be prevented by TypeScriptexpect(() =>render(<FieldListContainer@@ -1130,10 +948,6 @@ describe('FieldListContainer', () => {})})-// ============================================================================-// FieldList Component Tests (Integration)-// ============================================================================-describe('FieldList', () => {beforeEach(() => {vi.clearAllMocks()@@ -1141,15 +955,10 @@ describe('FieldList', () => {mockIsVarUsedInNodes.mockReturnValue(false)})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render FieldList component', () => {- // Arrangeconst inputFields = createInputVarList(2)- // Actrender(<FieldListnodeId="node-1"@@ -1160,16 +969,13 @@ describe('FieldList', () => {/>,)- // Assertexpect(screen.getByText('Label Content')).toBeInTheDocument()expect(screen.getByText('var_0')).toBeInTheDocument()})it('should render add button', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -1180,7 +986,6 @@ describe('FieldList', () => {/>,)- // Assertconst addButton = screen.getAllByRole('button').find(btn =>btn.querySelector('svg'),)@@ -1188,10 +993,8 @@ describe('FieldList', () => {})it('should disable add button when readonly', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -1203,7 +1006,6 @@ describe('FieldList', () => {/>,)- // Assertconst addButton = screen.getAllByRole('button').find(btn =>btn.querySelector('svg'),)@@ -1211,10 +1013,8 @@ describe('FieldList', () => {})it('should apply custom labelClassName', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actconst { container } = render(<FieldListnodeId="node-1"@@ -1226,21 +1026,15 @@ describe('FieldList', () => {/>,)- // Assertconst labelContainer = container.querySelector('.custom-label-class')expect(labelContainer).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should open editor panel when add button is clicked', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -1256,15 +1050,12 @@ describe('FieldList', () => {if (addButton)fireEvent.click(addButton)- // Assertexpect(mockToggleInputFieldEditPanel).toHaveBeenCalled()})it('should not open editor when readonly and add button clicked', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -1281,21 +1072,15 @@ describe('FieldList', () => {if (addButton)fireEvent.click(addButton)- // Assert - button is disabled so click shouldnt workexpect(mockToggleInputFieldEditPanel).not.toHaveBeenCalled()})})- // -------------------------------------------------------------------------- // Callback Tests- // -------------------------------------------------------------------------describe('Callback Handling', () => {it('should call handleInputFieldsChange with nodeId when fields change', () => {- // Arrangeconst inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-123"@@ -1305,10 +1090,8 @@ describe('FieldList', () => {allVariableNames={[]}/>,)- // Trigger sort to cause fields changefireEvent.click(screen.getByTestId('trigger-sort'))- // Assertexpect(handleInputFieldsChange).toHaveBeenCalledWith('node-123',expect.any(Array),@@ -1316,17 +1099,12 @@ describe('FieldList', () => {})})- // -------------------------------------------------------------------------- // Remove Confirmation Tests- // -------------------------------------------------------------------------describe('Remove Confirmation', () => {it('should show remove confirmation when variable is used in nodes', async () => {- // ArrangemockIsVarUsedInNodes.mockReturnValue(true)mockIsHovering = trueconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -1337,26 +1115,21 @@ describe('FieldList', () => {/>,)- // Find all buttons in the sortable container (edit and delete)const sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')- // The second button should be the delete buttonif (fieldItemButtons.length >= 2)fireEvent.click(fieldItemButtons[1])- // Assertawait waitFor(() => {expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()})})it('should hide remove confirmation when cancel is clicked', async () => {- // ArrangemockIsVarUsedInNodes.mockReturnValue(true)mockIsHovering = trueconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -1367,7 +1140,6 @@ describe('FieldList', () => {/>,)- // Trigger remove - find delete button in sortable containerconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 2)@@ -1377,23 +1149,19 @@ describe('FieldList', () => {expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()})- // Click cancelfireEvent.click(screen.getByTestId('confirm-cancel'))- // Assertawait waitFor(() => {expect(screen.queryByTestId('remove-var-confirm')).not.toBeInTheDocument()})})it('should remove field and call removeUsedVarInNodes when confirm is clicked', async () => {- // ArrangemockIsVarUsedInNodes.mockReturnValue(true)mockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1404,7 +1172,6 @@ describe('FieldList', () => {/>,)- // Trigger remove - find delete button in sortable containerconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 2)@@ -1414,10 +1181,8 @@ describe('FieldList', () => {expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()})- // Click confirmfireEvent.click(screen.getByTestId('confirm-ok'))- // Assertawait waitFor(() => {expect(handleInputFieldsChange).toHaveBeenCalled()expect(mockRemoveUsedVarInNodes).toHaveBeenCalled()@@ -1425,13 +1190,11 @@ describe('FieldList', () => {})it('should remove field directly when variable is not used in nodes', () => {- // ArrangemockIsVarUsedInNodes.mockReturnValue(false)mockIsHovering = trueconst inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1442,24 +1205,18 @@ describe('FieldList', () => {/>,)- // Find delete button in sortable containerconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 2)fireEvent.click(fieldItemButtons[1])- // Assert - should not show confirmationexpect(screen.queryByTestId('remove-var-confirm')).not.toBeInTheDocument()expect(handleInputFieldsChange).toHaveBeenCalled()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle empty inputFields', () => {- // Actrender(<FieldListnodeId="node-1"@@ -1470,12 +1227,10 @@ describe('FieldList', () => {/>,)- // Assertexpect(screen.getByTestId('sortable-container')).toBeInTheDocument()})it('should handle null LabelRightContent', () => {- // Actrender(<FieldListnodeId="node-1"@@ -1486,12 +1241,10 @@ describe('FieldList', () => {/>,)- // Assert - should render without errorsexpect(screen.getByText('var_0')).toBeInTheDocument()})it('should handle complex LabelRightContent', () => {- // Arrangeconst complexContent = (<div data-testid="complex-content"><span>Part 1</span>@@ -1499,7 +1252,6 @@ describe('FieldList', () => {</div>)- // Actrender(<FieldListnodeId="node-1"@@ -1510,22 +1262,16 @@ describe('FieldList', () => {/>,)- // Assertexpect(screen.getByTestId('complex-content')).toBeInTheDocument()expect(screen.getByText('Part 1')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with React.memo', () => {- // Arrangeconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actconst { rerender } = render(<FieldListnodeId="node-1"@@ -1546,16 +1292,13 @@ describe('FieldList', () => {/>,)- // Assertexpect(screen.getByText('var_0')).toBeInTheDocument()})it('should maintain stable onInputFieldsChange callback', () => {- // Arrangeconst inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actconst { rerender } = render(<FieldListnodeId="node-1"@@ -1580,31 +1323,21 @@ describe('FieldList', () => {fireEvent.click(screen.getByTestId('trigger-sort'))- // Assertexpect(handleInputFieldsChange).toHaveBeenCalledTimes(2)})})})-// ============================================================================-// useFieldList Hook Tests-// ============================================================================-describe('useFieldList Hook', () => {beforeEach(() => {vi.clearAllMocks()mockIsVarUsedInNodes.mockReturnValue(false)})- // -------------------------------------------------------------------------- // Initialization Tests- // -------------------------------------------------------------------------describe('Initialization', () => {it('should initialize with provided inputFields', () => {- // Arrangeconst inputFields = createInputVarList(2)- // Actrender(<FieldListnodeId="node-1"@@ -1615,13 +1348,11 @@ describe('useFieldList Hook', () => {/>,)- // Assertexpect(screen.getByText('var_0')).toBeInTheDocument()expect(screen.getByText('var_1')).toBeInTheDocument()})it('should initialize with empty inputFields', () => {- // Actrender(<FieldListnodeId="node-1"@@ -1632,21 +1363,15 @@ describe('useFieldList Hook', () => {/>,)- // Assertexpect(screen.getByTestId('sortable-container')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // handleListSortChange Tests- // -------------------------------------------------------------------------describe('handleListSortChange', () => {it('should update inputFields and call onInputFieldsChange', () => {- // Arrangeconst inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1658,7 +1383,6 @@ describe('useFieldList Hook', () => {)fireEvent.click(screen.getByTestId('trigger-sort'))- // Assertexpect(handleInputFieldsChange).toHaveBeenCalledWith('node-1',expect.arrayContaining([@@ -1669,11 +1393,9 @@ describe('useFieldList Hook', () => {})it('should strip sortable properties from list items', () => {- // Arrangeconst inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1685,7 +1407,6 @@ describe('useFieldList Hook', () => {)fireEvent.click(screen.getByTestId('trigger-sort'))- // Assertconst calledWith = handleInputFieldsChange.mock.calls[0][1]expect(calledWith[0]).not.toHaveProperty('id')expect(calledWith[0]).not.toHaveProperty('chosen')@@ -1693,17 +1414,12 @@ describe('useFieldList Hook', () => {})})- // -------------------------------------------------------------------------- // handleRemoveField Tests- // -------------------------------------------------------------------------describe('handleRemoveField', () => {it('should show confirmation when variable is used', async () => {- // ArrangemockIsVarUsedInNodes.mockReturnValue(true)mockIsHovering = trueconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -1714,26 +1430,22 @@ describe('useFieldList Hook', () => {/>,)- // Find delete button in sortable containerconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 2)fireEvent.click(fieldItemButtons[1])- // Assertawait waitFor(() => {expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()})})it('should remove directly when variable is not used', () => {- // ArrangemockIsVarUsedInNodes.mockReturnValue(false)mockIsHovering = trueconst inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1744,25 +1456,21 @@ describe('useFieldList Hook', () => {/>,)- // Find delete button in sortable containerconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 2)fireEvent.click(fieldItemButtons[1])- // Assertexpect(screen.queryByTestId('remove-var-confirm')).not.toBeInTheDocument()expect(handleInputFieldsChange).toHaveBeenCalled()})it('should not call handleInputFieldsChange immediately when variable is used (lines 70-72)', async () => {- // Arrange - This tests that when variable is used, we show confirmation instead of removing directlymockIsVarUsedInNodes.mockReturnValue(true)mockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1773,13 +1481,11 @@ describe('useFieldList Hook', () => {/>,)- // Find delete button and click itconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 2)fireEvent.click(fieldItemButtons[1])- // Assert - handleInputFieldsChange should NOT be called yet (waiting for confirmation)await waitFor(() => {expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()})@@ -1787,12 +1493,10 @@ describe('useFieldList Hook', () => {})it('should call isVarUsedInNodes with correct variable selector', async () => {- // ArrangemockIsVarUsedInNodes.mockReturnValue(true)mockIsHovering = trueconst inputFields = [createInputVar({ variable: 'my_test_var' })]- // Actrender(<FieldListnodeId="test-node-123"@@ -1808,18 +1512,15 @@ describe('useFieldList Hook', () => {if (fieldItemButtons.length >= 2)fireEvent.click(fieldItemButtons[1])- // Assertexpect(mockIsVarUsedInNodes).toHaveBeenCalledWith(['rag', 'test-node-123', 'my_test_var'])})it('should handle empty variable name gracefully', async () => {- // Arrange - Tests line 70 with empty variablemockIsVarUsedInNodes.mockReturnValue(false)mockIsHovering = trueconst inputFields = [createInputVar({ variable: '' })]const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1835,18 +1536,15 @@ describe('useFieldList Hook', () => {if (fieldItemButtons.length >= 2)fireEvent.click(fieldItemButtons[1])- // Assert - should still work with empty variableexpect(mockIsVarUsedInNodes).toHaveBeenCalledWith(['rag', 'node-1', ''])})it('should set removedVar and removedIndex when showing confirmation (lines 71-73)', async () => {- // Arrange - Tests the setRemovedVar and setRemoveIndex calls in lines 71-73mockIsVarUsedInNodes.mockReturnValue(true)mockIsHovering = trueconst inputFields = createInputVarList(3)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1857,22 +1555,17 @@ describe('useFieldList Hook', () => {/>,)- // Click delete on the SECOND item (index 1)const sortableContainer = screen.getByTestId('sortable-container')const allFieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')- // Each field item has 2 buttons (edit, delete), so index 3 is delete of second itemif (allFieldItemButtons.length >= 4)fireEvent.click(allFieldItemButtons[3])- // Show confirmationawait waitFor(() => {expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()})- // Click confirmfireEvent.click(screen.getByTestId('confirm-ok'))- // Assert - should remove the correct item (var_1 at index 1)await waitFor(() => {expect(handleInputFieldsChange).toHaveBeenCalled()})@@ -1882,15 +1575,10 @@ describe('useFieldList Hook', () => {})})- // -------------------------------------------------------------------------- // handleOpenInputFieldEditor Tests- // -------------------------------------------------------------------------describe('handleOpenInputFieldEditor', () => {it('should call toggleInputFieldEditPanel with editor props', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -1906,7 +1594,6 @@ describe('useFieldList Hook', () => {if (addButton)fireEvent.click(addButton)- // Assertexpect(mockToggleInputFieldEditPanel).toHaveBeenCalledWith(expect.objectContaining({onClose: expect.any(Function),@@ -1916,11 +1603,9 @@ describe('useFieldList Hook', () => {})it('should pass initialData when editing existing field', () => {- // ArrangemockIsHovering = trueconst inputFields = [createInputVar({ variable: 'my_var', label: 'My Label' })]- // Actrender(<FieldListnodeId="node-1"@@ -1930,13 +1615,11 @@ describe('useFieldList Hook', () => {allVariableNames={[]}/>,)- // Find edit button in sortable container (first action button)const sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1)fireEvent.click(fieldItemButtons[0])- // Assertexpect(mockToggleInputFieldEditPanel).toHaveBeenCalledWith(expect.objectContaining({initialData: expect.objectContaining({@@ -1948,18 +1631,13 @@ describe('useFieldList Hook', () => {})})- // -------------------------------------------------------------------------- // onRemoveVarConfirm Tests- // -------------------------------------------------------------------------describe('onRemoveVarConfirm', () => {it('should remove field and call removeUsedVarInNodes', async () => {- // ArrangemockIsVarUsedInNodes.mockReturnValue(true)mockIsHovering = trueconst inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -1970,7 +1648,6 @@ describe('useFieldList Hook', () => {/>,)- // Find delete button in sortable containerconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 2)@@ -1982,7 +1659,6 @@ describe('useFieldList Hook', () => {fireEvent.click(screen.getByTestId('confirm-ok'))- // Assertawait waitFor(() => {expect(handleInputFieldsChange).toHaveBeenCalled()expect(mockRemoveUsedVarInNodes).toHaveBeenCalled()@@ -1991,10 +1667,6 @@ describe('useFieldList Hook', () => {})})-// ============================================================================-// handleSubmitField Tests (via toggleInputFieldEditPanel mock)-// ============================================================================-describe('handleSubmitField', () => {beforeEach(() => {vi.clearAllMocks()@@ -2003,11 +1675,9 @@ describe('handleSubmitField', () => {})it('should add new field when editingFieldIndex is -1', () => {- // Arrangeconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2018,19 +1688,15 @@ describe('handleSubmitField', () => {/>,)- // Click add button to open editorfireEvent.click(screen.getByTestId('field-list-add-btn'))- // Get the onSubmit callback that was passed to toggleInputFieldEditPanelexpect(mockToggleInputFieldEditPanel).toHaveBeenCalled()const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]expect(editorProps).toHaveProperty('onSubmit')- // Simulate form submission with new field dataconst newFieldData = createInputVar({ variable: 'new_var', label: 'New Label' })editorProps.onSubmit(newFieldData)- // Assertexpect(handleInputFieldsChange).toHaveBeenCalledWith('node-1',expect.arrayContaining([@@ -2041,12 +1707,10 @@ describe('handleSubmitField', () => {})it('should update existing field when editingFieldIndex is valid', () => {- // ArrangemockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2057,20 +1721,16 @@ describe('handleSubmitField', () => {/>,)- // Click edit button on existing fieldconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1)fireEvent.click(fieldItemButtons[0])- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Simulate form submission with updated dataconst updatedFieldData = createInputVar({ variable: 'var_0', label: 'Updated Label' })editorProps.onSubmit(updatedFieldData)- // Assert - field should be updated, not addedexpect(handleInputFieldsChange).toHaveBeenCalledWith('node-1',expect.arrayContaining([@@ -2082,12 +1742,10 @@ describe('handleSubmitField', () => {})it('should call handleInputVarRename when variable name changes', () => {- // ArrangemockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2098,23 +1756,19 @@ describe('handleSubmitField', () => {/>,)- // Click edit buttonconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1)fireEvent.click(fieldItemButtons[0])- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Simulate form submission with changed variable name (including moreInfo)const updatedFieldData = createInputVar({ variable: 'new_var_name', label: 'Label 0' })editorProps.onSubmit(updatedFieldData, {type: 'changeVarName',payload: { beforeKey: 'var_0', afterKey: 'new_var_name' },})- // Assertexpect(mockHandleInputVarRename).toHaveBeenCalledWith('node-1',['rag', 'node-1', 'var_0'],@@ -2123,12 +1777,10 @@ describe('handleSubmitField', () => {})it('should not call handleInputVarRename when moreInfo type is not changeVarName', () => {- // Arrange - This tests line 108 branch in hooks.tsmockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2139,31 +1791,25 @@ describe('handleSubmitField', () => {/>,)- // Click edit buttonconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1)fireEvent.click(fieldItemButtons[0])- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Simulate form submission WITHOUT moreInfo (no variable name change)const updatedFieldData = createInputVar({ variable: 'var_0', label: 'Updated Label' })editorProps.onSubmit(updatedFieldData)- // Assert - handleInputVarRename should NOT be calledexpect(mockHandleInputVarRename).not.toHaveBeenCalled()expect(handleInputFieldsChange).toHaveBeenCalled()})it('should not call handleInputVarRename when moreInfo has different type', () => {- // Arrange - This tests line 108 branch in hooks.ts with different typemockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2174,31 +1820,25 @@ describe('handleSubmitField', () => {/>,)- // Click edit buttonconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1)fireEvent.click(fieldItemButtons[0])- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Simulate form submission with moreInfo but different typeconst updatedFieldData = createInputVar({ variable: 'var_0', label: 'Updated Label' })- editorProps.onSubmit(updatedFieldData, { type: 'otherType' as any })+ editorProps.onSubmit(updatedFieldData, { type: 'otherType' as never })- // Assert - handleInputVarRename should NOT be calledexpect(mockHandleInputVarRename).not.toHaveBeenCalled()expect(handleInputFieldsChange).toHaveBeenCalled()})it('should handle empty beforeKey and afterKey in moreInfo payload', () => {- // Arrange - This tests line 108 with empty keysmockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2209,23 +1849,19 @@ describe('handleSubmitField', () => {/>,)- // Click edit buttonconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1)fireEvent.click(fieldItemButtons[0])- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Simulate form submission with changeVarName but empty keysconst updatedFieldData = createInputVar({ variable: 'new_var' })editorProps.onSubmit(updatedFieldData, {type: 'changeVarName',payload: { beforeKey: '', afterKey: '' },})- // Assert - handleInputVarRename should be called with empty stringsexpect(mockHandleInputVarRename).toHaveBeenCalledWith('node-1',['rag', 'node-1', ''],@@ -2234,12 +1870,10 @@ describe('handleSubmitField', () => {})it('should handle undefined payload in moreInfo', () => {- // Arrange - This tests line 108 with undefined payloadmockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2250,23 +1884,19 @@ describe('handleSubmitField', () => {/>,)- // Click edit buttonconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1)fireEvent.click(fieldItemButtons[0])- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Simulate form submission with changeVarName but undefined payloadconst updatedFieldData = createInputVar({ variable: 'new_var' })editorProps.onSubmit(updatedFieldData, {type: 'changeVarName',payload: undefined,})- // Assert - handleInputVarRename should be called with empty strings (fallback)expect(mockHandleInputVarRename).toHaveBeenCalledWith('node-1',['rag', 'node-1', ''],@@ -2275,11 +1905,9 @@ describe('handleSubmitField', () => {})it('should close editor panel after successful submission', () => {- // Arrangeconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2290,26 +1918,20 @@ describe('handleSubmitField', () => {/>,)- // Click add buttonfireEvent.click(screen.getByTestId('field-list-add-btn'))- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Simulate form submissionconst newFieldData = createInputVar({ variable: 'new_var' })editorProps.onSubmit(newFieldData)- // Assert - toggleInputFieldEditPanel should be called with null to closeexpect(mockToggleInputFieldEditPanel).toHaveBeenCalledTimes(2)expect(mockToggleInputFieldEditPanel).toHaveBeenLastCalledWith(null)})it('should call onClose when editor is closed manually', () => {- // Arrangeconst inputFields = createInputVarList(1)- // Actrender(<FieldListnodeId="node-1"@@ -2320,25 +1942,17 @@ describe('handleSubmitField', () => {/>,)- // Click add buttonfireEvent.click(screen.getByTestId('field-list-add-btn'))- // Get the onClose callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]expect(editorProps).toHaveProperty('onClose')- // Simulate closeeditorProps.onClose()- // Assert - toggleInputFieldEditPanel should be called with nullexpect(mockToggleInputFieldEditPanel).toHaveBeenLastCalledWith(null)})})-// ============================================================================-// Duplicate Variable Name Handling Tests-// ============================================================================-describe('Duplicate Variable Name Handling', () => {beforeEach(() => {vi.clearAllMocks()@@ -2347,12 +1961,10 @@ describe('Duplicate Variable Name Handling', () => {})it('should not add field if variable name is duplicate', async () => {- // Arrangeconst Toast = await import('@/app/components/base/toast')const inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2363,31 +1975,24 @@ describe('Duplicate Variable Name Handling', () => {/>,)- // Click add buttonfireEvent.click(screen.getByTestId('field-list-add-btn'))- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Try to submit with a duplicate variable nameconst duplicateFieldData = createInputVar({ variable: 'existing_var' })editorProps.onSubmit(duplicateFieldData)- // Assert - handleInputFieldsChange should NOT be calledexpect(handleInputFieldsChange).not.toHaveBeenCalled()- // Toast should be shownexpect(Toast.default.notify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }),)})it('should allow updating field to same variable name', () => {- // ArrangemockIsHovering = trueconst inputFields = createInputVarList(2)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2398,35 +2003,25 @@ describe('Duplicate Variable Name Handling', () => {/>,)- // Click edit button on first fieldconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1)fireEvent.click(fieldItemButtons[0])- // Get the onSubmit callbackconst editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]- // Submit with same variable name (just updating label)const updatedFieldData = createInputVar({ variable: 'var_0', label: 'New Label' })editorProps.onSubmit(updatedFieldData)- // Assert - should allow update with same variable nameexpect(handleInputFieldsChange).toHaveBeenCalled()})})-// ============================================================================-// SortableItem Type Tests-// ============================================================================-describe('SortableItem Type', () => {it('should have correct structure', () => {- // Arrangeconst inputVar = createInputVar()const sortableItem = createSortableItem(inputVar)- // Assertexpect(sortableItem.id).toBe(inputVar.variable)expect(sortableItem.chosen).toBe(false)expect(sortableItem.selected).toBe(false)@@ -2436,23 +2031,17 @@ describe('SortableItem Type', () => {})it('should allow overriding sortable properties', () => {- // Arrangeconst inputVar = createInputVar()const sortableItem = createSortableItem(inputVar, {chosen: true,selected: true,})- // Assertexpect(sortableItem.chosen).toBe(true)expect(sortableItem.selected).toBe(true)})})-// ============================================================================-// Integration Tests-// ============================================================================-describe('Integration Tests', () => {beforeEach(() => {vi.clearAllMocks()@@ -2462,12 +2051,10 @@ describe('Integration Tests', () => {describe('Complete Workflow', () => {it('should handle add -> edit -> remove workflow', async () => {- // ArrangemockIsHovering = trueconst inputFields = createInputVarList(1)const handleInputFieldsChange = vi.fn()- // Act - Renderrender(<FieldListnodeId="node-1"@@ -2478,11 +2065,9 @@ describe('Integration Tests', () => {/>,)- // Step 1: Click add button (in header, outside sortable container)fireEvent.click(screen.getByTestId('field-list-add-btn'))expect(mockToggleInputFieldEditPanel).toHaveBeenCalled()- // Step 2: Edit on existing fieldconst sortableContainer = screen.getByTestId('sortable-container')const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')if (fieldItemButtons.length >= 1) {@@ -2490,7 +2075,6 @@ describe('Integration Tests', () => {expect(mockToggleInputFieldEditPanel).toHaveBeenCalledTimes(2)}- // Step 3: Remove fieldif (fieldItemButtons.length >= 2)fireEvent.click(fieldItemButtons[1])@@ -2498,11 +2082,9 @@ describe('Integration Tests', () => {})it('should handle sort operation correctly', () => {- // Arrangeconst inputFields = createInputVarList(3)const handleInputFieldsChange = vi.fn()- // Actrender(<FieldListnodeId="node-1"@@ -2515,13 +2097,11 @@ describe('Integration Tests', () => {fireEvent.click(screen.getByTestId('trigger-sort'))- // Assertexpect(handleInputFieldsChange).toHaveBeenCalledWith('node-1',expect.any(Array),)const newOrder = handleInputFieldsChange.mock.calls[0][1]- // First two should be swappedexpect(newOrder[0].variable).toBe('var_1')expect(newOrder[1].variable).toBe('var_0')})@@ -2529,10 +2109,8 @@ describe('Integration Tests', () => {describe('Props Propagation', () => {it('should propagate readonly prop through all components', () => {- // Arrangeconst inputFields = createInputVarList(2)- // Actrender(<FieldListnodeId="node-1"@@ -2544,7 +2122,6 @@ describe('Integration Tests', () => {/>,)- // Assertconst addButton = screen.getAllByRole('button').find(btn =>btn.querySelector('svg'),)diff --git a/web/app/components/rag-pipeline/components/panel/input-field/label-right-content/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/label-right-content/__tests__/index.spec.tsxsimilarity index 90%rename from web/app/components/rag-pipeline/components/panel/input-field/label-right-content/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/input-field/label-right-content/__tests__/index.spec.tsxindex 71be12bb8d3..ba9390a028c 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/label-right-content/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/label-right-content/__tests__/index.spec.tsx@@ -2,17 +2,9 @@ import type { DataSourceNodeType } from '@/app/components/workflow/nodes/data-soimport { cleanup, render, screen } from '@testing-library/react'import { afterEach, describe, expect, it, vi } from 'vitest'import { BlockEnum } from '@/app/components/workflow/types'-import Datasource from './datasource'-import GlobalInputs from './global-inputs'--// Mock react-i18next-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string) => key,- }),-}))+import Datasource from '../datasource'+import GlobalInputs from '../global-inputs'-// Mock BlockIconvi.mock('@/app/components/workflow/block-icon', () => ({default: ({ type, toolIcon, className }: { type: BlockEnum, toolIcon?: string, className?: string }) => (<div@@ -24,12 +16,10 @@ vi.mock('@/app/components/workflow/block-icon', () => ({),}))-// Mock useToolIconvi.mock('@/app/components/workflow/hooks', () => ({useToolIcon: (nodeData: DataSourceNodeType) => nodeData.provider_name || 'default-icon',}))-// Mock Tooltipvi.mock('@/app/components/base/tooltip', () => ({default: ({ popupContent, popupClassName }: { popupContent: string, popupClassName?: string }) => (<div data-testid="tooltip" data-content={popupContent} className={popupClassName} />@@ -132,7 +122,6 @@ describe('Datasource', () => {render(<Datasource nodeData={nodeData} />)- // Should still render without the title textexpect(screen.getByTestId('block-icon')).toBeInTheDocument()})@@ -160,13 +149,13 @@ describe('GlobalInputs', () => {it('should render without crashing', () => {render(<GlobalInputs />)- expect(screen.getByText('inputFieldPanel.globalInputs.title')).toBeInTheDocument()+ expect(screen.getByText('datasetPipeline.inputFieldPanel.globalInputs.title')).toBeInTheDocument()})it('should render title with correct translation key', () => {render(<GlobalInputs />)- expect(screen.getByText('inputFieldPanel.globalInputs.title')).toBeInTheDocument()+ expect(screen.getByText('datasetPipeline.inputFieldPanel.globalInputs.title')).toBeInTheDocument()})it('should render tooltip component', () => {@@ -179,7 +168,7 @@ describe('GlobalInputs', () => {render(<GlobalInputs />)const tooltip = screen.getByTestId('tooltip')- expect(tooltip).toHaveAttribute('data-content', 'inputFieldPanel.globalInputs.tooltip')+ expect(tooltip).toHaveAttribute('data-content', 'datasetPipeline.inputFieldPanel.globalInputs.tooltip')})it('should have correct tooltip className', () => {@@ -199,7 +188,7 @@ describe('GlobalInputs', () => {it('should have correct title styling', () => {render(<GlobalInputs />)- const titleElement = screen.getByText('inputFieldPanel.globalInputs.title')+ const titleElement = screen.getByText('datasetPipeline.inputFieldPanel.globalInputs.title')expect(titleElement).toHaveClass('system-sm-semibold-uppercase', 'text-text-secondary')})})diff --git a/web/app/components/rag-pipeline/components/panel/input-field/preview/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/index.spec.tsxsimilarity index 75%rename from web/app/components/rag-pipeline/components/panel/input-field/preview/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/index.spec.tsxindex f86297ccb50..6284d3045b3 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/preview/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/index.spec.tsx@@ -1,29 +1,23 @@-import type { Datasource, DataSourceOption } from '../../test-run/types'+import type { Datasource, DataSourceOption } from '../../../test-run/types'import type { RAGPipelineVariable, RAGPipelineVariables } from '@/models/pipeline'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { PipelineInputVarType } from '@/models/pipeline'-import DataSource from './data-source'-import Form from './form'-import PreviewPanel from './index'-import ProcessDocuments from './process-documents'+import DataSource from '../data-source'+import Form from '../form'+import PreviewPanel from '../index'+import ProcessDocuments from '../process-documents'-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock useFloatingRight hookconst mockUseFloatingRight = vi.fn(() => ({floatingRight: false,floatingRightWidth: 480,}))-vi.mock('../hooks', () => ({+vi.mock('../../hooks', () => ({useFloatingRight: () => mockUseFloatingRight(),}))-// Mock useInputFieldPanel hookconst mockToggleInputFieldPreviewPanel = vi.fn()vi.mock('@/app/components/rag-pipeline/hooks', () => ({useInputFieldPanel: () => ({@@ -35,7 +29,6 @@ vi.mock('@/app/components/rag-pipeline/hooks', () => ({}),}))-// Track mock state for workflow storelet mockPipelineId: string | null = 'test-pipeline-id'vi.mock('@/app/components/workflow/store', () => ({@@ -56,17 +49,14 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock reactflow storevi.mock('reactflow', () => ({useStore: () => undefined,}))-// Mock zustand shallowvi.mock('zustand/react/shallow', () => ({useShallow: (fn: unknown) => fn,}))-// Track mock data for API hookslet mockPreProcessingParamsData: { variables: RAGPipelineVariables } | undefinedlet mockProcessingParamsData: { variables: RAGPipelineVariables } | undefined@@ -83,10 +73,9 @@ vi.mock('@/service/use-pipeline', () => ({}),}))-// Track mock datasource optionslet mockDatasourceOptions: DataSourceOption[] = []-vi.mock('../../test-run/preparation/data-source-options', () => ({+vi.mock('../../../test-run/preparation/data-source-options', () => ({default: ({onSelect,dataSourceNodeId,@@ -113,13 +102,11 @@ vi.mock('../../test-run/preparation/data-source-options', () => ({),}))-// Helper function to convert option string to option objectconst mapOptionToObject = (option: string) => ({label: option,value: option,})-// Mock form-related hooksvi.mock('@/app/components/rag-pipeline/hooks/use-input-fields', () => ({useInitialData: (variables: RAGPipelineVariables) => {return React.useMemo(() => {@@ -150,7 +137,6 @@ vi.mock('@/app/components/rag-pipeline/hooks/use-input-fields', () => ({},}))-// Mock useAppForm hookvi.mock('@/app/components/base/form', () => ({useAppForm: ({ defaultValues }: { defaultValues: Record<string, unknown> }) => ({handleSubmit: vi.fn(),@@ -163,7 +149,6 @@ vi.mock('@/app/components/base/form', () => ({}),}))-// Mock BaseField componentvi.mock('@/app/components/base/form/form-scenarios/base/field', () => ({default: ({ config }: { initialData: Record<string, unknown>, config: { variable: string, label: string } }) => {const FieldComponent = ({ form }: { form: unknown }) => (@@ -177,10 +162,6 @@ vi.mock('@/app/components/base/form/form-scenarios/base/field', () => ({},}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createRAGPipelineVariable = (overrides?: Partial<RAGPipelineVariable>,): RAGPipelineVariable => ({@@ -209,10 +190,6 @@ const createDatasourceOption = (...overrides,})-// ============================================================================-// Test Wrapper Component-// ============================================================================-const createTestQueryClient = () =>new QueryClient({defaultOptions: {@@ -234,10 +211,6 @@ const renderWithProviders = (ui: React.ReactElement) => {return render(ui, { wrapper: TestWrapper })}-// ============================================================================-// PreviewPanel Component Tests-// ============================================================================-describe('PreviewPanel', () => {beforeEach(() => {vi.clearAllMocks()@@ -251,170 +224,126 @@ describe('PreviewPanel', () => {mockDatasourceOptions = []})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render preview panel without crashing', () => {- // ActrenderWithProviders(<PreviewPanel />)- // Assertexpect(screen.getByText('datasetPipeline.operations.preview'),).toBeInTheDocument()})it('should render preview badge', () => {- // ActrenderWithProviders(<PreviewPanel />)- // Assertconst badge = screen.getByText('datasetPipeline.operations.preview')expect(badge).toBeInTheDocument()})it('should render close button', () => {- // ActrenderWithProviders(<PreviewPanel />)- // Assertconst closeButton = screen.getByRole('button')expect(closeButton).toBeInTheDocument()})it('should render DataSource component', () => {- // ActrenderWithProviders(<PreviewPanel />)- // Assertexpect(screen.getByTestId('data-source-options')).toBeInTheDocument()})it('should render ProcessDocuments component', () => {- // ActrenderWithProviders(<PreviewPanel />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()})it('should render divider between sections', () => {- // Actconst { container } = renderWithProviders(<PreviewPanel />)- // Assertconst divider = container.querySelector('.bg-divider-subtle')expect(divider).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // State Management Tests- // -------------------------------------------------------------------------describe('State Management', () => {it('should initialize with empty datasource state', () => {- // ActrenderWithProviders(<PreviewPanel />)- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('')})it('should update datasource state when DataSource selects', () => {- // ArrangemockDatasourceOptions = [createDatasourceOption({ value: 'node-1', label: 'Node 1' }),]- // ActrenderWithProviders(<PreviewPanel />)fireEvent.click(screen.getByTestId('option-node-1'))- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('node-1')})it('should pass datasource nodeId to ProcessDocuments', () => {- // ArrangemockDatasourceOptions = [createDatasourceOption({ value: 'test-node', label: 'Test Node' }),]- // ActrenderWithProviders(<PreviewPanel />)fireEvent.click(screen.getByTestId('option-test-node'))- // Assert - ProcessDocuments receives the nodeIdexpect(screen.getByTestId('current-node-id').textContent).toBe('test-node')})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call toggleInputFieldPreviewPanel when close button clicked', () => {- // ActrenderWithProviders(<PreviewPanel />)const closeButton = screen.getByRole('button')fireEvent.click(closeButton)- // Assertexpect(mockToggleInputFieldPreviewPanel).toHaveBeenCalledTimes(1)})it('should handle multiple close button clicks', () => {- // ActrenderWithProviders(<PreviewPanel />)const closeButton = screen.getByRole('button')fireEvent.click(closeButton)fireEvent.click(closeButton)fireEvent.click(closeButton)- // Assertexpect(mockToggleInputFieldPreviewPanel).toHaveBeenCalledTimes(3)})it('should handle datasource selection changes', () => {- // ArrangemockDatasourceOptions = [createDatasourceOption({ value: 'node-1', label: 'Node 1' }),createDatasourceOption({ value: 'node-2', label: 'Node 2' }),]- // ActrenderWithProviders(<PreviewPanel />)fireEvent.click(screen.getByTestId('option-node-1'))- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('node-1')- // Act - Change selectionfireEvent.click(screen.getByTestId('option-node-2'))- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('node-2')})})- // -------------------------------------------------------------------------- // Floating Right Behavior Tests- // -------------------------------------------------------------------------describe('Floating Right Behavior', () => {it('should apply floating right styles when floatingRight is true', () => {- // ArrangemockUseFloatingRight.mockReturnValue({floatingRight: true,floatingRightWidth: 400,})- // Actconst { container } = renderWithProviders(<PreviewPanel />)- // Assertconst panel = container.firstChild as HTMLElementexpect(panel.className).toContain('absolute')expect(panel.className).toContain('right-0')@@ -422,43 +351,33 @@ describe('PreviewPanel', () => {})it('should not apply floating right styles when floatingRight is false', () => {- // ArrangemockUseFloatingRight.mockReturnValue({floatingRight: false,floatingRightWidth: 480,})- // Actconst { container } = renderWithProviders(<PreviewPanel />)- // Assertconst panel = container.firstChild as HTMLElementexpect(panel.className).not.toContain('absolute')expect(panel.style.width).toBe('480px')})it('should update width when floatingRightWidth changes', () => {- // ArrangemockUseFloatingRight.mockReturnValue({floatingRight: false,floatingRightWidth: 600,})- // Actconst { container } = renderWithProviders(<PreviewPanel />)- // Assertconst panel = container.firstChild as HTMLElementexpect(panel.style.width).toBe('600px')})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain stable handleClosePreviewPanel callback', () => {- // Actconst { rerender } = renderWithProviders(<PreviewPanel />)fireEvent.click(screen.getByRole('button'))@@ -469,51 +388,37 @@ describe('PreviewPanel', () => {)fireEvent.click(screen.getByRole('button'))- // Assertexpect(mockToggleInputFieldPreviewPanel).toHaveBeenCalledTimes(2)})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle empty datasource options', () => {- // ArrangemockDatasourceOptions = []- // ActrenderWithProviders(<PreviewPanel />)- // Assertexpect(screen.getByTestId('data-source-options')).toBeInTheDocument()expect(screen.getByTestId('current-node-id').textContent).toBe('')})it('should handle rapid datasource selections', () => {- // ArrangemockDatasourceOptions = [createDatasourceOption({ value: 'node-1', label: 'Node 1' }),createDatasourceOption({ value: 'node-2', label: 'Node 2' }),createDatasourceOption({ value: 'node-3', label: 'Node 3' }),]- // ActrenderWithProviders(<PreviewPanel />)fireEvent.click(screen.getByTestId('option-node-1'))fireEvent.click(screen.getByTestId('option-node-2'))fireEvent.click(screen.getByTestId('option-node-3'))- // Assert - Final selection should be node-3expect(screen.getByTestId('current-node-id').textContent).toBe('node-3')})})})-// ============================================================================-// DataSource Component Tests-// ============================================================================-describe('DataSource', () => {beforeEach(() => {vi.clearAllMocks()@@ -522,164 +427,123 @@ describe('DataSource', () => {mockDatasourceOptions = []})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render step one title', () => {- // Arrangeconst onSelect = vi.fn()- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="" />,)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepOneTitle'),).toBeInTheDocument()})it('should render DataSourceOptions component', () => {- // Arrangeconst onSelect = vi.fn()- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="" />,)- // Assertexpect(screen.getByTestId('data-source-options')).toBeInTheDocument()})it('should pass dataSourceNodeId to DataSourceOptions', () => {- // Arrangeconst onSelect = vi.fn()- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="test-node-id" />,)- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('test-node-id',)})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should handle empty dataSourceNodeId', () => {- // Arrangeconst onSelect = vi.fn()- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="" />)- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('')})it('should handle different dataSourceNodeId values', () => {- // Arrangeconst onSelect = vi.fn()- // Actconst { rerender } = renderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="node-1" />,)- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('node-1')- // Act - Change nodeIdrerender(<TestWrapper><DataSource onSelect={onSelect} dataSourceNodeId="node-2" /></TestWrapper>,)- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('node-2')})})- // -------------------------------------------------------------------------- // API Integration Tests- // -------------------------------------------------------------------------describe('API Integration', () => {it('should fetch pre-processing params when pipelineId and nodeId are present', async () => {- // Arrangeconst onSelect = vi.fn()mockPreProcessingParamsData = {variables: [createRAGPipelineVariable()],}- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="test-node" />,)- // Assert - Form should render with fetched variablesawait waitFor(() => {expect(screen.getByTestId('field-test_variable')).toBeInTheDocument()})})it('should not render form fields when params data is empty', () => {- // Arrangeconst onSelect = vi.fn()mockPreProcessingParamsData = { variables: [] }- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="test-node" />,)- // Assertexpect(screen.queryByTestId('field-test_variable')).not.toBeInTheDocument()})it('should handle undefined params data', () => {- // Arrangeconst onSelect = vi.fn()mockPreProcessingParamsData = undefined- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="" />,)- // Assert - Should render without errorsexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepOneTitle'),).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onSelect when datasource option is clicked', () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = [createDatasourceOption({ value: 'selected-node', label: 'Selected' }),]- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="" />,)fireEvent.click(screen.getByTestId('option-selected-node'))- // Assertexpect(onSelect).toHaveBeenCalledTimes(1)expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({@@ -689,58 +553,43 @@ describe('DataSource', () => {})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be memoized (React.memo)', () => {- // Arrangeconst onSelect = vi.fn()- // Actconst { rerender } = renderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="node-1" />,)- // Rerender with same propsrerender(<TestWrapper><DataSource onSelect={onSelect} dataSourceNodeId="node-1" /></TestWrapper>,)- // Assert - Component should not cause additional rendersexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepOneTitle'),).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle null pipelineId', () => {- // Arrangeconst onSelect = vi.fn()mockPipelineId = null- // ActrenderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="test-node" />,)- // Assert - Should render without errorsexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepOneTitle'),).toBeInTheDocument()})it('should handle special characters in dataSourceNodeId', () => {- // Arrangeconst onSelect = vi.fn()- // ActrenderWithProviders(<DataSourceonSelect={onSelect}@@ -748,7 +597,6 @@ describe('DataSource', () => {/>,)- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('node-with-special-chars_123',)@@ -756,10 +604,6 @@ describe('DataSource', () => {})})-// ============================================================================-// ProcessDocuments Component Tests-// ============================================================================-describe('ProcessDocuments', () => {beforeEach(() => {vi.clearAllMocks()@@ -767,81 +611,60 @@ describe('ProcessDocuments', () => {mockProcessingParamsData = undefined})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render step two title', () => {- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId="" />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()})it('should render Form component', () => {- // ArrangemockProcessingParamsData = {variables: [createRAGPipelineVariable({ variable: 'process_var' })],}- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)- // Assert - Form should be renderedexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should handle empty dataSourceNodeId', () => {- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId="" />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()})it('should handle different dataSourceNodeId values', () => {- // Actconst { rerender } = renderWithProviders(<ProcessDocuments dataSourceNodeId="node-1" />,)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()- // Act - Change nodeIdrerender(<TestWrapper><ProcessDocuments dataSourceNodeId="node-2" /></TestWrapper>,)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // API Integration Tests- // -------------------------------------------------------------------------describe('API Integration', () => {it('should fetch processing params when pipelineId and nodeId are present', async () => {- // ArrangemockProcessingParamsData = {variables: [createRAGPipelineVariable({@@ -851,41 +674,32 @@ describe('ProcessDocuments', () => {],}- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)- // Assertawait waitFor(() => {expect(screen.getByTestId('field-chunk_size')).toBeInTheDocument()})})it('should not render form fields when params data is empty', () => {- // ArrangemockProcessingParamsData = { variables: [] }- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)- // Assertexpect(screen.queryByTestId('field-chunk_size')).not.toBeInTheDocument()})it('should handle undefined params data', () => {- // ArrangemockProcessingParamsData = undefined- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId="" />)- // Assert - Should render without errorsexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()})it('should render multiple form fields from params', async () => {- // ArrangemockProcessingParamsData = {variables: [createRAGPipelineVariable({@@ -899,10 +713,8 @@ describe('ProcessDocuments', () => {],}- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)- // Assertawait waitFor(() => {expect(screen.getByTestId('field-var1')).toBeInTheDocument()expect(screen.getByTestId('field-var2')).toBeInTheDocument()@@ -910,55 +722,40 @@ describe('ProcessDocuments', () => {})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be memoized (React.memo)', () => {- // Actconst { rerender } = renderWithProviders(<ProcessDocuments dataSourceNodeId="node-1" />,)- // Rerender with same propsrerender(<TestWrapper><ProcessDocuments dataSourceNodeId="node-1" /></TestWrapper>,)- // Assert - Component should render without issuesexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle null pipelineId', () => {- // ArrangemockPipelineId = null- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)- // Assert - Should render without errorsexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()})it('should handle very long dataSourceNodeId', () => {- // Arrangeconst longNodeId = 'a'.repeat(100)- // ActrenderWithProviders(<ProcessDocuments dataSourceNodeId={longNodeId} />)- // Assertexpect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),).toBeInTheDocument()@@ -966,57 +763,39 @@ describe('ProcessDocuments', () => {})})-// ============================================================================-// Form Component Tests-// ============================================================================-describe('Form', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render form element', () => {- // Actconst { container } = renderWithProviders(<Form variables={[]} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})it('should render form fields for each variable', () => {- // Arrangeconst variables = [createRAGPipelineVariable({ variable: 'field1', label: 'Field 1' }),createRAGPipelineVariable({ variable: 'field2', label: 'Field 2' }),]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-field1')).toBeInTheDocument()expect(screen.getByTestId('field-field2')).toBeInTheDocument()})it('should render no fields when variables is empty', () => {- // ActrenderWithProviders(<Form variables={[]} />)- // Assertexpect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should handle different variable types', () => {- // Arrangeconst variables = [createRAGPipelineVariable({variable: 'text_var',@@ -1033,17 +812,14 @@ describe('Form', () => {}),]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-text_var')).toBeInTheDocument()expect(screen.getByTestId('field-number_var')).toBeInTheDocument()expect(screen.getByTestId('field-select_var')).toBeInTheDocument()})it('should handle variables with default values', () => {- // Arrangeconst variables = [createRAGPipelineVariable({variable: 'with_default',@@ -1051,15 +827,12 @@ describe('Form', () => {}),]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-with_default')).toBeInTheDocument()})it('should handle variables with all optional fields', () => {- // Arrangeconst variables = [createRAGPipelineVariable({variable: 'full_var',@@ -1073,59 +846,42 @@ describe('Form', () => {}),]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-full_var')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Form Behavior Tests- // -------------------------------------------------------------------------describe('Form Behavior', () => {it('should prevent default form submission', () => {- // Arrangeconst variables = [createRAGPipelineVariable()]const preventDefaultMock = vi.fn()- // Actconst { container } = renderWithProviders(<Form variables={variables} />)const form = container.querySelector('form')!- // Create and dispatch submit eventconst submitEvent = new Event('submit', { bubbles: true, cancelable: true })Object.defineProperty(submitEvent, 'preventDefault', {value: preventDefaultMock,})form.dispatchEvent(submitEvent)- // Assert - Form should prevent default submissionexpect(preventDefaultMock).toHaveBeenCalled()})it('should pass form to each field component', () => {- // Arrangeconst variables = [createRAGPipelineVariable({ variable: 'test_var' })]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('form-ref').textContent).toBe('has-form')})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should memoize initialData when variables do not change', () => {- // Arrangeconst variables = [createRAGPipelineVariable()]- // Actconst { rerender } = renderWithProviders(<Form variables={variables} />)rerender(<TestWrapper>@@ -1133,72 +889,55 @@ describe('Form', () => {</TestWrapper>,)- // Assert - Component should render without issuesexpect(screen.getByTestId('field-test_variable')).toBeInTheDocument()})it('should memoize configurations when variables do not change', () => {- // Arrangeconst variables = [createRAGPipelineVariable({ variable: 'var1' }),createRAGPipelineVariable({ variable: 'var2' }),]- // Actconst { rerender } = renderWithProviders(<Form variables={variables} />)- // Rerender with same variables referencererender(<TestWrapper><Form variables={variables} /></TestWrapper>,)- // Assertexpect(screen.getByTestId('field-var1')).toBeInTheDocument()expect(screen.getByTestId('field-var2')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle empty variables array', () => {- // Actconst { container } = renderWithProviders(<Form variables={[]} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()expect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()})it('should handle single variable', () => {- // Arrangeconst variables = [createRAGPipelineVariable({ variable: 'single' })]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-single')).toBeInTheDocument()})it('should handle many variables', () => {- // Arrangeconst variables = Array.from({ length: 20 }, (_, i) =>createRAGPipelineVariable({ variable: `var_${i}`, label: `Var ${i}` }))- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-var_0')).toBeInTheDocument()expect(screen.getByTestId('field-var_19')).toBeInTheDocument()})it('should handle variables with special characters in names', () => {- // Arrangeconst variables = [createRAGPipelineVariable({variable: 'var_with_underscore',@@ -1206,15 +945,12 @@ describe('Form', () => {}),]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-var_with_underscore')).toBeInTheDocument()})it('should handle variables with unicode labels', () => {- // Arrangeconst variables = [createRAGPipelineVariable({variable: 'unicode_var',@@ -1223,16 +959,13 @@ describe('Form', () => {}),]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-unicode_var')).toBeInTheDocument()expect(screen.getByText('中文标签 🎉')).toBeInTheDocument()})it('should handle variables with empty string default values', () => {- // Arrangeconst variables = [createRAGPipelineVariable({variable: 'empty_default',@@ -1240,15 +973,12 @@ describe('Form', () => {}),]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-empty_default')).toBeInTheDocument()})it('should handle variables with zero max_length', () => {- // Arrangeconst variables = [createRAGPipelineVariable({variable: 'zero_length',@@ -1256,19 +986,13 @@ describe('Form', () => {}),]- // ActrenderWithProviders(<Form variables={variables} />)- // Assertexpect(screen.getByTestId('field-zero_length')).toBeInTheDocument()})})})-// ============================================================================-// Integration Tests-// ============================================================================-describe('Preview Panel Integration', () => {beforeEach(() => {vi.clearAllMocks()@@ -1282,12 +1006,8 @@ describe('Preview Panel Integration', () => {mockDatasourceOptions = []})- // -------------------------------------------------------------------------- // End-to-End Flow Tests- // -------------------------------------------------------------------------describe('End-to-End Flow', () => {it('should complete full preview flow: select datasource -> show forms', async () => {- // ArrangemockDatasourceOptions = [createDatasourceOption({ value: 'node-1', label: 'Local File' }),]@@ -1308,13 +1028,10 @@ describe('Preview Panel Integration', () => {],}- // ActrenderWithProviders(<PreviewPanel />)- // Select datasourcefireEvent.click(screen.getByTestId('option-node-1'))- // Assert - Both forms should show their fieldsawait waitFor(() => {expect(screen.getByTestId('field-source_var')).toBeInTheDocument()expect(screen.getByTestId('field-process_var')).toBeInTheDocument()@@ -1322,7 +1039,6 @@ describe('Preview Panel Integration', () => {})it('should update both forms when datasource changes', async () => {- // ArrangemockDatasourceOptions = [createDatasourceOption({ value: 'node-1', label: 'Node 1' }),createDatasourceOption({ value: 'node-2', label: 'Node 2' }),@@ -1334,75 +1050,56 @@ describe('Preview Panel Integration', () => {variables: [createRAGPipelineVariable({ variable: 'proc_var' })],}- // ActrenderWithProviders(<PreviewPanel />)- // Select first datasourcefireEvent.click(screen.getByTestId('option-node-1'))- // Assert initial selectionawait waitFor(() => {expect(screen.getByTestId('current-node-id').textContent).toBe('node-1')})- // Select second datasourcefireEvent.click(screen.getByTestId('option-node-2'))- // Assert updated selectionawait waitFor(() => {expect(screen.getByTestId('current-node-id').textContent).toBe('node-2')})})})- // -------------------------------------------------------------------------- // Component Communication Tests- // -------------------------------------------------------------------------describe('Component Communication', () => {it('should pass correct nodeId from PreviewPanel to child components', () => {- // ArrangemockDatasourceOptions = [createDatasourceOption({ value: 'communicated-node', label: 'Node' }),]- // ActrenderWithProviders(<PreviewPanel />)fireEvent.click(screen.getByTestId('option-communicated-node'))- // Assertexpect(screen.getByTestId('current-node-id').textContent).toBe('communicated-node',)})})- // -------------------------------------------------------------------------- // State Persistence Tests- // -------------------------------------------------------------------------describe('State Persistence', () => {it('should maintain datasource selection within same render cycle', () => {- // ArrangemockDatasourceOptions = [createDatasourceOption({ value: 'persistent-node', label: 'Persistent' }),createDatasourceOption({ value: 'other-node', label: 'Other' }),]- // ActrenderWithProviders(<PreviewPanel />)fireEvent.click(screen.getByTestId('option-persistent-node'))- // Assert - Selection should be maintainedexpect(screen.getByTestId('current-node-id').textContent).toBe('persistent-node',)- // Change selection and verify state updates correctlyfireEvent.click(screen.getByTestId('option-other-node'))expect(screen.getByTestId('current-node-id').textContent).toBe('other-node',)- // Go back to original and verifyfireEvent.click(screen.getByTestId('option-persistent-node'))expect(screen.getByTestId('current-node-id').textContent).toBe('persistent-node',diff --git a/web/app/components/rag-pipeline/components/panel/test-run/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/__tests__/index.spec.tsxsimilarity index 85%rename from web/app/components/rag-pipeline/components/panel/test-run/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/test-run/__tests__/index.spec.tsxindex 7ead398ac10..5acea3733c4 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/__tests__/index.spec.tsx@@ -3,15 +3,9 @@ import type { WorkflowRunningData } from '@/app/components/workflow/types'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { ChunkingMode } from '@/models/datasets'-import Header from './header'-// Import components after mocks-import TestRunPanel from './index'+import Header from '../header'+import TestRunPanel from '../index'-// ============================================================================-// Mocks-// ============================================================================--// Mock workflow storeconst mockIsPreparingDataSource = vi.fn(() => true)const mockSetIsPreparingDataSource = vi.fn()const mockWorkflowRunningData = vi.fn<() => WorkflowRunningData | undefined>(() => undefined)@@ -34,7 +28,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock workflow interactionsconst mockHandleCancelDebugAndPreviewPanel = vi.fn()vi.mock('@/app/components/workflow/hooks', () => ({useWorkflowInteractions: () => ({@@ -46,22 +39,18 @@ vi.mock('@/app/components/workflow/hooks', () => ({useToolIcon: () => 'mock-tool-icon',}))-// Mock data source providervi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/store/provider', () => ({default: ({ children }: { children: React.ReactNode }) => <div data-testid="data-source-provider">{children}</div>,}))-// Mock Preparation component-vi.mock('./preparation', () => ({+vi.mock('../preparation', () => ({default: () => <div data-testid="preparation-component">Preparation</div>,}))-// Mock Result component (for TestRunPanel tests only)-vi.mock('./result', () => ({+vi.mock('../result', () => ({default: () => <div data-testid="result-component">Result</div>,}))-// Mock ResultPanel from workflowvi.mock('@/app/components/workflow/run/result-panel', () => ({default: (props: Record<string, unknown>) => (<div data-testid="result-panel">@@ -72,7 +61,6 @@ vi.mock('@/app/components/workflow/run/result-panel', () => ({),}))-// Mock TracingPanel from workflowvi.mock('@/app/components/workflow/run/tracing-panel', () => ({default: (props: { list: unknown[] }) => (<div data-testid="tracing-panel">@@ -85,20 +73,14 @@ vi.mock('@/app/components/workflow/run/tracing-panel', () => ({),}))-// Mock Loading componentvi.mock('@/app/components/base/loading', () => ({default: () => <div data-testid="loading">Loading...</div>,}))-// Mock configvi.mock('@/config', () => ({RAG_PIPELINE_PREVIEW_CHUNK_NUM: 5,}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createMockWorkflowRunningData = (overrides: Partial<WorkflowRunningData> = {}): WorkflowRunningData => ({result: {status: WorkflowRunningStatus.Succeeded,@@ -141,10 +123,6 @@ const createMockQAOutputs = () => ({],})-// ============================================================================-// TestRunPanel Component Tests-// ============================================================================-describe('TestRunPanel', () => {beforeEach(() => {vi.clearAllMocks()@@ -152,7 +130,6 @@ describe('TestRunPanel', () => {mockWorkflowRunningData.mockReturnValue(undefined)})- // Basic rendering testsdescribe('Rendering', () => {it('should render with correct container styles', () => {const { container } = render(<TestRunPanel />)@@ -168,7 +145,6 @@ describe('TestRunPanel', () => {})})- // Conditional rendering based on isPreparingDataSourcedescribe('Conditional Content Rendering', () => {it('should render Preparation inside DataSourceProvider when isPreparingDataSource is true', () => {mockIsPreparingDataSource.mockReturnValue(true)@@ -192,17 +168,12 @@ describe('TestRunPanel', () => {})})-// ============================================================================-// Header Component Tests-// ============================================================================-describe('Header', () => {beforeEach(() => {vi.clearAllMocks()mockIsPreparingDataSource.mockReturnValue(true)})- // Rendering testsdescribe('Rendering', () => {it('should render title with correct translation key', () => {render(<Header />)@@ -225,7 +196,6 @@ describe('Header', () => {})})- // Close button interactionsdescribe('Close Button Interaction', () => {it('should call setIsPreparingDataSource(false) and handleCancelDebugAndPreviewPanel when clicked and isPreparingDataSource is true', () => {mockIsPreparingDataSource.mockReturnValue(true)@@ -253,19 +223,13 @@ describe('Header', () => {})})-// ============================================================================-// Result Component Tests (Real Implementation)-// ============================================================================--// Unmock Result for these tests-vi.doUnmock('./result')+vi.doUnmock('../result')describe('Result', () => {- // Dynamically import Result to get real implementation- let Result: typeof import('./result').default+ let Result: typeof import('../result').defaultbeforeAll(async () => {- const resultModule = await import('./result')+ const resultModule = await import('../result')Result = resultModule.default})@@ -274,7 +238,6 @@ describe('Result', () => {mockWorkflowRunningData.mockReturnValue(undefined)})- // Rendering testsdescribe('Rendering', () => {it('should render with RESULT tab active by default', async () => {render(<Result />)@@ -294,7 +257,6 @@ describe('Result', () => {})})- // Tab switching testsdescribe('Tab Switching', () => {it('should switch to DETAIL tab when clicked', async () => {mockWorkflowRunningData.mockReturnValue(createMockWorkflowRunningData())@@ -321,7 +283,6 @@ describe('Result', () => {})})- // Loading statesdescribe('Loading States', () => {it('should show loading in DETAIL tab when no result data', async () => {mockWorkflowRunningData.mockReturnValue({@@ -352,18 +313,13 @@ describe('Result', () => {})})-// ============================================================================-// ResultPreview Component Tests-// ============================================================================--// We need to import ResultPreview directly-vi.doUnmock('./result/result-preview')+vi.doUnmock('../result/result-preview')describe('ResultPreview', () => {- let ResultPreview: typeof import('./result/result-preview').default+ let ResultPreview: typeof import('../result/result-preview').defaultbeforeAll(async () => {- const previewModule = await import('./result/result-preview')+ const previewModule = await import('../result/result-preview')ResultPreview = previewModule.default})@@ -373,7 +329,6 @@ describe('ResultPreview', () => {vi.clearAllMocks()})- // Loading statedescribe('Loading State', () => {it('should show loading spinner when isRunning is true and no outputs', () => {render(@@ -402,7 +357,6 @@ describe('ResultPreview', () => {})})- // Error statedescribe('Error State', () => {it('should show error message when not running and has error', () => {render(@@ -448,7 +402,6 @@ describe('ResultPreview', () => {})})- // Success state with outputsdescribe('Success State with Outputs', () => {it('should render chunk content when outputs are available', () => {render(@@ -460,7 +413,6 @@ describe('ResultPreview', () => {/>,)- // Check that chunk content is rendered (the real ChunkCardList renders the content)expect(screen.getByText('test chunk content')).toBeInTheDocument()})@@ -492,7 +444,6 @@ describe('ResultPreview', () => {})})- // Edge casesdescribe('Edge Cases', () => {it('should handle empty outputs gracefully', () => {render(@@ -504,7 +455,6 @@ describe('ResultPreview', () => {/>,)- // Should not crash and should not show chunk card listexpect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()})@@ -523,17 +473,13 @@ describe('ResultPreview', () => {})})-// ============================================================================-// Tabs Component Tests-// ============================================================================--vi.doUnmock('./result/tabs')+vi.doUnmock('../result/tabs')describe('Tabs', () => {- let Tabs: typeof import('./result/tabs').default+ let Tabs: typeof import('../result/tabs').defaultbeforeAll(async () => {- const tabsModule = await import('./result/tabs')+ const tabsModule = await import('../result/tabs')Tabs = tabsModule.default})@@ -543,7 +489,6 @@ describe('Tabs', () => {vi.clearAllMocks()})- // Rendering testsdescribe('Rendering', () => {it('should render all three tabs', () => {render(@@ -560,7 +505,6 @@ describe('Tabs', () => {})})- // Active tab stylingdescribe('Active Tab Styling', () => {it('should highlight RESULT tab when currentTab is RESULT', () => {render(@@ -589,7 +533,6 @@ describe('Tabs', () => {})})- // Tab click handlingdescribe('Tab Click Handling', () => {it('should call switchTab with RESULT when RESULT tab is clicked', () => {render(@@ -634,7 +577,6 @@ describe('Tabs', () => {})})- // Disabled state when no datadescribe('Disabled State', () => {it('should disable tabs when workflowRunningData is undefined', () => {render(@@ -651,17 +593,13 @@ describe('Tabs', () => {})})-// ============================================================================-// Tab Component Tests-// ============================================================================--vi.doUnmock('./result/tabs/tab')+vi.doUnmock('../result/tabs/tab')describe('Tab', () => {- let Tab: typeof import('./result/tabs/tab').default+ let Tab: typeof import('../result/tabs/tab').defaultbeforeAll(async () => {- const tabModule = await import('./result/tabs/tab')+ const tabModule = await import('../result/tabs/tab')Tab = tabModule.default})@@ -671,7 +609,6 @@ describe('Tab', () => {vi.clearAllMocks()})- // Rendering testsdescribe('Rendering', () => {it('should render tab with label', () => {render(@@ -688,7 +625,6 @@ describe('Tab', () => {})})- // Active state stylingdescribe('Active State', () => {it('should have active styles when isActive is true', () => {render(@@ -721,7 +657,6 @@ describe('Tab', () => {})})- // Click handlingdescribe('Click Handling', () => {it('should call onClick with value when clicked', () => {render(@@ -753,12 +688,10 @@ describe('Tab', () => {const tab = screen.getByRole('button')fireEvent.click(tab)- // The click handler is still called, but button is disabledexpect(tab).toBeDisabled()})})- // Disabled statedescribe('Disabled State', () => {it('should be disabled when workflowRunningData is undefined', () => {render(@@ -793,19 +726,14 @@ describe('Tab', () => {})})-// ============================================================================-// formatPreviewChunks Utility Tests-// ============================================================================-describe('formatPreviewChunks', () => {- let formatPreviewChunks: typeof import('./result/result-preview/utils').formatPreviewChunks+ let formatPreviewChunks: typeof import('../result/result-preview/utils').formatPreviewChunksbeforeAll(async () => {- const utilsModule = await import('./result/result-preview/utils')+ const utilsModule = await import('../result/result-preview/utils')formatPreviewChunks = utilsModule.formatPreviewChunks})- // Edge casesdescribe('Edge Cases', () => {it('should return undefined for null outputs', () => {expect(formatPreviewChunks(null)).toBeUndefined()@@ -824,7 +752,6 @@ describe('formatPreviewChunks', () => {})})- // General (text) chunksdescribe('General Chunks (ChunkingMode.text)', () => {it('should format general chunks correctly', () => {const outputs = createMockGeneralOutputs(['content1', 'content2', 'content3'])@@ -842,7 +769,6 @@ describe('formatPreviewChunks', () => {const outputs = createMockGeneralOutputs(manyChunks)const result = formatPreviewChunks(outputs) as GeneralChunks- // RAG_PIPELINE_PREVIEW_CHUNK_NUM is mocked to 5expect(result).toHaveLength(5)expect(result).toEqual([{ content: 'chunk0', summary: undefined },@@ -861,7 +787,6 @@ describe('formatPreviewChunks', () => {})})- // Parent-child chunksdescribe('Parent-Child Chunks (ChunkingMode.parentChild)', () => {it('should format paragraph mode parent-child chunks correctly', () => {const outputs = createMockParentChildOutputs('paragraph')@@ -902,7 +827,6 @@ describe('formatPreviewChunks', () => {})})- // QA chunksdescribe('QA Chunks (ChunkingMode.qa)', () => {it('should format QA chunks correctly', () => {const outputs = createMockQAOutputs()@@ -931,14 +855,10 @@ describe('formatPreviewChunks', () => {})})-// ============================================================================-// Types Tests-// ============================================================================-describe('Types', () => {describe('TestRunStep Enum', () => {it('should have correct enum values', async () => {- const { TestRunStep } = await import('./types')+ const { TestRunStep } = await import('../types')expect(TestRunStep.dataSource).toBe('dataSource')expect(TestRunStep.documentProcessing).toBe('documentProcessing')diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/__tests__/hooks.spec.ts b/web/app/components/rag-pipeline/components/panel/test-run/preparation/__tests__/hooks.spec.tsnew file mode 100644index 00000000000..ee65a9d65cc--- /dev/null+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/__tests__/hooks.spec.ts@@ -0,0 +1,232 @@+import type { DataSourceNodeType } from '@/app/components/workflow/nodes/data-source/types'+import { renderHook } from '@testing-library/react'+import { act } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { BlockEnum } from '@/app/components/workflow/types'+import { useDatasourceOptions, useOnlineDocument, useOnlineDrive, useTestRunSteps, useWebsiteCrawl } from '../hooks'++const mockNodes: Array<{ id: string, data: Partial<DataSourceNodeType> & { type: string } }> = []+vi.mock('reactflow', () => ({+ useNodes: () => mockNodes,+}))++const mockDataSourceStoreGetState = vi.fn()+vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/store', () => ({+ useDataSourceStore: () => ({+ getState: mockDataSourceStoreGetState,+ }),+}))++vi.mock('@/app/components/workflow/types', async () => {+ const actual = await vi.importActual<typeof import('@/app/components/workflow/types')>('@/app/components/workflow/types')+ return {+ ...actual,+ BlockEnum: {+ ...actual.BlockEnum,+ DataSource: 'data-source',+ },+ }+})++vi.mock('../../types', () => ({+ TestRunStep: {+ dataSource: 'dataSource',+ documentProcessing: 'documentProcessing',+ },+}))++vi.mock('@/models/datasets', () => ({+ CrawlStep: {+ init: 'init',+ },+}))++describe('useTestRunSteps', () => {+ afterEach(() => {+ vi.clearAllMocks()+ })++ it('should initialize with step 1', () => {+ const { result } = renderHook(() => useTestRunSteps())++ expect(result.current.currentStep).toBe(1)+ })++ it('should return 2 steps (dataSource and documentProcessing)', () => {+ const { result } = renderHook(() => useTestRunSteps())++ expect(result.current.steps).toHaveLength(2)+ expect(result.current.steps[0].value).toBe('dataSource')+ expect(result.current.steps[1].value).toBe('documentProcessing')+ })++ it('should increment step on handleNextStep', () => {+ const { result } = renderHook(() => useTestRunSteps())++ act(() => {+ result.current.handleNextStep()+ })++ expect(result.current.currentStep).toBe(2)+ })++ it('should decrement step on handleBackStep', () => {+ const { result } = renderHook(() => useTestRunSteps())++ act(() => {+ result.current.handleNextStep()+ })+ expect(result.current.currentStep).toBe(2)++ act(() => {+ result.current.handleBackStep()+ })+ expect(result.current.currentStep).toBe(1)+ })++ it('should have translated step labels', () => {+ const { result } = renderHook(() => useTestRunSteps())++ expect(result.current.steps[0].label).toBeDefined()+ expect(typeof result.current.steps[0].label).toBe('string')+ })+})++describe('useDatasourceOptions', () => {+ beforeEach(() => {+ mockNodes.length = 0+ vi.clearAllMocks()+ })++ it('should return empty options when no DataSource nodes', () => {+ mockNodes.push({ id: 'n1', data: { type: BlockEnum.LLM, title: 'LLM' } })++ const { result } = renderHook(() => useDatasourceOptions())++ expect(result.current).toEqual([])+ })++ it('should return options from DataSource nodes', () => {+ mockNodes.push(+ { id: 'ds-1', data: { type: BlockEnum.DataSource, title: 'Source A' } },+ { id: 'ds-2', data: { type: BlockEnum.DataSource, title: 'Source B' } },+ )++ const { result } = renderHook(() => useDatasourceOptions())++ expect(result.current).toHaveLength(2)+ expect(result.current[0]).toEqual({+ label: 'Source A',+ value: 'ds-1',+ data: expect.objectContaining({ type: 'data-source' }),+ })+ expect(result.current[1]).toEqual({+ label: 'Source B',+ value: 'ds-2',+ data: expect.objectContaining({ type: 'data-source' }),+ })+ })++ it('should filter out non-DataSource nodes', () => {+ mockNodes.push(+ { id: 'ds-1', data: { type: BlockEnum.DataSource, title: 'Source' } },+ { id: 'llm-1', data: { type: BlockEnum.LLM, title: 'LLM' } },+ { id: 'end-1', data: { type: BlockEnum.End, title: 'End' } },+ )++ const { result } = renderHook(() => useDatasourceOptions())++ expect(result.current).toHaveLength(1)+ expect(result.current[0].value).toBe('ds-1')+ })+})++describe('useOnlineDocument', () => {+ it('should clear all online document data', () => {+ const mockSetDocumentsData = vi.fn()+ const mockSetSearchValue = vi.fn()+ const mockSetSelectedPagesId = vi.fn()+ const mockSetOnlineDocuments = vi.fn()+ const mockSetCurrentDocument = vi.fn()++ mockDataSourceStoreGetState.mockReturnValue({+ setDocumentsData: mockSetDocumentsData,+ setSearchValue: mockSetSearchValue,+ setSelectedPagesId: mockSetSelectedPagesId,+ setOnlineDocuments: mockSetOnlineDocuments,+ setCurrentDocument: mockSetCurrentDocument,+ })++ const { result } = renderHook(() => useOnlineDocument())++ act(() => {+ result.current.clearOnlineDocumentData()+ })++ expect(mockSetDocumentsData).toHaveBeenCalledWith([])+ expect(mockSetSearchValue).toHaveBeenCalledWith('')+ expect(mockSetSelectedPagesId).toHaveBeenCalledWith(new Set())+ expect(mockSetOnlineDocuments).toHaveBeenCalledWith([])+ expect(mockSetCurrentDocument).toHaveBeenCalledWith(undefined)+ })+})++describe('useWebsiteCrawl', () => {+ it('should clear all website crawl data', () => {+ const mockSetStep = vi.fn()+ const mockSetCrawlResult = vi.fn()+ const mockSetWebsitePages = vi.fn()+ const mockSetPreviewIndex = vi.fn()+ const mockSetCurrentWebsite = vi.fn()++ mockDataSourceStoreGetState.mockReturnValue({+ setStep: mockSetStep,+ setCrawlResult: mockSetCrawlResult,+ setWebsitePages: mockSetWebsitePages,+ setPreviewIndex: mockSetPreviewIndex,+ setCurrentWebsite: mockSetCurrentWebsite,+ })++ const { result } = renderHook(() => useWebsiteCrawl())++ act(() => {+ result.current.clearWebsiteCrawlData()+ })++ expect(mockSetStep).toHaveBeenCalledWith('init')+ expect(mockSetCrawlResult).toHaveBeenCalledWith(undefined)+ expect(mockSetCurrentWebsite).toHaveBeenCalledWith(undefined)+ expect(mockSetWebsitePages).toHaveBeenCalledWith([])+ expect(mockSetPreviewIndex).toHaveBeenCalledWith(-1)+ })+})++describe('useOnlineDrive', () => {+ it('should clear all online drive data', () => {+ const mockSetOnlineDriveFileList = vi.fn()+ const mockSetBucket = vi.fn()+ const mockSetPrefix = vi.fn()+ const mockSetKeywords = vi.fn()+ const mockSetSelectedFileIds = vi.fn()++ mockDataSourceStoreGetState.mockReturnValue({+ setOnlineDriveFileList: mockSetOnlineDriveFileList,+ setBucket: mockSetBucket,+ setPrefix: mockSetPrefix,+ setKeywords: mockSetKeywords,+ setSelectedFileIds: mockSetSelectedFileIds,+ })++ const { result } = renderHook(() => useOnlineDrive())++ act(() => {+ result.current.clearOnlineDriveData()+ })++ expect(mockSetOnlineDriveFileList).toHaveBeenCalledWith([])+ expect(mockSetBucket).toHaveBeenCalledWith('')+ expect(mockSetPrefix).toHaveBeenCalledWith([])+ expect(mockSetKeywords).toHaveBeenCalledWith('')+ expect(mockSetSelectedFileIds).toHaveBeenCalledWith([])+ })+})diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/preparation/__tests__/index.spec.tsxsimilarity index 76%rename from web/app/components/rag-pipeline/components/panel/test-run/preparation/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/test-run/preparation/__tests__/index.spec.tsxindex 0aa7df0fa8e..a7956927c18 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/__tests__/index.spec.tsx@@ -1,27 +1,21 @@-import type { Datasource } from '../types'+import type { Datasource } from '../../types'import type { DataSourceNodeType } from '@/app/components/workflow/nodes/data-source/types'import { act, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { DatasourceType } from '@/models/pipeline'-import FooterTips from './footer-tips'+import FooterTips from '../footer-tips'import {useDatasourceOptions,useOnlineDocument,useOnlineDrive,useTestRunSteps,useWebsiteCrawl,-} from './hooks'-import Preparation from './index'-import StepIndicator from './step-indicator'+} from '../hooks'+import Preparation from '../index'+import StepIndicator from '../step-indicator'-// ============================================================================-// Pre-declare variables and functions used in mocks (hoisting)-// ============================================================================--// Mock Nodes for useDatasourceOptions - must be declared before vi.mocklet mockNodes: Array<{ id: string, data: DataSourceNodeType }> = []-// Test Data Factory - must be declared before vi.mock that uses itconst createNodeData = (overrides?: Partial<DataSourceNodeType>): DataSourceNodeType => ({title: 'Test Node',desc: 'Test description',@@ -36,39 +30,18 @@ const createNodeData = (overrides?: Partial<DataSourceNodeType>): DataSourceNode...overrides,} as unknown as DataSourceNodeType)-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock react-i18next-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, options?: { ns?: string }) => {- const ns = options?.ns ? `${options.ns}.` : ''- return `${ns}${key}`- },- }),-}))--// Mock reactflowvi.mock('reactflow', () => ({useNodes: () => mockNodes,}))-// Mock zustand/react/shallowvi.mock('zustand/react/shallow', () => ({useShallow: <T,>(fn: (state: unknown) => T) => fn,}))-// Mock amplitude trackingvi.mock('@/app/components/base/amplitude', () => ({trackEvent: vi.fn(),}))-// ============================================================================-// Mock Data Source Store-// ============================================================================-let mockDataSourceStoreState = {localFileList: [] as Array<{ file: { id: string, name: string, type: string, size: number, extension: string, mime_type: string } }>,onlineDocuments: [] as Array<{ workspace_id: string, page_id?: string, title?: string }>,@@ -103,10 +76,6 @@ vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/stuseDataSourceStoreWithSelector: <T,>(selector: (state: typeof mockDataSourceStoreState) => T) => selector(mockDataSourceStoreState),}))-// ============================================================================-// Mock Workflow Store-// ============================================================================-let mockWorkflowStoreState = {setIsPreparingDataSource: vi.fn(),pipelineId: 'test-pipeline-id',@@ -119,10 +88,6 @@ vi.mock('@/app/components/workflow/store', () => ({useStore: <T,>(selector: (state: typeof mockWorkflowStoreState) => T) => selector(mockWorkflowStoreState),}))-// ============================================================================-// Mock Workflow Hooks-// ============================================================================-const mockHandleRun = vi.fn()vi.mock('@/app/components/workflow/hooks', () => ({@@ -132,10 +97,6 @@ vi.mock('@/app/components/workflow/hooks', () => ({useToolIcon: () => ({ type: 'icon', icon: 'test-icon' }),}))-// ============================================================================-// Mock Child Components-// ============================================================================-vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/local-file', () => ({default: ({ allowedExtensions, supportBatchUpload }: { allowedExtensions: string[], supportBatchUpload: boolean }) => (<div data-testid="local-file" data-extensions={JSON.stringify(allowedExtensions)} data-batch={supportBatchUpload}>@@ -179,7 +140,7 @@ vi.mock('@/app/components/datasets/documents/create-from-pipeline/data-source/on),}))-vi.mock('./data-source-options', () => ({+vi.mock('../data-source-options', () => ({default: ({ dataSourceNodeId, onSelect }: { dataSourceNodeId: string, onSelect: (ds: Datasource) => void }) => (<div data-testid="data-source-options" data-selected={dataSourceNodeId}><button@@ -232,7 +193,7 @@ vi.mock('./data-source-options', () => ({),}))-vi.mock('./document-processing', () => ({+vi.mock('../document-processing', () => ({default: ({ dataSourceNodeId, onProcess, onBack }: { dataSourceNodeId: string, onProcess: (data: Record<string, unknown>) => void, onBack: () => void }) => (<div data-testid="document-processing" data-node-id={dataSourceNodeId}><button data-testid="process-btn" onClick={() => onProcess({ field1: 'value1' })}>Process</button>@@ -242,10 +203,6 @@ vi.mock('./document-processing', () => ({),}))-// ============================================================================-// Helper to reset all mocks-// ============================================================================-const resetAllMocks = () => {mockDataSourceStoreState = {localFileList: [],@@ -281,10 +238,6 @@ const resetAllMocks = () => {mockHandleRun.mockClear()}-// ============================================================================-// StepIndicator Component Tests-// ============================================================================-describe('StepIndicator', () => {beforeEach(() => {vi.clearAllMocks()@@ -296,40 +249,30 @@ describe('StepIndicator', () => {{ label: 'Step 3', value: 'step3' },]- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {- // Arrange & Actrender(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Assertexpect(screen.getByText('Step 1')).toBeInTheDocument()expect(screen.getByText('Step 2')).toBeInTheDocument()expect(screen.getByText('Step 3')).toBeInTheDocument()})it('should render all step labels', () => {- // Arrangeconst steps = [{ label: 'Data Source', value: 'dataSource' },{ label: 'Processing', value: 'processing' },]- // Actrender(<StepIndicator steps={steps} currentStep={1} />)- // Assertexpect(screen.getByText('Data Source')).toBeInTheDocument()expect(screen.getByText('Processing')).toBeInTheDocument()})it('should render container with correct classes', () => {- // Arrange & Actconst { container } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Assertconst wrapper = container.firstChild as HTMLElementexpect(wrapper.className).toContain('flex')expect(wrapper.className).toContain('items-center')@@ -339,112 +282,82 @@ describe('StepIndicator', () => {})it('should render divider between steps but not after last step', () => {- // Arrange & Actconst { container } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Assert - Should have 2 dividers for 3 stepsconst dividers = container.querySelectorAll('.h-px.w-3')expect(dividers.length).toBe(2)})it('should not render divider when there is only one step', () => {- // Arrangeconst singleStep = [{ label: 'Only Step', value: 'only' }]- // Actconst { container } = render(<StepIndicator steps={singleStep} currentStep={1} />)- // Assertconst dividers = container.querySelectorAll('.h-px.w-3')expect(dividers.length).toBe(0)})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should highlight first step when currentStep is 1', () => {- // Arrange & Actconst { container } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Assert - Check for accent indicator on first stepconst indicators = container.querySelectorAll('.bg-state-accent-solid')expect(indicators.length).toBe(1) // The dot indicator})it('should highlight second step when currentStep is 2', () => {- // Arrange & Actrender(<StepIndicator steps={defaultSteps} currentStep={2} />)- // Assertconst step2Container = screen.getByText('Step 2').parentElementexpect(step2Container?.className).toContain('text-state-accent-solid')})it('should highlight third step when currentStep is 3', () => {- // Arrange & Actrender(<StepIndicator steps={defaultSteps} currentStep={3} />)- // Assertconst step3Container = screen.getByText('Step 3').parentElementexpect(step3Container?.className).toContain('text-state-accent-solid')})it('should apply tertiary color to non-current steps', () => {- // Arrange & Actrender(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Assertconst step2Container = screen.getByText('Step 2').parentElementexpect(step2Container?.className).toContain('text-text-tertiary')})it('should show dot indicator only for current step', () => {- // Arrange & Actconst { container } = render(<StepIndicator steps={defaultSteps} currentStep={2} />)- // Assert - Only one dot should existconst dots = container.querySelectorAll('.size-1.rounded-full')expect(dots.length).toBe(1)})it('should handle empty steps array', () => {- // Arrange & Actconst { container } = render(<StepIndicator steps={[]} currentStep={1} />)- // Assertexpect(container.firstChild).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with React.memo', () => {- // Arrange & Actconst { rerender } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Rerender with same propsrerender(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Assert - Component should render correctlyexpect(screen.getByText('Step 1')).toBeInTheDocument()})it('should update when currentStep changes', () => {- // Arrangeconst { rerender } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Assert initial statelet step1Container = screen.getByText('Step 1').parentElementexpect(step1Container?.className).toContain('text-state-accent-solid')- // Act - Change steprerender(<StepIndicator steps={defaultSteps} currentStep={2} />)- // Assertstep1Container = screen.getByText('Step 1').parentElementexpect(step1Container?.className).toContain('text-text-tertiary')const step2Container = screen.getByText('Step 2').parentElement@@ -452,130 +365,95 @@ describe('StepIndicator', () => {})it('should update when steps array changes', () => {- // Arrangeconst { rerender } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)- // Actconst newSteps = [{ label: 'New Step 1', value: 'new1' },{ label: 'New Step 2', value: 'new2' },]rerender(<StepIndicator steps={newSteps} currentStep={1} />)- // Assertexpect(screen.getByText('New Step 1')).toBeInTheDocument()expect(screen.getByText('New Step 2')).toBeInTheDocument()expect(screen.queryByText('Step 3')).not.toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle currentStep of 0', () => {- // Arrange & Actconst { container } = render(<StepIndicator steps={defaultSteps} currentStep={0} />)- // Assert - No step should be highlighted (currentStep - 1 = -1)const dots = container.querySelectorAll('.size-1.rounded-full')expect(dots.length).toBe(0)})it('should handle currentStep greater than steps length', () => {- // Arrange & Actconst { container } = render(<StepIndicator steps={defaultSteps} currentStep={10} />)- // Assert - No step should be highlightedconst dots = container.querySelectorAll('.size-1.rounded-full')expect(dots.length).toBe(0)})it('should handle steps with empty labels', () => {- // Arrangeconst stepsWithEmpty = [{ label: '', value: 'empty' },{ label: 'Valid', value: 'valid' },]- // Actrender(<StepIndicator steps={stepsWithEmpty} currentStep={1} />)- // Assertexpect(screen.getByText('Valid')).toBeInTheDocument()})it('should handle steps with very long labels', () => {- // Arrangeconst longLabel = 'A'.repeat(100)const stepsWithLong = [{ label: longLabel, value: 'long' }]- // Actrender(<StepIndicator steps={stepsWithLong} currentStep={1} />)- // Assertexpect(screen.getByText(longLabel)).toBeInTheDocument()})it('should handle special characters in labels', () => {- // Arrangeconst specialSteps = [{ label: '<Test> & "Label"', value: 'special' }]- // Actrender(<StepIndicator steps={specialSteps} currentStep={1} />)- // Assertexpect(screen.getByText('<Test> & "Label"')).toBeInTheDocument()})it('should handle unicode characters in labels', () => {- // Arrangeconst unicodeSteps = [{ label: '数据源 🎉', value: 'unicode' }]- // Actrender(<StepIndicator steps={unicodeSteps} currentStep={1} />)- // Assertexpect(screen.getByText('数据源 🎉')).toBeInTheDocument()})it('should handle negative currentStep', () => {- // Arrange & Actconst { container } = render(<StepIndicator steps={defaultSteps} currentStep={-1} />)- // Assert - No step should be highlightedconst dots = container.querySelectorAll('.size-1.rounded-full')expect(dots.length).toBe(0)})})})-// ============================================================================-// FooterTips Component Tests-// ============================================================================-describe('FooterTips', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {- // Arrange & Actrender(<FooterTips />)- // Assert - Check for translated textexpect(screen.getByText('datasetPipeline.testRun.tooltip')).toBeInTheDocument()})it('should render with correct container classes', () => {- // Arrange & Actconst { container } = render(<FooterTips />)- // Assertconst wrapper = container.firstChild as HTMLElementexpect(wrapper.className).toContain('system-xs-regular')expect(wrapper.className).toContain('flex')@@ -588,226 +466,161 @@ describe('FooterTips', () => {})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with React.memo', () => {- // Arrange & Actconst { rerender } = render(<FooterTips />)- // Rerenderrerender(<FooterTips />)- // Assertexpect(screen.getByText('datasetPipeline.testRun.tooltip')).toBeInTheDocument()})it('should render consistently across multiple rerenders', () => {- // Arrangeconst { rerender } = render(<FooterTips />)- // Act - Multiple rerendersfor (let i = 0; i < 5; i++)rerender(<FooterTips />)- // Assertexpect(screen.getByText('datasetPipeline.testRun.tooltip')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle unmount cleanly', () => {- // Arrangeconst { unmount } = render(<FooterTips />)- // Assertexpect(() => unmount()).not.toThrow()})})})-// ============================================================================-// useTestRunSteps Hook Tests-// ============================================================================-describe('useTestRunSteps', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Initial State Tests- // -------------------------------------------------------------------------describe('Initial State', () => {it('should initialize with currentStep as 1', () => {- // Arrange & Actconst { result } = renderHook(() => useTestRunSteps())- // Assertexpect(result.current.currentStep).toBe(1)})it('should provide steps array with data source and document processing steps', () => {- // Arrange & Actconst { result } = renderHook(() => useTestRunSteps())- // Assertexpect(result.current.steps).toHaveLength(2)expect(result.current.steps[0].value).toBe('dataSource')expect(result.current.steps[1].value).toBe('documentProcessing')})it('should provide translated step labels', () => {- // Arrange & Actconst { result } = renderHook(() => useTestRunSteps())- // Assertexpect(result.current.steps[0].label).toContain('testRun.steps.dataSource')expect(result.current.steps[1].label).toContain('testRun.steps.documentProcessing')})})- // -------------------------------------------------------------------------- // handleNextStep Tests- // -------------------------------------------------------------------------describe('handleNextStep', () => {it('should increment currentStep by 1', () => {- // Arrangeconst { result } = renderHook(() => useTestRunSteps())- // Actact(() => {result.current.handleNextStep()})- // Assertexpect(result.current.currentStep).toBe(2)})it('should continue incrementing on multiple calls', () => {- // Arrangeconst { result } = renderHook(() => useTestRunSteps())- // Actact(() => {result.current.handleNextStep()result.current.handleNextStep()result.current.handleNextStep()})- // Assertexpect(result.current.currentStep).toBe(4)})})- // -------------------------------------------------------------------------- // handleBackStep Tests- // -------------------------------------------------------------------------describe('handleBackStep', () => {it('should decrement currentStep by 1', () => {- // Arrangeconst { result } = renderHook(() => useTestRunSteps())- // First go to step 2act(() => {result.current.handleNextStep()})expect(result.current.currentStep).toBe(2)- // Actact(() => {result.current.handleBackStep()})- // Assertexpect(result.current.currentStep).toBe(1)})it('should allow going to negative steps (no validation)', () => {- // Arrangeconst { result } = renderHook(() => useTestRunSteps())- // Actact(() => {result.current.handleBackStep()})- // Assertexpect(result.current.currentStep).toBe(0)})it('should continue decrementing on multiple calls', () => {- // Arrangeconst { result } = renderHook(() => useTestRunSteps())- // Go to step 5act(() => {for (let i = 0; i < 4; i++)result.current.handleNextStep()})expect(result.current.currentStep).toBe(5)- // Act - Go back 3 stepsact(() => {result.current.handleBackStep()result.current.handleBackStep()result.current.handleBackStep()})- // Assertexpect(result.current.currentStep).toBe(2)})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should return stable handleNextStep callback', () => {- // Arrangeconst { result, rerender } = renderHook(() => useTestRunSteps())const initialCallback = result.current.handleNextStep- // Actrerender()- // Assertexpect(result.current.handleNextStep).toBe(initialCallback)})it('should return stable handleBackStep callback', () => {- // Arrangeconst { result, rerender } = renderHook(() => useTestRunSteps())const initialCallback = result.current.handleBackStep- // Actrerender()- // Assertexpect(result.current.handleBackStep).toBe(initialCallback)})})- // -------------------------------------------------------------------------- // Integration Tests- // -------------------------------------------------------------------------describe('Integration', () => {it('should handle forward and backward navigation', () => {- // Arrangeconst { result } = renderHook(() => useTestRunSteps())- // Act & Assert - Navigate forwardact(() => result.current.handleNextStep())expect(result.current.currentStep).toBe(2)act(() => result.current.handleNextStep())expect(result.current.currentStep).toBe(3)- // Act & Assert - Navigate backwardact(() => result.current.handleBackStep())expect(result.current.currentStep).toBe(2)@@ -817,33 +630,22 @@ describe('useTestRunSteps', () => {})})-// ============================================================================-// useDatasourceOptions Hook Tests-// ============================================================================-describe('useDatasourceOptions', () => {beforeEach(() => {vi.clearAllMocks()resetAllMocks()})- // -------------------------------------------------------------------------- // Basic Functionality Tests- // -------------------------------------------------------------------------describe('Basic Functionality', () => {it('should return empty array when no nodes exist', () => {- // ArrangemockNodes = []- // Actconst { result } = renderHook(() => useDatasourceOptions())- // Assertexpect(result.current).toEqual([])})it('should return empty array when no DataSource nodes exist', () => {- // ArrangemockNodes = [{id: 'node-1',@@ -854,15 +656,12 @@ describe('useDatasourceOptions', () => {},]- // Actconst { result } = renderHook(() => useDatasourceOptions())- // Assertexpect(result.current).toEqual([])})it('should return options for DataSource nodes only', () => {- // ArrangemockNodes = [{id: 'datasource-1',@@ -887,10 +686,8 @@ describe('useDatasourceOptions', () => {},]- // Actconst { result } = renderHook(() => useDatasourceOptions())- // Assertexpect(result.current).toHaveLength(2)expect(result.current[0]).toEqual({label: 'Local File Source',@@ -905,7 +702,6 @@ describe('useDatasourceOptions', () => {})it('should map node id to option value', () => {- // ArrangemockNodes = [{id: 'unique-node-id-123',@@ -916,15 +712,12 @@ describe('useDatasourceOptions', () => {},]- // Actconst { result } = renderHook(() => useDatasourceOptions())- // Assertexpect(result.current[0].value).toBe('unique-node-id-123')})it('should map node title to option label', () => {- // ArrangemockNodes = [{id: 'node-1',@@ -935,15 +728,12 @@ describe('useDatasourceOptions', () => {},]- // Actconst { result } = renderHook(() => useDatasourceOptions())- // Assertexpect(result.current[0].label).toBe('Custom Data Source Title')})it('should include full node data in option', () => {- // Arrangeconst nodeData = {...createNodeData({title: 'Full Data Test',@@ -960,20 +750,14 @@ describe('useDatasourceOptions', () => {},]- // Actconst { result } = renderHook(() => useDatasourceOptions())- // Assertexpect(result.current[0].data).toEqual(nodeData)})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should return same options reference when nodes do not change', () => {- // ArrangemockNodes = [{id: 'node-1',@@ -984,18 +768,15 @@ describe('useDatasourceOptions', () => {},]- // Actconst { result, rerender } = renderHook(() => useDatasourceOptions())rerender()- // Assert - Options should be memoized and still work correctly after rerenderexpect(result.current).toHaveLength(1)expect(result.current[0].label).toBe('Test')})it('should update options when nodes change', () => {- // ArrangemockNodes = [{id: 'node-1',@@ -1010,7 +791,6 @@ describe('useDatasourceOptions', () => {expect(result.current).toHaveLength(1)expect(result.current[0].label).toBe('First')- // Act - Change nodesmockNodes = [{id: 'node-2',@@ -1029,19 +809,14 @@ describe('useDatasourceOptions', () => {]rerender()- // Assertexpect(result.current).toHaveLength(2)expect(result.current[0].label).toBe('Second')expect(result.current[1].label).toBe('Third')})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle nodes with empty title', () => {- // ArrangemockNodes = [{id: 'node-1',@@ -1052,15 +827,12 @@ describe('useDatasourceOptions', () => {},]- // Actconst { result } = renderHook(() => useDatasourceOptions())- // Assertexpect(result.current[0].label).toBe('')})it('should handle multiple DataSource nodes', () => {- // ArrangemockNodes = Array.from({ length: 10 }, (_, i) => ({id: `node-${i}`,data: {@@ -1069,10 +841,8 @@ describe('useDatasourceOptions', () => {} as DataSourceNodeType,}))- // Actconst { result } = renderHook(() => useDatasourceOptions())- // Assertexpect(result.current).toHaveLength(10)result.current.forEach((option, i) => {expect(option.value).toBe(`node-${i}`)@@ -1082,30 +852,20 @@ describe('useDatasourceOptions', () => {})})-// ============================================================================-// useOnlineDocument Hook Tests-// ============================================================================-describe('useOnlineDocument', () => {beforeEach(() => {vi.clearAllMocks()resetAllMocks()})- // -------------------------------------------------------------------------- // clearOnlineDocumentData Tests- // -------------------------------------------------------------------------describe('clearOnlineDocumentData', () => {it('should clear all online document related data', () => {- // Arrangeconst { result } = renderHook(() => useOnlineDocument())- // Actact(() => {result.current.clearOnlineDocumentData()})- // Assertexpect(mockDataSourceStoreState.setDocumentsData).toHaveBeenCalledWith([])expect(mockDataSourceStoreState.setSearchValue).toHaveBeenCalledWith('')expect(mockDataSourceStoreState.setSelectedPagesId).toHaveBeenCalledWith(new Set())@@ -1114,7 +874,6 @@ describe('useOnlineDocument', () => {})it('should call all clear functions in correct order', () => {- // Arrangeconst { result } = renderHook(() => useOnlineDocument())const callOrder: string[] = []mockDataSourceStoreState.setDocumentsData = vi.fn(() => callOrder.push('setDocumentsData'))@@ -1123,12 +882,10 @@ describe('useOnlineDocument', () => {mockDataSourceStoreState.setOnlineDocuments = vi.fn(() => callOrder.push('setOnlineDocuments'))mockDataSourceStoreState.setCurrentDocument = vi.fn(() => callOrder.push('setCurrentDocument'))- // Actact(() => {result.current.clearOnlineDocumentData()})- // Assertexpect(callOrder).toEqual(['setDocumentsData','setSearchValue',@@ -1139,58 +896,40 @@ describe('useOnlineDocument', () => {})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain functional callback after rerender', () => {- // Arrangeconst { result, rerender } = renderHook(() => useOnlineDocument())- // Act - First callact(() => {result.current.clearOnlineDocumentData()})const firstCallCount = mockDataSourceStoreState.setDocumentsData.mock.calls.length- // Rerenderrerender()- // Act - Second call after rerenderact(() => {result.current.clearOnlineDocumentData()})- // Assert - Callback should still work after rerenderexpect(mockDataSourceStoreState.setDocumentsData.mock.calls.length).toBe(firstCallCount + 1)})})})-// ============================================================================-// useWebsiteCrawl Hook Tests-// ============================================================================-describe('useWebsiteCrawl', () => {beforeEach(() => {vi.clearAllMocks()resetAllMocks()})- // -------------------------------------------------------------------------- // clearWebsiteCrawlData Tests- // -------------------------------------------------------------------------describe('clearWebsiteCrawlData', () => {it('should clear all website crawl related data', () => {- // Arrangeconst { result } = renderHook(() => useWebsiteCrawl())- // Actact(() => {result.current.clearWebsiteCrawlData()})- // Assertexpect(mockDataSourceStoreState.setStep).toHaveBeenCalledWith('init')expect(mockDataSourceStoreState.setCrawlResult).toHaveBeenCalledWith(undefined)expect(mockDataSourceStoreState.setCurrentWebsite).toHaveBeenCalledWith(undefined)@@ -1199,7 +938,6 @@ describe('useWebsiteCrawl', () => {})it('should call all clear functions in correct order', () => {- // Arrangeconst { result } = renderHook(() => useWebsiteCrawl())const callOrder: string[] = []mockDataSourceStoreState.setStep = vi.fn(() => callOrder.push('setStep'))@@ -1208,12 +946,10 @@ describe('useWebsiteCrawl', () => {mockDataSourceStoreState.setWebsitePages = vi.fn(() => callOrder.push('setWebsitePages'))mockDataSourceStoreState.setPreviewIndex = vi.fn(() => callOrder.push('setPreviewIndex'))- // Actact(() => {result.current.clearWebsiteCrawlData()})- // Assertexpect(callOrder).toEqual(['setStep','setCrawlResult',@@ -1224,58 +960,40 @@ describe('useWebsiteCrawl', () => {})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain functional callback after rerender', () => {- // Arrangeconst { result, rerender } = renderHook(() => useWebsiteCrawl())- // Act - First callact(() => {result.current.clearWebsiteCrawlData()})const firstCallCount = mockDataSourceStoreState.setStep.mock.calls.length- // Rerenderrerender()- // Act - Second call after rerenderact(() => {result.current.clearWebsiteCrawlData()})- // Assert - Callback should still work after rerenderexpect(mockDataSourceStoreState.setStep.mock.calls.length).toBe(firstCallCount + 1)})})})-// ============================================================================-// useOnlineDrive Hook Tests-// ============================================================================-describe('useOnlineDrive', () => {beforeEach(() => {vi.clearAllMocks()resetAllMocks()})- // -------------------------------------------------------------------------- // clearOnlineDriveData Tests- // -------------------------------------------------------------------------describe('clearOnlineDriveData', () => {it('should clear all online drive related data', () => {- // Arrangeconst { result } = renderHook(() => useOnlineDrive())- // Actact(() => {result.current.clearOnlineDriveData()})- // Assertexpect(mockDataSourceStoreState.setOnlineDriveFileList).toHaveBeenCalledWith([])expect(mockDataSourceStoreState.setBucket).toHaveBeenCalledWith('')expect(mockDataSourceStoreState.setPrefix).toHaveBeenCalledWith([])@@ -1284,7 +1002,6 @@ describe('useOnlineDrive', () => {})it('should call all clear functions in correct order', () => {- // Arrangeconst { result } = renderHook(() => useOnlineDrive())const callOrder: string[] = []mockDataSourceStoreState.setOnlineDriveFileList = vi.fn(() => callOrder.push('setOnlineDriveFileList'))@@ -1293,12 +1010,10 @@ describe('useOnlineDrive', () => {mockDataSourceStoreState.setKeywords = vi.fn(() => callOrder.push('setKeywords'))mockDataSourceStoreState.setSelectedFileIds = vi.fn(() => callOrder.push('setSelectedFileIds'))- // Actact(() => {result.current.clearOnlineDriveData()})- // Assertexpect(callOrder).toEqual(['setOnlineDriveFileList','setBucket',@@ -1309,398 +1024,291 @@ describe('useOnlineDrive', () => {})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain functional callback after rerender', () => {- // Arrangeconst { result, rerender } = renderHook(() => useOnlineDrive())- // Act - First callact(() => {result.current.clearOnlineDriveData()})const firstCallCount = mockDataSourceStoreState.setOnlineDriveFileList.mock.calls.length- // Rerenderrerender()- // Act - Second call after rerenderact(() => {result.current.clearOnlineDriveData()})- // Assert - Callback should still work after rerenderexpect(mockDataSourceStoreState.setOnlineDriveFileList.mock.calls.length).toBe(firstCallCount + 1)})})})-// ============================================================================-// Preparation Component Tests-// ============================================================================-describe('Preparation', () => {beforeEach(() => {vi.clearAllMocks()resetAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {- // Arrange & Actrender(<Preparation />)- // Assertexpect(screen.getByTestId('data-source-options')).toBeInTheDocument()})it('should render StepIndicator', () => {- // Arrange & Actrender(<Preparation />)- // Assert - Check for step textexpect(screen.getByText('datasetPipeline.testRun.steps.dataSource')).toBeInTheDocument()expect(screen.getByText('datasetPipeline.testRun.steps.documentProcessing')).toBeInTheDocument()})it('should render DataSourceOptions on step 1', () => {- // Arrange & Actrender(<Preparation />)- // Assertexpect(screen.getByTestId('data-source-options')).toBeInTheDocument()})it('should render Actions on step 1', () => {- // Arrange & Actrender(<Preparation />)- // Assertexpect(screen.getByText('datasetCreation.stepOne.button')).toBeInTheDocument()})it('should render FooterTips on step 1', () => {- // Arrange & Actrender(<Preparation />)- // Assertexpect(screen.getByText('datasetPipeline.testRun.tooltip')).toBeInTheDocument()})it('should not render DocumentProcessing on step 1', () => {- // Arrange & Actrender(<Preparation />)- // Assertexpect(screen.queryByTestId('document-processing')).not.toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Data Source Selection Tests- // -------------------------------------------------------------------------describe('Data Source Selection', () => {it('should render LocalFile component when local file datasource is selected', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(screen.getByTestId('local-file')).toBeInTheDocument()})it('should render OnlineDocuments component when online document datasource is selected', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-document'))- // Assertexpect(screen.getByTestId('online-documents')).toBeInTheDocument()})it('should render WebsiteCrawl component when website crawl datasource is selected', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-website-crawl'))- // Assertexpect(screen.getByTestId('website-crawl')).toBeInTheDocument()})it('should render OnlineDrive component when online drive datasource is selected', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-drive'))- // Assertexpect(screen.getByTestId('online-drive')).toBeInTheDocument()})it('should pass correct props to LocalFile component', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))- // Assertconst localFile = screen.getByTestId('local-file')expect(localFile).toHaveAttribute('data-extensions', '["txt","pdf"]')expect(localFile).toHaveAttribute('data-batch', 'false')})it('should pass isInPipeline=true to OnlineDocuments', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-document'))- // Assertconst onlineDocs = screen.getByTestId('online-documents')expect(onlineDocs).toHaveAttribute('data-in-pipeline', 'true')})it('should pass supportBatchUpload=false to all data source components', () => {- // Arrangerender(<Preparation />)- // Act - Select online documentfireEvent.click(screen.getByTestId('select-online-document'))- // Assertexpect(screen.getByTestId('online-documents')).toHaveAttribute('data-batch', 'false')})it('should update dataSourceNodeId when selecting different datasources', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(screen.getByTestId('data-source-options')).toHaveAttribute('data-selected', 'local-file-node')- // Act - Select anotherfireEvent.click(screen.getByTestId('select-online-document'))- // Assertexpect(screen.getByTestId('data-source-options')).toHaveAttribute('data-selected', 'online-doc-node')})})- // -------------------------------------------------------------------------- // Next Button Disabled State Tests- // -------------------------------------------------------------------------describe('Next Button Disabled State', () => {it('should disable next button when no datasource is selected', () => {- // Arrange & Actrender(<Preparation />)- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()})it('should disable next button for local file when file list is empty', () => {- // ArrangemockDataSourceStoreState.localFileList = []render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()})it('should disable next button for local file when file has no id', () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: '', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()})it('should enable next button for local file when file has valid id', () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})it('should disable next button for online document when documents list is empty', () => {- // ArrangemockDataSourceStoreState.onlineDocuments = []render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-document'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()})it('should enable next button for online document when documents exist', () => {- // ArrangemockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1', page_id: 'page-1' }]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-document'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})it('should disable next button for website crawl when pages list is empty', () => {- // ArrangemockDataSourceStoreState.websitePages = []render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-website-crawl'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()})it('should enable next button for website crawl when pages exist', () => {- // ArrangemockDataSourceStoreState.websitePages = [{ url: 'https://example.com' }]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-website-crawl'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})it('should disable next button for online drive when no files selected', () => {- // ArrangemockDataSourceStoreState.selectedFileIds = []render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-drive'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()})it('should enable next button for online drive when files are selected', () => {- // ArrangemockDataSourceStoreState.selectedFileIds = ['file-1']render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-drive'))- // Assertexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})})- // -------------------------------------------------------------------------- // Step Navigation Tests- // -------------------------------------------------------------------------describe('Step Navigation', () => {it('should navigate to step 2 when next button is clicked with valid data', () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // Act - Select datasource and click nextfireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))- // Assertexpect(screen.getByTestId('document-processing')).toBeInTheDocument()expect(screen.queryByTestId('data-source-options')).not.toBeInTheDocument()})it('should pass correct dataSourceNodeId to DocumentProcessing', () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))- // Assertexpect(screen.getByTestId('document-processing')).toHaveAttribute('data-node-id', 'local-file-node')})it('should navigate back to step 1 when back button is clicked', () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // Act - Go to step 2fireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))expect(screen.getByTestId('document-processing')).toBeInTheDocument()- // Act - Go backfireEvent.click(screen.getByTestId('back-btn'))- // Assertexpect(screen.getByTestId('data-source-options')).toBeInTheDocument()expect(screen.queryByTestId('document-processing')).not.toBeInTheDocument()})})- // -------------------------------------------------------------------------- // handleProcess Tests- // -------------------------------------------------------------------------describe('handleProcess', () => {it('should call handleRun with correct params for local file', async () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))fireEvent.click(screen.getByTestId('process-btn'))- // Assertawait waitFor(() => {expect(mockHandleRun).toHaveBeenCalledWith(expect.objectContaining({inputs: { field1: 'value1' },@@ -1711,17 +1319,14 @@ describe('Preparation', () => {})it('should call handleRun with correct params for online document', async () => {- // ArrangemockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1', page_id: 'page-1', title: 'Test Doc' }]mockDataSourceStoreState.currentCredentialId = 'cred-123'render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-document'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))fireEvent.click(screen.getByTestId('process-btn'))- // Assertawait waitFor(() => {expect(mockHandleRun).toHaveBeenCalledWith(expect.objectContaining({inputs: { field1: 'value1' },@@ -1732,17 +1337,14 @@ describe('Preparation', () => {})it('should call handleRun with correct params for website crawl', async () => {- // ArrangemockDataSourceStoreState.websitePages = [{ url: 'https://example.com', title: 'Example' }]mockDataSourceStoreState.currentCredentialId = 'cred-456'render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-website-crawl'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))fireEvent.click(screen.getByTestId('process-btn'))- // Assertawait waitFor(() => {expect(mockHandleRun).toHaveBeenCalledWith(expect.objectContaining({inputs: { field1: 'value1' },@@ -1753,19 +1355,16 @@ describe('Preparation', () => {})it('should call handleRun with correct params for online drive', async () => {- // ArrangemockDataSourceStoreState.selectedFileIds = ['file-1']mockDataSourceStoreState.onlineDriveFileList = [{ id: 'file-1', name: 'data.csv', type: 'file' }]mockDataSourceStoreState.bucket = 'my-bucket'mockDataSourceStoreState.currentCredentialId = 'cred-789'render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-drive'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))fireEvent.click(screen.getByTestId('process-btn'))- // Assertawait waitFor(() => {expect(mockHandleRun).toHaveBeenCalledWith(expect.objectContaining({inputs: { field1: 'value1' },@@ -1776,211 +1375,151 @@ describe('Preparation', () => {})it('should call setIsPreparingDataSource(false) after processing', async () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))fireEvent.click(screen.getByTestId('process-btn'))- // Assertawait waitFor(() => {expect(mockWorkflowStoreState.setIsPreparingDataSource).toHaveBeenCalledWith(false)})})})- // -------------------------------------------------------------------------- // clearDataSourceData Tests- // -------------------------------------------------------------------------describe('clearDataSourceData', () => {it('should clear online document data when switching from online document', () => {- // Arrangerender(<Preparation />)- // Act - Select online document firstfireEvent.click(screen.getByTestId('select-online-document'))- // Then switch to local filefireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(mockDataSourceStoreState.setDocumentsData).toHaveBeenCalled()expect(mockDataSourceStoreState.setOnlineDocuments).toHaveBeenCalled()})it('should clear website crawl data when switching from website crawl', () => {- // Arrangerender(<Preparation />)- // Act - Select website crawl firstfireEvent.click(screen.getByTestId('select-website-crawl'))- // Then switch to local filefireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(mockDataSourceStoreState.setWebsitePages).toHaveBeenCalled()expect(mockDataSourceStoreState.setCrawlResult).toHaveBeenCalled()})it('should clear online drive data when switching from online drive', () => {- // Arrangerender(<Preparation />)- // Act - Select online drive firstfireEvent.click(screen.getByTestId('select-online-drive'))- // Then switch to local filefireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(mockDataSourceStoreState.setOnlineDriveFileList).toHaveBeenCalled()expect(mockDataSourceStoreState.setBucket).toHaveBeenCalled()})})- // -------------------------------------------------------------------------- // handleCredentialChange Tests- // -------------------------------------------------------------------------describe('handleCredentialChange', () => {it('should update credential and clear data when credential changes for online document', () => {- // ArrangemockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1' }]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-document'))fireEvent.click(screen.getByText('Change Credential'))- // Assertexpect(mockDataSourceStoreState.setCurrentCredentialId).toHaveBeenCalledWith('new-credential-id')})it('should clear data when credential changes for website crawl', () => {- // ArrangemockDataSourceStoreState.websitePages = [{ url: 'https://example.com' }]render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-website-crawl'))fireEvent.click(screen.getByText('Change Credential'))- // Assertexpect(mockDataSourceStoreState.setCurrentCredentialId).toHaveBeenCalledWith('new-credential-id')expect(mockDataSourceStoreState.setWebsitePages).toHaveBeenCalled()})it('should clear data when credential changes for online drive', () => {- // ArrangemockDataSourceStoreState.selectedFileIds = ['file-1']render(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-online-drive'))fireEvent.click(screen.getByText('Change Credential'))- // Assertexpect(mockDataSourceStoreState.setCurrentCredentialId).toHaveBeenCalledWith('new-credential-id')expect(mockDataSourceStoreState.setOnlineDriveFileList).toHaveBeenCalled()})})- // -------------------------------------------------------------------------- // handleSwitchDataSource Tests- // -------------------------------------------------------------------------describe('handleSwitchDataSource', () => {it('should clear credential when switching datasource', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(mockDataSourceStoreState.setCurrentCredentialId).toHaveBeenCalledWith('')})it('should update currentNodeIdRef when switching datasource', () => {- // Arrangerender(<Preparation />)- // ActfireEvent.click(screen.getByTestId('select-local-file'))- // Assertexpect(mockDataSourceStoreState.currentNodeIdRef.current).toBe('local-file-node')})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with React.memo', () => {- // Arrange & Actconst { rerender } = render(<Preparation />)rerender(<Preparation />)- // Assertexpect(screen.getByTestId('data-source-options')).toBeInTheDocument()})it('should maintain state across rerenders', () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]const { rerender } = render(<Preparation />)- // Act - Select datasource and go to step 2fireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))- // Rerenderrerender(<Preparation />)- // Assert - Should still be on step 2expect(screen.getByTestId('document-processing')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle unmount cleanly', () => {- // Arrangeconst { unmount } = render(<Preparation />)- // Assertexpect(() => unmount()).not.toThrow()})it('should enable next button for unknown datasource type (return false branch)', () => {- // Arrange - This tests line 67: return false for unknown datasource typesrender(<Preparation />)- // Act - Select unknown type datasourcefireEvent.click(screen.getByTestId('select-unknown-type'))- // Assert - Button should NOT be disabled because unknown type returns false (not disabled)expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})it('should handle handleProcess with unknown datasource type', async () => {- // Arrange - This tests processing with unknown type, triggering default branchrender(<Preparation />)- // Act - Select unknown type and go to step 2fireEvent.click(screen.getByTestId('select-unknown-type'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))- // Process with unknown typefireEvent.click(screen.getByTestId('process-btn'))- // Assert - handleRun should be called with empty datasource_info_list (no type matched)await waitFor(() => {expect(mockHandleRun).toHaveBeenCalledWith(expect.objectContaining({start_node_id: 'unknown-type-node',@@ -1991,202 +1530,153 @@ describe('Preparation', () => {})it('should handle rapid datasource switching', () => {- // Arrangerender(<Preparation />)- // Act - Rapidly switch between datasourcesfireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByTestId('select-online-document'))fireEvent.click(screen.getByTestId('select-website-crawl'))fireEvent.click(screen.getByTestId('select-online-drive'))fireEvent.click(screen.getByTestId('select-local-file'))- // Assert - Should end up with local file selectedexpect(screen.getByTestId('local-file')).toBeInTheDocument()})it('should handle rapid step navigation', () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // Act - Select and navigatefireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))fireEvent.click(screen.getByTestId('back-btn'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))fireEvent.click(screen.getByTestId('back-btn'))- // Assert - Should be back on step 1expect(screen.getByTestId('data-source-options')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Integration Tests- // -------------------------------------------------------------------------describe('Integration', () => {it('should complete full flow: select datasource -> next -> process', async () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // Act - Step 1: Select datasourcefireEvent.click(screen.getByTestId('select-local-file'))expect(screen.getByTestId('local-file')).toBeInTheDocument()- // Act - Step 1: Click nextfireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))expect(screen.getByTestId('document-processing')).toBeInTheDocument()- // Act - Step 2: ProcessfireEvent.click(screen.getByTestId('process-btn'))- // Assertawait waitFor(() => {expect(mockHandleRun).toHaveBeenCalled()})})it('should complete full flow with back navigation', async () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]mockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1' }]render(<Preparation />)- // Act - Select local file and go to step 2fireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))expect(screen.getByTestId('document-processing')).toBeInTheDocument()- // Act - Go back and switch to online documentfireEvent.click(screen.getByTestId('back-btn'))fireEvent.click(screen.getByTestId('select-online-document'))expect(screen.getByTestId('online-documents')).toBeInTheDocument()- // Act - Go to step 2 againfireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))- // Assert - Should be on step 2 with online documentexpect(screen.getByTestId('document-processing')).toHaveAttribute('data-node-id', 'online-doc-node')})})})-// ============================================================================-// Callback Dependencies Tests-// ============================================================================-describe('Callback Dependencies', () => {beforeEach(() => {vi.clearAllMocks()resetAllMocks()})- // -------------------------------------------------------------------------- // nextBtnDisabled useMemo Dependencies- // -------------------------------------------------------------------------describe('nextBtnDisabled Memoization', () => {it('should update when localFileList changes', () => {- // Arrangeconst { rerender } = render(<Preparation />)fireEvent.click(screen.getByTestId('select-local-file'))- // Assert - Initially disabledexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()- // Act - Update localFileListmockDataSourceStoreState.localFileList = [{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]rerender(<Preparation />)fireEvent.click(screen.getByTestId('select-local-file'))- // Assert - Now enabledexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})it('should update when onlineDocuments changes', () => {- // Arrangeconst { rerender } = render(<Preparation />)fireEvent.click(screen.getByTestId('select-online-document'))- // Assert - Initially disabledexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()- // Act - Update onlineDocumentsmockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1' }]rerender(<Preparation />)fireEvent.click(screen.getByTestId('select-online-document'))- // Assert - Now enabledexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})it('should update when websitePages changes', () => {- // Arrangeconst { rerender } = render(<Preparation />)fireEvent.click(screen.getByTestId('select-website-crawl'))- // Assert - Initially disabledexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()- // Act - Update websitePagesmockDataSourceStoreState.websitePages = [{ url: 'https://example.com' }]rerender(<Preparation />)fireEvent.click(screen.getByTestId('select-website-crawl'))- // Assert - Now enabledexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})it('should update when selectedFileIds changes', () => {- // Arrangeconst { rerender } = render(<Preparation />)fireEvent.click(screen.getByTestId('select-online-drive'))- // Assert - Initially disabledexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()- // Act - Update selectedFileIdsmockDataSourceStoreState.selectedFileIds = ['file-1']rerender(<Preparation />)fireEvent.click(screen.getByTestId('select-online-drive'))- // Assert - Now enabledexpect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()})})- // -------------------------------------------------------------------------- // handleProcess useCallback Dependencies- // -------------------------------------------------------------------------describe('handleProcess Callback Dependencies', () => {it('should use latest store state when processing', async () => {- // ArrangemockDataSourceStoreState.localFileList = [{ file: { id: 'initial-file', name: 'initial.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },]render(<Preparation />)- // Act - Select and navigatefireEvent.click(screen.getByTestId('select-local-file'))fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))- // Update store before processingmockDataSourceStoreState.localFileList = [{ file: { id: 'updated-file', name: 'updated.txt', type: 'text/plain', size: 200, extension: 'txt', mime_type: 'text/plain' } },]fireEvent.click(screen.getByTestId('process-btn'))- // Assert - Should use latest fileawait waitFor(() => {expect(mockHandleRun).toHaveBeenCalledWith(expect.objectContaining({datasource_info_list: expect.arrayContaining([@@ -2197,24 +1687,16 @@ describe('Callback Dependencies', () => {})})- // -------------------------------------------------------------------------- // clearDataSourceData useCallback Dependencies- // -------------------------------------------------------------------------describe('clearDataSourceData Callback Dependencies', () => {it('should call correct clear function based on datasource type', () => {- // Arrangerender(<Preparation />)- // Act - Select online documentfireEvent.click(screen.getByTestId('select-online-document'))- // Assertexpect(mockDataSourceStoreState.setOnlineDocuments).toHaveBeenCalled()- // Act - Switch to website crawlfireEvent.click(screen.getByTestId('select-website-crawl'))- // Assertexpect(mockDataSourceStoreState.setWebsitePages).toHaveBeenCalled()})})diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/actions/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/preparation/actions/__tests__/index.spec.tsxsimilarity index 74%rename from web/app/components/rag-pipeline/components/panel/test-run/preparation/actions/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/test-run/preparation/actions/__tests__/index.spec.tsxindex 6899e4ac46c..95f24d3b105 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/actions/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/actions/__tests__/index.spec.tsx@@ -1,49 +1,33 @@import { fireEvent, render, screen } from '@testing-library/react'-import Actions from './index'--// ============================================================================-// Actions Component Tests-// ============================================================================+import Actions from '../index'describe('Actions', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions handleNextStep={handleNextStep} />)- // Assertexpect(screen.getByRole('button')).toBeInTheDocument()})it('should render button with translated text', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions handleNextStep={handleNextStep} />)- // Assert - Translation mock returns key with namespace prefixexpect(screen.getByText('datasetCreation.stepOne.button')).toBeInTheDocument()})it('should render with correct container structure', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { container } = render(<Actions handleNextStep={handleNextStep} />)- // Assertconst wrapper = container.firstChild as HTMLElementexpect(wrapper.className).toContain('flex')expect(wrapper.className).toContain('justify-end')@@ -52,197 +36,143 @@ describe('Actions', () => {})it('should render span with px-0.5 class around text', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { container } = render(<Actions handleNextStep={handleNextStep} />)- // Assertconst span = container.querySelector('span')expect(span).toBeInTheDocument()expect(span?.className).toContain('px-0.5')})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should pass disabled=true to button when disabled prop is true', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions disabled={true} handleNextStep={handleNextStep} />)- // Assertexpect(screen.getByRole('button')).toBeDisabled()})it('should pass disabled=false to button when disabled prop is false', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions disabled={false} handleNextStep={handleNextStep} />)- // Assertexpect(screen.getByRole('button')).not.toBeDisabled()})it('should not disable button when disabled prop is undefined', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions handleNextStep={handleNextStep} />)- // Assertexpect(screen.getByRole('button')).not.toBeDisabled()})it('should handle disabled switching from true to false', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { rerender } = render(<Actions disabled={true} handleNextStep={handleNextStep} />,)- // Assert - Initially disabledexpect(screen.getByRole('button')).toBeDisabled()- // Act - Rerender with disabled=falsererender(<Actions disabled={false} handleNextStep={handleNextStep} />)- // Assert - Now enabledexpect(screen.getByRole('button')).not.toBeDisabled()})it('should handle disabled switching from false to true', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { rerender } = render(<Actions disabled={false} handleNextStep={handleNextStep} />,)- // Assert - Initially enabledexpect(screen.getByRole('button')).not.toBeDisabled()- // Act - Rerender with disabled=truererender(<Actions disabled={true} handleNextStep={handleNextStep} />)- // Assert - Now disabledexpect(screen.getByRole('button')).toBeDisabled()})it('should handle undefined disabled becoming true', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { rerender } = render(<Actions handleNextStep={handleNextStep} />,)- // Assert - Initially not disabled (undefined)expect(screen.getByRole('button')).not.toBeDisabled()- // Act - Rerender with disabled=truererender(<Actions disabled={true} handleNextStep={handleNextStep} />)- // Assert - Now disabledexpect(screen.getByRole('button')).toBeDisabled()})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call handleNextStep when button is clicked', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions handleNextStep={handleNextStep} />)fireEvent.click(screen.getByRole('button'))- // Assertexpect(handleNextStep).toHaveBeenCalledTimes(1)})it('should call handleNextStep exactly once per click', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions handleNextStep={handleNextStep} />)fireEvent.click(screen.getByRole('button'))- // Assertexpect(handleNextStep).toHaveBeenCalled()expect(handleNextStep.mock.calls).toHaveLength(1)})it('should call handleNextStep multiple times on multiple clicks', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions handleNextStep={handleNextStep} />)const button = screen.getByRole('button')fireEvent.click(button)fireEvent.click(button)fireEvent.click(button)- // Assertexpect(handleNextStep).toHaveBeenCalledTimes(3)})it('should not call handleNextStep when button is disabled and clicked', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions disabled={true} handleNextStep={handleNextStep} />)fireEvent.click(screen.getByRole('button'))- // Assert - Disabled button should not trigger onClickexpect(handleNextStep).not.toHaveBeenCalled()})it('should handle rapid clicks when not disabled', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions handleNextStep={handleNextStep} />)const button = screen.getByRole('button')- // Simulate rapid clicksfor (let i = 0; i < 10; i++)fireEvent.click(button)- // Assertexpect(handleNextStep).toHaveBeenCalledTimes(10)})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should use the new handleNextStep when prop changes', () => {- // Arrangeconst handleNextStep1 = vi.fn()const handleNextStep2 = vi.fn()- // Actconst { rerender } = render(<Actions handleNextStep={handleNextStep1} />,)@@ -251,16 +181,13 @@ describe('Actions', () => {rerender(<Actions handleNextStep={handleNextStep2} />)fireEvent.click(screen.getByRole('button'))- // Assertexpect(handleNextStep1).toHaveBeenCalledTimes(1)expect(handleNextStep2).toHaveBeenCalledTimes(1)})it('should maintain functionality after rerender with same props', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { rerender } = render(<Actions handleNextStep={handleNextStep} />,)@@ -269,17 +196,14 @@ describe('Actions', () => {rerender(<Actions handleNextStep={handleNextStep} />)fireEvent.click(screen.getByRole('button'))- // Assertexpect(handleNextStep).toHaveBeenCalledTimes(2)})it('should work correctly when handleNextStep changes multiple times', () => {- // Arrangeconst handleNextStep1 = vi.fn()const handleNextStep2 = vi.fn()const handleNextStep3 = vi.fn()- // Actconst { rerender } = render(<Actions handleNextStep={handleNextStep1} />,)@@ -291,77 +215,58 @@ describe('Actions', () => {rerender(<Actions handleNextStep={handleNextStep3} />)fireEvent.click(screen.getByRole('button'))- // Assertexpect(handleNextStep1).toHaveBeenCalledTimes(1)expect(handleNextStep2).toHaveBeenCalledTimes(1)expect(handleNextStep3).toHaveBeenCalledTimes(1)})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped with React.memo', () => {- // Arrangeconst handleNextStep = vi.fn()- // Act - Verify component is memoized by checking display name patternconst { rerender } = render(<Actions handleNextStep={handleNextStep} />,)- // Rerender with same props should work without issuesrerender(<Actions handleNextStep={handleNextStep} />)- // Assert - Component should render correctly after rerenderexpect(screen.getByRole('button')).toBeInTheDocument()})it('should not break when props remain the same across rerenders', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { rerender } = render(<Actions disabled={false} handleNextStep={handleNextStep} />,)- // Multiple rerenders with same propsfor (let i = 0; i < 5; i++) {rerender(<Actions disabled={false} handleNextStep={handleNextStep} />)}- // Assert - Should still function correctlyfireEvent.click(screen.getByRole('button'))expect(handleNextStep).toHaveBeenCalledTimes(1)})it('should update correctly when only disabled prop changes', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { rerender } = render(<Actions disabled={false} handleNextStep={handleNextStep} />,)- // Assert - Initially not disabledexpect(screen.getByRole('button')).not.toBeDisabled()- // Act - Change only disabled proprerender(<Actions disabled={true} handleNextStep={handleNextStep} />)- // Assert - Should reflect the new disabled stateexpect(screen.getByRole('button')).toBeDisabled()})it('should update correctly when only handleNextStep prop changes', () => {- // Arrangeconst handleNextStep1 = vi.fn()const handleNextStep2 = vi.fn()- // Actconst { rerender } = render(<Actions disabled={false} handleNextStep={handleNextStep1} />,)@@ -369,169 +274,124 @@ describe('Actions', () => {fireEvent.click(screen.getByRole('button'))expect(handleNextStep1).toHaveBeenCalledTimes(1)- // Act - Change only handleNextStep proprerender(<Actions disabled={false} handleNextStep={handleNextStep2} />)fireEvent.click(screen.getByRole('button'))- // Assert - New callback should be usedexpect(handleNextStep1).toHaveBeenCalledTimes(1)expect(handleNextStep2).toHaveBeenCalledTimes(1)})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should call handleNextStep even if it has side effects', () => {- // Arrangelet sideEffectValue = 0const handleNextStep = vi.fn(() => {sideEffectValue = 42})- // Actrender(<Actions handleNextStep={handleNextStep} />)fireEvent.click(screen.getByRole('button'))- // Assertexpect(handleNextStep).toHaveBeenCalledTimes(1)expect(sideEffectValue).toBe(42)})it('should handle handleNextStep that returns a value', () => {- // Arrangeconst handleNextStep = vi.fn(() => 'return value')- // Actrender(<Actions handleNextStep={handleNextStep} />)fireEvent.click(screen.getByRole('button'))- // Assertexpect(handleNextStep).toHaveBeenCalledTimes(1)expect(handleNextStep).toHaveReturnedWith('return value')})it('should handle handleNextStep that is async', async () => {- // Arrangeconst handleNextStep = vi.fn().mockResolvedValue(undefined)- // Actrender(<Actions handleNextStep={handleNextStep} />)fireEvent.click(screen.getByRole('button'))- // Assertexpect(handleNextStep).toHaveBeenCalledTimes(1)})it('should render correctly with both disabled=true and handleNextStep', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions disabled={true} handleNextStep={handleNextStep} />)- // Assertconst button = screen.getByRole('button')expect(button).toBeDisabled()})it('should handle component unmount gracefully', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { unmount } = render(<Actions handleNextStep={handleNextStep} />)- // Assert - Unmount should not throwexpect(() => unmount()).not.toThrow()})it('should handle disabled as boolean-like falsy value', () => {- // Arrangeconst handleNextStep = vi.fn()- // Act - Test with explicit falserender(<Actions disabled={false} handleNextStep={handleNextStep} />)- // Assertexpect(screen.getByRole('button')).not.toBeDisabled()})})- // -------------------------------------------------------------------------- // Accessibility Tests- // -------------------------------------------------------------------------describe('Accessibility', () => {it('should have button element that can receive focus', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions handleNextStep={handleNextStep} />)const button = screen.getByRole('button')- // Assert - Button should be focusable (not disabled by default)expect(button).not.toBeDisabled()})it('should indicate disabled state correctly', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actrender(<Actions disabled={true} handleNextStep={handleNextStep} />)- // Assertexpect(screen.getByRole('button')).toHaveAttribute('disabled')})})- // -------------------------------------------------------------------------- // Integration Tests- // -------------------------------------------------------------------------describe('Integration', () => {it('should work in a typical workflow: enable -> click -> disable', () => {- // Arrangeconst handleNextStep = vi.fn()- // Act - Start enabledconst { rerender } = render(<Actions disabled={false} handleNextStep={handleNextStep} />,)- // Assert - Can click when enabledexpect(screen.getByRole('button')).not.toBeDisabled()fireEvent.click(screen.getByRole('button'))expect(handleNextStep).toHaveBeenCalledTimes(1)- // Act - Disable after click (simulating loading state)rerender(<Actions disabled={true} handleNextStep={handleNextStep} />)- // Assert - Cannot click when disabledexpect(screen.getByRole('button')).toBeDisabled()fireEvent.click(screen.getByRole('button'))expect(handleNextStep).toHaveBeenCalledTimes(1) // Still 1, not 2- // Act - Re-enablererender(<Actions disabled={false} handleNextStep={handleNextStep} />)- // Assert - Can click againexpect(screen.getByRole('button')).not.toBeDisabled()fireEvent.click(screen.getByRole('button'))expect(handleNextStep).toHaveBeenCalledTimes(2)})it('should maintain consistent rendering across multiple state changes', () => {- // Arrangeconst handleNextStep = vi.fn()- // Actconst { rerender } = render(<Actions disabled={false} handleNextStep={handleNextStep} />,)- // Toggle disabled state multiple timesconst states = [true, false, true, false, true]states.forEach((disabled) => {rerender(<Actions disabled={disabled} handleNextStep={handleNextStep} />)@@ -541,7 +401,6 @@ describe('Actions', () => {expect(screen.getByRole('button')).not.toBeDisabled()})- // Assert - Button should still render correctlyexpect(screen.getByRole('button')).toBeInTheDocument()expect(screen.getByText('datasetCreation.stepOne.button')).toBeInTheDocument()})diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/data-source-options/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/preparation/data-source-options/__tests__/index.spec.tsxsimilarity index 80%rename from web/app/components/rag-pipeline/components/panel/test-run/preparation/data-source-options/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/test-run/preparation/data-source-options/__tests__/index.spec.tsxindex a5e23d21a2d..b159455cb68 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/data-source-options/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/data-source-options/__tests__/index.spec.tsx@@ -1,28 +1,21 @@-import type { DataSourceOption } from '../../types'+import type { DataSourceOption } from '../../../types'import type { DataSourceNodeType } from '@/app/components/workflow/nodes/data-source/types'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'-import DataSourceOptions from './index'-import OptionCard from './option-card'+import DataSourceOptions from '../index'+import OptionCard from '../option-card'-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Track mock options for useDatasourceOptions hooklet mockDatasourceOptions: DataSourceOption[] = []-vi.mock('../hooks', () => ({+vi.mock('../../hooks', () => ({useDatasourceOptions: () => mockDatasourceOptions,}))-// Mock useToolIcon hookconst mockToolIcon = { type: 'icon', icon: 'test-icon' }vi.mock('@/app/components/workflow/hooks', () => ({useToolIcon: () => mockToolIcon,}))-// Mock BlockIcon componentvi.mock('@/app/components/workflow/block-icon', () => ({default: ({ type, toolIcon }: { type: string, toolIcon: unknown }) => (<div data-testid="block-icon" data-type={type} data-tool-icon={JSON.stringify(toolIcon)}>@@ -31,10 +24,6 @@ vi.mock('@/app/components/workflow/block-icon', () => ({),}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createNodeData = (overrides?: Partial<DataSourceNodeType>): DataSourceNodeType => ({title: 'Test Node',desc: 'Test description',@@ -55,24 +44,15 @@ const createDataSourceOption = (overrides?: Partial<DataSourceOption>): DataSour...overrides,})-// ============================================================================-// OptionCard Component Tests-// ============================================================================-describe('OptionCard', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render option card without crashing', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel="Test Label"@@ -82,15 +62,12 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByText('Test Label')).toBeInTheDocument()})it('should render label text', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel="My Data Source"@@ -100,15 +77,12 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByText('My Data Source')).toBeInTheDocument()})it('should render BlockIcon component', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel="Test"@@ -118,15 +92,12 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByTestId('block-icon')).toBeInTheDocument()})it('should pass correct type to BlockIcon', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel="Test"@@ -136,17 +107,13 @@ describe('OptionCard', () => {/>,)- // Assertconst blockIcon = screen.getByTestId('block-icon')- // BlockEnum.DataSource value is 'datasource'expect(blockIcon).toHaveAttribute('data-type', 'datasource')})it('should set title attribute on label element', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel="Long Label Text"@@ -156,20 +123,14 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByTitle('Long Label Text')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should apply selected styles when selected is true', () => {- // Arrangeconst nodeData = createNodeData()- // Actconst { container } = render(<OptionCardlabel="Test"@@ -179,17 +140,14 @@ describe('OptionCard', () => {/>,)- // Assertconst card = container.firstChild as HTMLElementexpect(card.className).toContain('border-components-option-card-option-selected-border')expect(card.className).toContain('bg-components-option-card-option-selected-bg')})it('should apply unselected styles when selected is false', () => {- // Arrangeconst nodeData = createNodeData()- // Actconst { container } = render(<OptionCardlabel="Test"@@ -199,16 +157,13 @@ describe('OptionCard', () => {/>,)- // Assertconst card = container.firstChild as HTMLElementexpect(card.className).not.toContain('border-components-option-card-option-selected-border')})it('should apply text-text-primary to label when selected', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel="Test Label"@@ -218,16 +173,13 @@ describe('OptionCard', () => {/>,)- // Assertconst label = screen.getByText('Test Label')expect(label.className).toContain('text-text-primary')})it('should apply text-text-secondary to label when not selected', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel="Test Label"@@ -237,16 +189,13 @@ describe('OptionCard', () => {/>,)- // Assertconst label = screen.getByText('Test Label')expect(label.className).toContain('text-text-secondary')})it('should handle undefined onClick prop', () => {- // Arrangeconst nodeData = createNodeData()- // Actconst { container } = render(<OptionCardlabel="Test"@@ -257,19 +206,16 @@ describe('OptionCard', () => {/>,)- // Assert - should not throw when clickingconst card = container.firstChild as HTMLElementexpect(() => fireEvent.click(card)).not.toThrow()})it('should handle different node data types', () => {- // Arrangeconst nodeData = createNodeData({title: 'Website Crawler',provider_type: 'website_crawl',})- // Actrender(<OptionCardlabel="Website Crawler"@@ -279,21 +225,15 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByText('Website Crawler')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onClick with value when card is clicked', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()- // Actconst { container } = render(<OptionCardlabel="Test"@@ -305,17 +245,14 @@ describe('OptionCard', () => {)fireEvent.click(container.firstChild as HTMLElement)- // Assertexpect(onClick).toHaveBeenCalledTimes(1)expect(onClick).toHaveBeenCalledWith('test-value')})it('should call onClick with correct value for different cards', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()- // Actconst { container: container1 } = render(<OptionCardlabel="Card 1"@@ -338,18 +275,15 @@ describe('OptionCard', () => {)fireEvent.click(container2.firstChild as HTMLElement)- // Assertexpect(onClick).toHaveBeenCalledTimes(2)expect(onClick).toHaveBeenNthCalledWith(1, 'value-1')expect(onClick).toHaveBeenNthCalledWith(2, 'value-2')})it('should handle rapid clicks', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()- // Actconst { container } = render(<OptionCardlabel="Test"@@ -364,16 +298,13 @@ describe('OptionCard', () => {fireEvent.click(card)fireEvent.click(card)- // Assertexpect(onClick).toHaveBeenCalledTimes(3)})it('should call onClick with empty string value', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()- // Actconst { container } = render(<OptionCardlabel="Test"@@ -385,21 +316,15 @@ describe('OptionCard', () => {)fireEvent.click(container.firstChild as HTMLElement)- // Assertexpect(onClick).toHaveBeenCalledWith('')})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain stable handleClickCard callback when props dont change', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()- // Actconst { rerender, container } = render(<OptionCardlabel="Test"@@ -422,18 +347,15 @@ describe('OptionCard', () => {)fireEvent.click(container.firstChild as HTMLElement)- // Assertexpect(onClick).toHaveBeenCalledTimes(2)expect(onClick).toHaveBeenNthCalledWith(1, 'test-value')expect(onClick).toHaveBeenNthCalledWith(2, 'test-value')})it('should update handleClickCard when value changes', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()- // Actconst { rerender, container } = render(<OptionCardlabel="Test"@@ -456,18 +378,15 @@ describe('OptionCard', () => {)fireEvent.click(container.firstChild as HTMLElement)- // Assertexpect(onClick).toHaveBeenNthCalledWith(1, 'old-value')expect(onClick).toHaveBeenNthCalledWith(2, 'new-value')})it('should update handleClickCard when onClick changes', () => {- // Arrangeconst onClick1 = vi.fn()const onClick2 = vi.fn()const nodeData = createNodeData()- // Actconst { rerender, container } = render(<OptionCardlabel="Test"@@ -490,22 +409,16 @@ describe('OptionCard', () => {)fireEvent.click(container.firstChild as HTMLElement)- // Assertexpect(onClick1).toHaveBeenCalledTimes(1)expect(onClick2).toHaveBeenCalledTimes(1)})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be memoized (React.memo)', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()- // Actconst { rerender } = render(<OptionCardlabel="Test"@@ -516,7 +429,6 @@ describe('OptionCard', () => {/>,)- // Rerender with same propsrerender(<OptionCardlabel="Test"@@ -527,15 +439,12 @@ describe('OptionCard', () => {/>,)- // Assert - Component should render without issuesexpect(screen.getByText('Test')).toBeInTheDocument()})it('should re-render when selected prop changes', () => {- // Arrangeconst nodeData = createNodeData()- // Actconst { rerender, container } = render(<OptionCardlabel="Test"@@ -557,21 +466,15 @@ describe('OptionCard', () => {/>,)- // Assert - Component should update stylescard = container.firstChild as HTMLElementexpect(card.className).toContain('border-components-option-card-option-selected-border')})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle empty label', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel=""@@ -581,16 +484,13 @@ describe('OptionCard', () => {/>,)- // Assert - Should render without crashingexpect(screen.getByTestId('block-icon')).toBeInTheDocument()})it('should handle very long label', () => {- // Arrangeconst nodeData = createNodeData()const longLabel = 'A'.repeat(200)- // Actrender(<OptionCardlabel={longLabel}@@ -600,17 +500,14 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByText(longLabel)).toBeInTheDocument()expect(screen.getByTitle(longLabel)).toBeInTheDocument()})it('should handle special characters in label', () => {- // Arrangeconst nodeData = createNodeData()const specialLabel = '<Test> & \'Label\' "Special"'- // Actrender(<OptionCardlabel={specialLabel}@@ -620,15 +517,12 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByText(specialLabel)).toBeInTheDocument()})it('should handle unicode characters in label', () => {- // Arrangeconst nodeData = createNodeData()- // Actrender(<OptionCardlabel="数据源 🎉 データソース"@@ -638,16 +532,13 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByText('数据源 🎉 データソース')).toBeInTheDocument()})it('should handle empty value', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()- // Actconst { container } = render(<OptionCardlabel="Test"@@ -659,17 +550,14 @@ describe('OptionCard', () => {)fireEvent.click(container.firstChild as HTMLElement)- // Assertexpect(onClick).toHaveBeenCalledWith('')})it('should handle special characters in value', () => {- // Arrangeconst onClick = vi.fn()const nodeData = createNodeData()const specialValue = 'test-value_123/abc:xyz'- // Actconst { container } = render(<OptionCardlabel="Test"@@ -681,15 +569,12 @@ describe('OptionCard', () => {)fireEvent.click(container.firstChild as HTMLElement)- // Assertexpect(onClick).toHaveBeenCalledWith(specialValue)})it('should handle nodeData with minimal properties', () => {- // Arrangeconst minimalNodeData = { title: 'Minimal' } as unknown as DataSourceNodeType- // Actrender(<OptionCardlabel="Minimal"@@ -699,20 +584,14 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByText('Minimal')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Accessibility Tests- // -------------------------------------------------------------------------describe('Accessibility', () => {it('should have cursor-pointer class for clickability indication', () => {- // Arrangeconst nodeData = createNodeData()- // Actconst { container } = render(<OptionCardlabel="Test"@@ -722,17 +601,14 @@ describe('OptionCard', () => {/>,)- // Assertconst card = container.firstChild as HTMLElementexpect(card.className).toContain('cursor-pointer')})it('should provide title attribute for label tooltip', () => {- // Arrangeconst nodeData = createNodeData()const label = 'This is a very long label that might get truncated'- // Actrender(<OptionCardlabel={label}@@ -742,31 +618,21 @@ describe('OptionCard', () => {/>,)- // Assertexpect(screen.getByTitle(label)).toBeInTheDocument()})})})-// ============================================================================-// DataSourceOptions Component Tests-// ============================================================================-describe('DataSourceOptions', () => {beforeEach(() => {vi.clearAllMocks()mockDatasourceOptions = []})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render container without crashing', () => {- // ArrangemockDatasourceOptions = []- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId=""@@ -774,19 +640,16 @@ describe('DataSourceOptions', () => {/>,)- // Assertexpect(container.querySelector('.grid')).toBeInTheDocument()})it('should render OptionCard for each option', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption({ label: 'Option 1', value: 'opt-1' }),createDataSourceOption({ label: 'Option 2', value: 'opt-2' }),createDataSourceOption({ label: 'Option 3', value: 'opt-3' }),]- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -794,17 +657,14 @@ describe('DataSourceOptions', () => {/>,)- // Assertexpect(screen.getByText('Option 1')).toBeInTheDocument()expect(screen.getByText('Option 2')).toBeInTheDocument()expect(screen.getByText('Option 3')).toBeInTheDocument()})it('should render empty grid when no options', () => {- // ArrangemockDatasourceOptions = []- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId=""@@ -812,17 +672,14 @@ describe('DataSourceOptions', () => {/>,)- // Assertconst grid = container.querySelector('.grid')expect(grid).toBeInTheDocument()expect(grid?.children.length).toBe(0)})it('should apply correct grid layout classes', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption()]- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId=""@@ -830,7 +687,6 @@ describe('DataSourceOptions', () => {/>,)- // Assertconst grid = container.querySelector('.grid')expect(grid?.className).toContain('grid-cols-4')expect(grid?.className).toContain('gap-1')@@ -838,13 +694,11 @@ describe('DataSourceOptions', () => {})it('should render correct number of option cards', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption({ label: 'A', value: 'a' }),createDataSourceOption({ label: 'B', value: 'b' }),]- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId="a"@@ -852,24 +706,18 @@ describe('DataSourceOptions', () => {/>,)- // Assertconst cards = container.querySelectorAll('.flex.cursor-pointer')expect(cards.length).toBe(2)})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should mark correct option as selected based on dataSourceNodeId', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption({ label: 'Option 1', value: 'opt-1' }),createDataSourceOption({ label: 'Option 2', value: 'opt-2' }),]- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId="opt-1"@@ -877,20 +725,17 @@ describe('DataSourceOptions', () => {/>,)- // Assert - First option should have selected stylesconst cards = container.querySelectorAll('.flex.cursor-pointer')expect(cards[0].className).toContain('border-components-option-card-option-selected-border')expect(cards[1].className).not.toContain('border-components-option-card-option-selected-border')})it('should mark second option as selected when matching', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption({ label: 'Option 1', value: 'opt-1' }),createDataSourceOption({ label: 'Option 2', value: 'opt-2' }),]- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId="opt-2"@@ -898,20 +743,17 @@ describe('DataSourceOptions', () => {/>,)- // Assertconst cards = container.querySelectorAll('.flex.cursor-pointer')expect(cards[0].className).not.toContain('border-components-option-card-option-selected-border')expect(cards[1].className).toContain('border-components-option-card-option-selected-border')})it('should mark none as selected when dataSourceNodeId does not match', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption({ label: 'Option 1', value: 'opt-1' }),createDataSourceOption({ label: 'Option 2', value: 'opt-2' }),]- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId="non-existent"@@ -919,7 +761,6 @@ describe('DataSourceOptions', () => {/>,)- // Assert - No option should have selected stylesconst cards = container.querySelectorAll('.flex.cursor-pointer')cards.forEach((card) => {expect(card.className).not.toContain('border-components-option-card-option-selected-border')@@ -927,10 +768,8 @@ describe('DataSourceOptions', () => {})it('should handle empty dataSourceNodeId', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption()]- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId=""@@ -938,17 +777,12 @@ describe('DataSourceOptions', () => {/>,)- // Assertexpect(container.querySelector('.grid')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onSelect with datasource when option is clicked', () => {- // Arrangeconst onSelect = vi.fn()const optionData = createNodeData({ title: 'Test Source' })mockDatasourceOptions = [@@ -959,7 +793,6 @@ describe('DataSourceOptions', () => {}),]- // Act - Use a dataSourceNodeId to prevent auto-select on mountrender(<DataSourceOptionsdataSourceNodeId="test-id"@@ -968,7 +801,6 @@ describe('DataSourceOptions', () => {)fireEvent.click(screen.getByText('Test Option'))- // Assertexpect(onSelect).toHaveBeenCalledTimes(1)expect(onSelect).toHaveBeenCalledWith({nodeId: 'test-id',@@ -977,7 +809,6 @@ describe('DataSourceOptions', () => {})it('should call onSelect with correct option when different options are clicked', () => {- // Arrangeconst onSelect = vi.fn()const data1 = createNodeData({ title: 'Source 1' })const data2 = createNodeData({ title: 'Source 2' })@@ -986,7 +817,6 @@ describe('DataSourceOptions', () => {createDataSourceOption({ label: 'Option 2', value: 'id-2', data: data2 }),]- // Act - Use a dataSourceNodeId to prevent auto-select on mountrender(<DataSourceOptionsdataSourceNodeId="id-1"@@ -996,18 +826,15 @@ describe('DataSourceOptions', () => {fireEvent.click(screen.getByText('Option 1'))fireEvent.click(screen.getByText('Option 2'))- // Assertexpect(onSelect).toHaveBeenCalledTimes(2)expect(onSelect).toHaveBeenNthCalledWith(1, { nodeId: 'id-1', nodeData: data1 })expect(onSelect).toHaveBeenNthCalledWith(2, { nodeId: 'id-2', nodeData: data2 })})it('should not call onSelect when option value not found', () => {- // Arrange - This tests the early return in handleSelectconst onSelect = vi.fn()mockDatasourceOptions = []- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -1015,19 +842,16 @@ describe('DataSourceOptions', () => {/>,)- // Assert - Since there are no options, onSelect should not be calledexpect(onSelect).not.toHaveBeenCalled()})it('should handle clicking same option multiple times', () => {- // Arrangeconst onSelect = vi.fn()const optionData = createNodeData()mockDatasourceOptions = [createDataSourceOption({ label: 'Option', value: 'opt-id', data: optionData }),]- // Actrender(<DataSourceOptionsdataSourceNodeId="opt-id"@@ -1038,17 +862,12 @@ describe('DataSourceOptions', () => {fireEvent.click(screen.getByText('Option'))fireEvent.click(screen.getByText('Option'))- // Assertexpect(onSelect).toHaveBeenCalledTimes(3)})})- // -------------------------------------------------------------------------- // Side Effects and Cleanup Tests- // -------------------------------------------------------------------------describe('Side Effects and Cleanup', () => {it('should auto-select first option on mount when dataSourceNodeId is empty', async () => {- // Arrangeconst onSelect = vi.fn()const firstOptionData = createNodeData({ title: 'First' })mockDatasourceOptions = [@@ -1056,7 +875,6 @@ describe('DataSourceOptions', () => {createDataSourceOption({ label: 'Second', value: 'second-id' }),]- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -1064,7 +882,6 @@ describe('DataSourceOptions', () => {/>,)- // Assert - First option should be auto-selected on mountawait waitFor(() => {expect(onSelect).toHaveBeenCalledWith({nodeId: 'first-id',@@ -1074,14 +891,12 @@ describe('DataSourceOptions', () => {})it('should not auto-select when dataSourceNodeId is provided', async () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'First', value: 'first-id' }),createDataSourceOption({ label: 'Second', value: 'second-id' }),]- // Actrender(<DataSourceOptionsdataSourceNodeId="second-id"@@ -1089,18 +904,15 @@ describe('DataSourceOptions', () => {/>,)- // Assert - onSelect should not be called since dataSourceNodeId is already setawait waitFor(() => {expect(onSelect).not.toHaveBeenCalled()})})it('should not auto-select when options array is empty', async () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = []- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -1108,20 +920,17 @@ describe('DataSourceOptions', () => {/>,)- // Assertawait waitFor(() => {expect(onSelect).not.toHaveBeenCalled()})})it('should run effect only once on mount', async () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'First', value: 'first-id' }),]- // Actconst { rerender } = render(<DataSourceOptionsdataSourceNodeId=""@@ -1129,7 +938,6 @@ describe('DataSourceOptions', () => {/>,)- // Rerender multiple timesrerender(<DataSourceOptionsdataSourceNodeId=""@@ -1143,21 +951,18 @@ describe('DataSourceOptions', () => {/>,)- // Assert - Effect should only run once (on mount)await waitFor(() => {expect(onSelect).toHaveBeenCalledTimes(1)})})it('should not re-run effect on rerender with different props', async () => {- // Arrangeconst onSelect1 = vi.fn()const onSelect2 = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'First', value: 'first-id' }),]- // Actconst { rerender } = render(<DataSourceOptionsdataSourceNodeId=""@@ -1176,18 +981,15 @@ describe('DataSourceOptions', () => {/>,)- // Assert - onSelect2 should not be called from effectexpect(onSelect2).not.toHaveBeenCalled()})it('should handle unmount cleanly', () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'Test', value: 'test-id' }),]- // Actconst { unmount } = render(<DataSourceOptionsdataSourceNodeId="test-id"@@ -1195,24 +997,18 @@ describe('DataSourceOptions', () => {/>,)- // Assert - Should unmount without errorsexpect(() => unmount()).not.toThrow()})})- // -------------------------------------------------------------------------- // Callback Stability Tests- // -------------------------------------------------------------------------describe('Callback Stability', () => {it('should maintain stable handleSelect callback', () => {- // Arrangeconst onSelect = vi.fn()const optionData = createNodeData()mockDatasourceOptions = [createDataSourceOption({ label: 'Option', value: 'opt-id', data: optionData }),]- // Actconst { rerender } = render(<DataSourceOptionsdataSourceNodeId=""@@ -1229,19 +1025,16 @@ describe('DataSourceOptions', () => {)fireEvent.click(screen.getByText('Option'))- // Assertexpect(onSelect).toHaveBeenCalledTimes(3) // 1 auto-select + 2 clicks})it('should update handleSelect when onSelect prop changes', () => {- // Arrangeconst onSelect1 = vi.fn()const onSelect2 = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'Option', value: 'opt-id' }),]- // Actconst { rerender } = render(<DataSourceOptionsdataSourceNodeId="opt-id"@@ -1258,13 +1051,11 @@ describe('DataSourceOptions', () => {)fireEvent.click(screen.getByText('Option'))- // Assertexpect(onSelect1).toHaveBeenCalledTimes(1)expect(onSelect2).toHaveBeenCalledTimes(1)})it('should update handleSelect when options change', () => {- // Arrangeconst onSelect = vi.fn()const data1 = createNodeData({ title: 'Data 1' })const data2 = createNodeData({ title: 'Data 2' })@@ -1272,7 +1063,6 @@ describe('DataSourceOptions', () => {createDataSourceOption({ label: 'Option', value: 'opt-id', data: data1 }),]- // Actconst { rerender } = render(<DataSourceOptionsdataSourceNodeId="opt-id"@@ -1281,7 +1071,6 @@ describe('DataSourceOptions', () => {)fireEvent.click(screen.getByText('Option'))- // Update options with different datamockDatasourceOptions = [createDataSourceOption({ label: 'Option', value: 'opt-id', data: data2 }),]@@ -1293,24 +1082,18 @@ describe('DataSourceOptions', () => {)fireEvent.click(screen.getByText('Option'))- // Assertexpect(onSelect).toHaveBeenNthCalledWith(1, { nodeId: 'opt-id', nodeData: data1 })expect(onSelect).toHaveBeenNthCalledWith(2, { nodeId: 'opt-id', nodeData: data2 })})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle single option', () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'Only Option', value: 'only-id' }),]- // Actrender(<DataSourceOptionsdataSourceNodeId="only-id"@@ -1318,16 +1101,13 @@ describe('DataSourceOptions', () => {/>,)- // Assertexpect(screen.getByText('Only Option')).toBeInTheDocument()})it('should handle many options', () => {- // ArrangemockDatasourceOptions = Array.from({ length: 20 }, (_, i) =>createDataSourceOption({ label: `Option ${i}`, value: `opt-${i}` }))- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -1335,13 +1115,11 @@ describe('DataSourceOptions', () => {/>,)- // Assertexpect(screen.getByText('Option 0')).toBeInTheDocument()expect(screen.getByText('Option 19')).toBeInTheDocument()})it('should handle options with duplicate labels but different values', () => {- // Arrangeconst onSelect = vi.fn()const data1 = createNodeData({ title: 'Source 1' })const data2 = createNodeData({ title: 'Source 2' })@@ -1350,7 +1128,6 @@ describe('DataSourceOptions', () => {createDataSourceOption({ label: 'Same Label', value: 'id-2', data: data2 }),]- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -1360,12 +1137,10 @@ describe('DataSourceOptions', () => {const labels = screen.getAllByText('Same Label')fireEvent.click(labels[1]) // Click second one- // Assertexpect(onSelect).toHaveBeenLastCalledWith({ nodeId: 'id-2', nodeData: data2 })})it('should handle special characters in option values', () => {- // Arrangeconst onSelect = vi.fn()const specialData = createNodeData()mockDatasourceOptions = [@@ -1376,7 +1151,6 @@ describe('DataSourceOptions', () => {}),]- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -1385,7 +1159,6 @@ describe('DataSourceOptions', () => {)fireEvent.click(screen.getByText('Special'))- // Assertexpect(onSelect).toHaveBeenCalledWith({nodeId: 'special-chars_123-abc',nodeData: specialData,@@ -1393,13 +1166,9 @@ describe('DataSourceOptions', () => {})it('should handle click on non-existent option value gracefully', () => {- // Arrange - Test the early return in handleSelect when selectedOption is not found- // This is a bit tricky to test directly since options are rendered from the same array- // We'll test by verifying the component doesn't crash with empty optionsconst onSelect = vi.fn()mockDatasourceOptions = []- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId=""@@ -1407,19 +1176,16 @@ describe('DataSourceOptions', () => {/>,)- // Assert - No options to click, but component should renderexpect(container.querySelector('.grid')).toBeInTheDocument()})it('should handle options with empty string values', () => {- // Arrangeconst onSelect = vi.fn()const emptyValueData = createNodeData()mockDatasourceOptions = [createDataSourceOption({ label: 'Empty Value', value: '', data: emptyValueData }),]- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -1428,7 +1194,6 @@ describe('DataSourceOptions', () => {)fireEvent.click(screen.getByText('Empty Value'))- // Assert - Should call onSelect with empty string nodeIdexpect(onSelect).toHaveBeenCalledWith({nodeId: '',nodeData: emptyValueData,@@ -1436,12 +1201,10 @@ describe('DataSourceOptions', () => {})it('should handle options with whitespace-only labels', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption({ label: ' ', value: 'whitespace' }),]- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId="whitespace"@@ -1449,25 +1212,19 @@ describe('DataSourceOptions', () => {/>,)- // Assertconst cards = container.querySelectorAll('.flex.cursor-pointer')expect(cards.length).toBe(1)})})- // -------------------------------------------------------------------------- // Error Handling Tests- // -------------------------------------------------------------------------describe('Error Handling', () => {it('should not crash when nodeData has unexpected shape', () => {- // Arrangeconst onSelect = vi.fn()const weirdNodeData = { unexpected: 'data' } as unknown as DataSourceNodeTypemockDatasourceOptions = [createDataSourceOption({ label: 'Weird', value: 'weird-id', data: weirdNodeData }),]- // Actrender(<DataSourceOptionsdataSourceNodeId="weird-id"@@ -1476,7 +1233,6 @@ describe('DataSourceOptions', () => {)fireEvent.click(screen.getByText('Weird'))- // Assertexpect(onSelect).toHaveBeenCalledWith({nodeId: 'weird-id',nodeData: weirdNodeData,@@ -1485,22 +1241,14 @@ describe('DataSourceOptions', () => {})})-// ============================================================================-// Integration Tests-// ============================================================================-describe('DataSourceOptions Integration', () => {beforeEach(() => {vi.clearAllMocks()mockDatasourceOptions = []})- // -------------------------------------------------------------------------- // Full Flow Tests- // -------------------------------------------------------------------------describe('Full Flow', () => {it('should complete full selection flow: render -> auto-select -> manual select', async () => {- // Arrangeconst onSelect = vi.fn()const data1 = createNodeData({ title: 'Source 1' })const data2 = createNodeData({ title: 'Source 2' })@@ -1509,7 +1257,6 @@ describe('DataSourceOptions Integration', () => {createDataSourceOption({ label: 'Option 2', value: 'id-2', data: data2 }),]- // Actrender(<DataSourceOptionsdataSourceNodeId=""@@ -1517,20 +1264,16 @@ describe('DataSourceOptions Integration', () => {/>,)- // Assert - Auto-select first option on mountawait waitFor(() => {expect(onSelect).toHaveBeenCalledWith({ nodeId: 'id-1', nodeData: data1 })})- // Act - Manual select second optionfireEvent.click(screen.getByText('Option 2'))- // Assertexpect(onSelect).toHaveBeenLastCalledWith({ nodeId: 'id-2', nodeData: data2 })})it('should update selection state when clicking different options', () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'Option A', value: 'a' }),@@ -1538,7 +1281,6 @@ describe('DataSourceOptions Integration', () => {createDataSourceOption({ label: 'Option C', value: 'c' }),]- // Act - Start with Option B selectedconst { rerender, container } = render(<DataSourceOptionsdataSourceNodeId="b"@@ -1546,11 +1288,9 @@ describe('DataSourceOptions Integration', () => {/>,)- // Assert - Option B should be selectedlet cards = container.querySelectorAll('.flex.cursor-pointer')expect(cards[1].className).toContain('border-components-option-card-option-selected-border')- // Act - Simulate selection change to Option Crerender(<DataSourceOptionsdataSourceNodeId="c"@@ -1558,14 +1298,12 @@ describe('DataSourceOptions Integration', () => {/>,)- // Assert - Option C should now be selectedcards = container.querySelectorAll('.flex.cursor-pointer')expect(cards[2].className).toContain('border-components-option-card-option-selected-border')expect(cards[1].className).not.toContain('border-components-option-card-option-selected-border')})it('should handle rapid option switching', async () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'A', value: 'a' }),@@ -1573,7 +1311,6 @@ describe('DataSourceOptions Integration', () => {createDataSourceOption({ label: 'C', value: 'c' }),]- // Actrender(<DataSourceOptionsdataSourceNodeId="a"@@ -1586,17 +1323,12 @@ describe('DataSourceOptions Integration', () => {fireEvent.click(screen.getByText('A'))fireEvent.click(screen.getByText('B'))- // Assertexpect(onSelect).toHaveBeenCalledTimes(4)})})- // -------------------------------------------------------------------------- // Component Communication Tests- // -------------------------------------------------------------------------describe('Component Communication', () => {it('should pass correct props from DataSourceOptions to OptionCard', () => {- // ArrangemockDatasourceOptions = [createDataSourceOption({label: 'Test Label',@@ -1605,7 +1337,6 @@ describe('DataSourceOptions Integration', () => {}),]- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId="test-value"@@ -1613,7 +1344,6 @@ describe('DataSourceOptions Integration', () => {/>,)- // Assert - Verify OptionCard receives correct props through rendered outputexpect(screen.getByText('Test Label')).toBeInTheDocument()expect(screen.getByTestId('block-icon')).toBeInTheDocument()const card = container.querySelector('.flex.cursor-pointer')@@ -1621,14 +1351,12 @@ describe('DataSourceOptions Integration', () => {})it('should propagate click events from OptionCard to DataSourceOptions', () => {- // Arrangeconst onSelect = vi.fn()const nodeData = createNodeData()mockDatasourceOptions = [createDataSourceOption({ label: 'Click Me', value: 'click-id', data: nodeData }),]- // Actrender(<DataSourceOptionsdataSourceNodeId="click-id"@@ -1637,7 +1365,6 @@ describe('DataSourceOptions Integration', () => {)fireEvent.click(screen.getByText('Click Me'))- // Assertexpect(onSelect).toHaveBeenCalledWith({nodeId: 'click-id',nodeData,@@ -1645,19 +1372,14 @@ describe('DataSourceOptions Integration', () => {})})- // -------------------------------------------------------------------------- // State Consistency Tests- // -------------------------------------------------------------------------describe('State Consistency', () => {it('should maintain consistent selection across multiple renders', () => {- // Arrangeconst onSelect = vi.fn()mockDatasourceOptions = [createDataSourceOption({ label: 'A', value: 'a' }),createDataSourceOption({ label: 'B', value: 'b' }),]- // Actconst { rerender, container } = render(<DataSourceOptionsdataSourceNodeId="a"@@ -1665,7 +1387,6 @@ describe('DataSourceOptions Integration', () => {/>,)- // Multiple rerendersfor (let i = 0; i < 5; i++) {rerender(<DataSourceOptions@@ -1675,14 +1396,12 @@ describe('DataSourceOptions Integration', () => {)}- // Assert - Selection should remain consistentconst cards = container.querySelectorAll('.flex.cursor-pointer')expect(cards[0].className).toContain('border-components-option-card-option-selected-border')expect(cards[1].className).not.toContain('border-components-option-card-option-selected-border')})it('should handle options array reference change with same content', () => {- // Arrangeconst onSelect = vi.fn()const nodeData = createNodeData()@@ -1690,7 +1409,6 @@ describe('DataSourceOptions Integration', () => {createDataSourceOption({ label: 'Option', value: 'opt', data: nodeData }),]- // Actconst { rerender } = render(<DataSourceOptionsdataSourceNodeId="opt"@@ -1698,7 +1416,6 @@ describe('DataSourceOptions Integration', () => {/>,)- // Create new array reference with same contentmockDatasourceOptions = [createDataSourceOption({ label: 'Option', value: 'opt', data: nodeData }),]@@ -1712,7 +1429,6 @@ describe('DataSourceOptions Integration', () => {fireEvent.click(screen.getByText('Option'))- // Assert - Should still work correctlyexpect(onSelect).toHaveBeenCalledWith({nodeId: 'opt',nodeData,@@ -1721,10 +1437,6 @@ describe('DataSourceOptions Integration', () => {})})-// ============================================================================-// handleSelect Early Return Branch Coverage-// ============================================================================-describe('handleSelect Early Return Coverage', () => {beforeEach(() => {vi.clearAllMocks()@@ -1732,9 +1444,6 @@ describe('handleSelect Early Return Coverage', () => {})it('should test early return when option not found by using modified mock during click', () => {- // Arrange - Test strategy: We need to trigger the early return when- // selectedOption is not found. Since the component renders cards from- // the options array, we need to modify the mock between render and click.const onSelect = vi.fn()const originalOptions = [createDataSourceOption({ label: 'Option A', value: 'a' }),@@ -1742,7 +1451,6 @@ describe('handleSelect Early Return Coverage', () => {]mockDatasourceOptions = originalOptions- // Act - Render the componentconst { rerender } = render(<DataSourceOptionsdataSourceNodeId="a"@@ -1750,12 +1458,6 @@ describe('handleSelect Early Return Coverage', () => {/>,)- // Now we need to cause the handleSelect to not find the option.- // The callback is memoized with [onSelect, options], so if we change- // the options, the callback should be updated too.-- // Let's create a scenario where the value doesn't match any option- // by rendering with options that have different valuesconst newOptions = [createDataSourceOption({ label: 'Option A', value: 'x' }), // Changed from 'a' to 'x'createDataSourceOption({ label: 'Option B', value: 'y' }), // Changed from 'b' to 'y'@@ -1769,11 +1471,8 @@ describe('handleSelect Early Return Coverage', () => {/>,)- // Click on 'Option A' which now has value 'x', not 'a'- // Since we're selecting by text, this tests that the click worksfireEvent.click(screen.getByText('Option A'))- // Assert - onSelect should be called with the new value 'x'expect(onSelect).toHaveBeenCalledWith({nodeId: 'x',nodeData: expect.any(Object),@@ -1781,11 +1480,9 @@ describe('handleSelect Early Return Coverage', () => {})it('should handle empty options array gracefully', () => {- // Arrange - Edge case: empty optionsconst onSelect = vi.fn()mockDatasourceOptions = []- // Actconst { container } = render(<DataSourceOptionsdataSourceNodeId=""@@ -1793,13 +1490,11 @@ describe('handleSelect Early Return Coverage', () => {/>,)- // Assert - No options to click, onSelect not calledexpect(container.querySelector('.grid')).toBeInTheDocument()expect(onSelect).not.toHaveBeenCalled()})it('should handle auto-select with mismatched first option', async () => {- // Arrange - Test auto-select behaviorconst onSelect = vi.fn()const firstOptionData = createNodeData({ title: 'First' })mockDatasourceOptions = [@@ -1810,7 +1505,6 @@ describe('handleSelect Early Return Coverage', () => {}),]- // Act - Empty dataSourceNodeId triggers auto-selectrender(<DataSourceOptionsdataSourceNodeId=""@@ -1818,7 +1512,6 @@ describe('handleSelect Early Return Coverage', () => {/>,)- // Assert - First option auto-selectedawait waitFor(() => {expect(onSelect).toHaveBeenCalledWith({nodeId: 'first-value',diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsxsimilarity index 85%rename from web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsxindex f69347d038a..341dfe2a517 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsx@@ -8,15 +8,10 @@ import * as React from 'react'import { BaseFieldType } from '@/app/components/base/form/form-scenarios/base/types'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { PipelineInputVarType } from '@/models/pipeline'-import Actions from './actions'-import DocumentProcessing from './index'-import Options from './options'+import Actions from '../actions'+import DocumentProcessing from '../index'+import Options from '../options'-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock workflow storelet mockPipelineId: string | null = 'test-pipeline-id'let mockWorkflowRunningData: { result: { status: string } } | undefined@@ -35,7 +30,6 @@ vi.mock('@/app/components/workflow/store', () => ({},}))-// Mock useDraftPipelineProcessingParamslet mockParamsConfig: PipelineProcessingParamsResponse | undefinedlet mockIsFetchingParams = false@@ -46,7 +40,6 @@ vi.mock('@/service/use-pipeline', () => ({}),}))-// Mock use-input-fields hooksconst mockUseInitialData = vi.fn()const mockUseConfigurations = vi.fn()@@ -55,14 +48,12 @@ vi.mock('@/app/components/rag-pipeline/hooks/use-input-fields', () => ({useConfigurations: (variables: RAGPipelineVariables) => mockUseConfigurations(variables),}))-// Mock generateZodSchemaconst mockGenerateZodSchema = vi.fn()vi.mock('@/app/components/base/form/form-scenarios/base/utils', () => ({generateZodSchema: (configurations: BaseConfiguration[]) => mockGenerateZodSchema(configurations),}))-// Mock Toastconst mockToastNotify = vi.fn()vi.mock('@/app/components/base/toast', () => ({@@ -71,7 +62,6 @@ vi.mock('@/app/components/base/toast', () => ({},}))-// Mock useAppFormconst mockHandleSubmit = vi.fn()const mockFormStore = {isSubmitting: false,@@ -112,7 +102,6 @@ vi.mock('@/app/components/base/form', () => ({},}))-// Mock BaseFieldvi.mock('@/app/components/base/form/form-scenarios/base/field', () => ({default: ({ config }: { initialData: Record<string, unknown>, config: BaseConfiguration }) => {return () => (@@ -125,10 +114,6 @@ vi.mock('@/app/components/base/form/form-scenarios/base/field', () => ({},}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createRAGPipelineVariable = (overrides?: Partial<RAGPipelineVariable>): RAGPipelineVariable => ({belong_to_node_id: 'test-node',type: PipelineInputVarType.textInput,@@ -163,10 +148,6 @@ const createMockSchema = (): ZodSchema => ({safeParse: vi.fn().mockReturnValue({ success: true }),}) as unknown as ZodSchema-// ============================================================================-// Helper Functions-// ============================================================================-const setupMocks = (options?: {pipelineId?: string | nullparamsConfig?: PipelineProcessingParamsResponse@@ -201,10 +182,6 @@ const renderWithQueryClient = (component: React.ReactElement) => {)}-// ============================================================================-// DocumentProcessing Component Tests-// ============================================================================-describe('DocumentProcessing', () => {const defaultProps = {dataSourceNodeId: 'datasource-node-1',@@ -217,101 +194,75 @@ describe('DocumentProcessing', () => {setupMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {- // ArrangesetupMocks({configurations: [createBaseConfiguration()],})- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})it('should render Options component with form elements', () => {- // Arrangeconst configurations = [createBaseConfiguration({ variable: 'field1', label: 'Field 1' }),createBaseConfiguration({ variable: 'field2', label: 'Field 2' }),]setupMocks({ configurations })- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(screen.getByTestId('field-field1')).toBeInTheDocument()expect(screen.getByTestId('field-field2')).toBeInTheDocument()})it('should render no fields when configurations is empty', () => {- // ArrangesetupMocks({ configurations: [] })- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()})it('should call useInitialData with variables from paramsConfig', () => {- // Arrangeconst variables = [createRAGPipelineVariable({ variable: 'var1' })]setupMocks({paramsConfig: { variables },})- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(mockUseInitialData).toHaveBeenCalledWith(variables)})it('should call useConfigurations with variables from paramsConfig', () => {- // Arrangeconst variables = [createRAGPipelineVariable({ variable: 'var1' })]setupMocks({paramsConfig: { variables },})- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(mockUseConfigurations).toHaveBeenCalledWith(variables)})it('should use empty array when paramsConfig.variables is undefined', () => {- // ArrangesetupMocks({ paramsConfig: undefined })- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(mockUseInitialData).toHaveBeenCalledWith([])expect(mockUseConfigurations).toHaveBeenCalledWith([])})})- // -------------------------------------------------------------------------- // Props Testing- // -------------------------------------------------------------------------describe('Props Testing', () => {it('should pass dataSourceNodeId to useInputVariables hook', () => {- // Arrangeconst customNodeId = 'custom-datasource-node'setupMocks()- // ActrenderWithQueryClient(<DocumentProcessing{...defaultProps}@@ -319,16 +270,13 @@ describe('DocumentProcessing', () => {/>,)- // Assert - verify hook is called (mocked, so we check component renders)expect(screen.getByTestId('form-actions')).toBeInTheDocument()})it('should pass onProcess callback to Options component', () => {- // Arrangeconst mockOnProcess = vi.fn()setupMocks({ configurations: [] })- // Actconst { container } = renderWithQueryClient(<DocumentProcessing{...defaultProps}@@ -336,16 +284,13 @@ describe('DocumentProcessing', () => {/>,)- // Assert - form should be renderedexpect(container.querySelector('form')).toBeInTheDocument()})it('should pass onBack callback to Actions component', () => {- // Arrangeconst mockOnBack = vi.fn()setupMocks()- // ActrenderWithQueryClient(<DocumentProcessing{...defaultProps}@@ -353,37 +298,28 @@ describe('DocumentProcessing', () => {/>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Callback Stability and Memoization Tests- // -------------------------------------------------------------------------describe('Callback Stability and Memoization', () => {it('should memoize renderCustomActions callback', () => {- // ArrangesetupMocks()const { rerender } = renderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Act - rerender with same propsrerender(<QueryClientProvider client={createQueryClient()}><DocumentProcessing {...defaultProps} /></QueryClientProvider>,)- // Assert - component should render correctly without issuesexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})it('should update renderCustomActions when isFetchingParams changes', () => {- // ArrangesetupMocks({ isFetchingParams: false })const { rerender } = renderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // ActsetupMocks({ isFetchingParams: true })rerender(<QueryClientProvider client={createQueryClient()}>@@ -391,12 +327,10 @@ describe('DocumentProcessing', () => {</QueryClientProvider>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})it('should update renderCustomActions when onBack changes', () => {- // Arrangeconst onBack1 = vi.fn()const onBack2 = vi.fn()setupMocks()@@ -404,28 +338,21 @@ describe('DocumentProcessing', () => {<DocumentProcessing {...defaultProps} onBack={onBack1} />,)- // Actrerender(<QueryClientProvider client={createQueryClient()}><DocumentProcessing {...defaultProps} onBack={onBack2} /></QueryClientProvider>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // User Interactions Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onBack when back button is clicked', () => {- // Arrangeconst mockOnBack = vi.fn()setupMocks()- // ActrenderWithQueryClient(<DocumentProcessing{...defaultProps}@@ -435,16 +362,13 @@ describe('DocumentProcessing', () => {const backButton = screen.getByText('datasetPipeline.operations.backToDataSource')fireEvent.click(backButton)- // Assertexpect(mockOnBack).toHaveBeenCalledTimes(1)})it('should handle form submission', () => {- // Arrangeconst mockOnProcess = vi.fn()setupMocks()- // ActrenderWithQueryClient(<DocumentProcessing{...defaultProps}@@ -454,33 +378,25 @@ describe('DocumentProcessing', () => {const processButton = screen.getByText('datasetPipeline.operations.process')fireEvent.click(processButton)- // Assertexpect(mockHandleSubmit).toHaveBeenCalled()})})- // -------------------------------------------------------------------------- // Component Memoization Tests- // -------------------------------------------------------------------------describe('Component Memoization', () => {it('should be wrapped with React.memo', () => {- // ArrangesetupMocks()const { rerender } = renderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Act - rerender with same propsrerender(<QueryClientProvider client={createQueryClient()}><DocumentProcessing {...defaultProps} /></QueryClientProvider>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})it('should not break when re-rendering with different props', () => {- // Arrangeconst initialProps = {...defaultProps,dataSourceNodeId: 'node-1',@@ -488,7 +404,6 @@ describe('DocumentProcessing', () => {setupMocks()const { rerender } = renderWithQueryClient(<DocumentProcessing {...initialProps} />)- // Actconst newProps = {...defaultProps,dataSourceNodeId: 'node-2',@@ -499,52 +414,38 @@ describe('DocumentProcessing', () => {</QueryClientProvider>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle undefined paramsConfig', () => {- // ArrangesetupMocks({ paramsConfig: undefined })- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(mockUseInitialData).toHaveBeenCalledWith([])expect(mockUseConfigurations).toHaveBeenCalledWith([])})it('should handle paramsConfig with empty variables', () => {- // ArrangesetupMocks({ paramsConfig: { variables: [] } })- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(mockUseInitialData).toHaveBeenCalledWith([])expect(mockUseConfigurations).toHaveBeenCalledWith([])})it('should handle null pipelineId', () => {- // ArrangesetupMocks({ pipelineId: null })- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})it('should handle large number of variables', () => {- // Arrangeconst variables = Array.from({ length: 50 }, (_, i) =>createRAGPipelineVariable({ variable: `var_${i}` }))const configurations = Array.from({ length: 50 }, (_, i) =>@@ -554,18 +455,14 @@ describe('DocumentProcessing', () => {configurations,})- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertexpect(screen.getAllByTestId(/^field-var_/)).toHaveLength(50)})it('should handle special characters in node id', () => {- // ArrangesetupMocks()- // ActrenderWithQueryClient(<DocumentProcessing{...defaultProps}@@ -573,46 +470,31 @@ describe('DocumentProcessing', () => {/>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Loading State Tests- // -------------------------------------------------------------------------describe('Loading State', () => {it('should pass isFetchingParams to Actions component', () => {- // ArrangesetupMocks({ isFetchingParams: true })- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assert - check that the process button is disabled when fetchingconst processButton = screen.getByText('datasetPipeline.operations.process')expect(processButton.closest('button')).toBeDisabled()})it('should enable process button when not fetching', () => {- // ArrangesetupMocks({ isFetchingParams: false })- // ActrenderWithQueryClient(<DocumentProcessing {...defaultProps} />)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process')expect(processButton.closest('button')).not.toBeDisabled()})})})-// ============================================================================-// Actions Component Tests-// ============================================================================--// Helper to create mock form params for Actions testsconst createMockFormParams = (overrides?: Partial<{handleSubmit: ReturnType<typeof vi.fn>isSubmitting: boolean@@ -631,10 +513,8 @@ describe('Actions', () => {describe('Rendering', () => {it('should render back button', () => {- // Arrangeconst mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -642,15 +522,12 @@ describe('Actions', () => {/>,)- // Assertexpect(screen.getByText('datasetPipeline.operations.backToDataSource')).toBeInTheDocument()})it('should render process button', () => {- // Arrangeconst mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -658,17 +535,14 @@ describe('Actions', () => {/>,)- // Assertexpect(screen.getByText('datasetPipeline.operations.process')).toBeInTheDocument()})})describe('Button States', () => {it('should disable process button when runDisabled is true', () => {- // Arrangeconst mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -677,16 +551,13 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})it('should disable process button when isSubmitting is true', () => {- // Arrangeconst mockFormParams = createMockFormParams({ isSubmitting: true })- // Actrender(<ActionsformParams={mockFormParams}@@ -694,16 +565,13 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})it('should disable process button when canSubmit is false', () => {- // Arrangeconst mockFormParams = createMockFormParams({ canSubmit: false })- // Actrender(<ActionsformParams={mockFormParams}@@ -711,19 +579,16 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})it('should disable process button when workflow is running', () => {- // ArrangemockWorkflowRunningData = {result: { status: WorkflowRunningStatus.Running },}const mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -731,19 +596,16 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})it('should enable process button when all conditions are met', () => {- // ArrangemockWorkflowRunningData = {result: { status: WorkflowRunningStatus.Succeeded },}const mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -752,7 +614,6 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).not.toBeDisabled()})@@ -760,11 +621,9 @@ describe('Actions', () => {describe('User Interactions', () => {it('should call onBack when back button is clicked', () => {- // Arrangeconst mockOnBack = vi.fn()const mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -774,16 +633,13 @@ describe('Actions', () => {fireEvent.click(screen.getByText('datasetPipeline.operations.backToDataSource'))- // Assertexpect(mockOnBack).toHaveBeenCalledTimes(1)})it('should call form.handleSubmit when process button is clicked', () => {- // Arrangeconst mockSubmit = vi.fn()const mockFormParams = createMockFormParams({ handleSubmit: mockSubmit })- // Actrender(<ActionsformParams={mockFormParams}@@ -793,17 +649,14 @@ describe('Actions', () => {fireEvent.click(screen.getByText('datasetPipeline.operations.process'))- // Assertexpect(mockSubmit).toHaveBeenCalledTimes(1)})})describe('Loading State', () => {it('should show loading state when isSubmitting', () => {- // Arrangeconst mockFormParams = createMockFormParams({ isSubmitting: true })- // Actrender(<ActionsformParams={mockFormParams}@@ -811,19 +664,16 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})it('should show loading state when workflow is running', () => {- // ArrangemockWorkflowRunningData = {result: { status: WorkflowRunningStatus.Running },}const mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -831,7 +681,6 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})@@ -839,10 +688,8 @@ describe('Actions', () => {describe('Edge Cases', () => {it('should handle undefined runDisabled prop', () => {- // Arrangeconst mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -850,17 +697,14 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).not.toBeDisabled()})it('should handle undefined workflowRunningData', () => {- // ArrangemockWorkflowRunningData = undefinedconst mockFormParams = createMockFormParams()- // Actrender(<ActionsformParams={mockFormParams}@@ -868,7 +712,6 @@ describe('Actions', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).not.toBeDisabled()})@@ -876,7 +719,6 @@ describe('Actions', () => {describe('Component Memoization', () => {it('should be wrapped with React.memo', () => {- // Arrangeconst mockFormParams = createMockFormParams()const mockOnBack = vi.fn()const { rerender } = render(@@ -886,7 +728,6 @@ describe('Actions', () => {/>,)- // Act - rerender with same propsrerender(<ActionsformParams={mockFormParams}@@ -894,16 +735,11 @@ describe('Actions', () => {/>,)- // Assertexpect(screen.getByText('datasetPipeline.operations.backToDataSource')).toBeInTheDocument()})})})-// ============================================================================-// Options Component Tests-// ============================================================================-describe('Options', () => {beforeEach(() => {vi.clearAllMocks()@@ -912,7 +748,6 @@ describe('Options', () => {describe('Rendering', () => {it('should render form element', () => {- // Arrangeconst props = {initialData: {},configurations: [],@@ -921,15 +756,12 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actconst { container } = render(<Options {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})it('should render fields based on configurations', () => {- // Arrangeconst configurations = [createBaseConfiguration({ variable: 'name', label: 'Name' }),createBaseConfiguration({ variable: 'email', label: 'Email' }),@@ -942,16 +774,13 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actrender(<Options {...props} />)- // Assertexpect(screen.getByTestId('field-name')).toBeInTheDocument()expect(screen.getByTestId('field-email')).toBeInTheDocument()})it('should render CustomActions', () => {- // Arrangeconst props = {initialData: {},configurations: [],@@ -962,15 +791,12 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actrender(<Options {...props} />)- // Assertexpect(screen.getByTestId('custom-action')).toBeInTheDocument()})it('should render with correct class name', () => {- // Arrangeconst props = {initialData: {},configurations: [],@@ -979,10 +805,8 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actconst { container } = render(<Options {...props} />)- // Assertconst form = container.querySelector('form')expect(form).toHaveClass('w-full')})@@ -990,7 +814,6 @@ describe('Options', () => {describe('Form Submission', () => {it('should prevent default form submission', () => {- // Arrangeconst mockOnSubmit = vi.fn()const props = {initialData: {},@@ -1000,7 +823,6 @@ describe('Options', () => {onSubmit: mockOnSubmit,}- // Actconst { container } = render(<Options {...props} />)const form = container.querySelector('form')!const submitEvent = new Event('submit', { bubbles: true, cancelable: true })@@ -1008,12 +830,10 @@ describe('Options', () => {fireEvent(form, submitEvent)- // Assertexpect(preventDefaultSpy).toHaveBeenCalled()})it('should stop propagation on form submit', () => {- // Arrangeconst mockOnSubmit = vi.fn()const props = {initialData: {},@@ -1023,7 +843,6 @@ describe('Options', () => {onSubmit: mockOnSubmit,}- // Actconst { container } = render(<Options {...props} />)const form = container.querySelector('form')!const submitEvent = new Event('submit', { bubbles: true, cancelable: true })@@ -1031,12 +850,10 @@ describe('Options', () => {fireEvent(form, submitEvent)- // Assertexpect(stopPropagationSpy).toHaveBeenCalled()})it('should call onSubmit when validation passes', () => {- // Arrangeconst mockOnSubmit = vi.fn()const props = {initialData: {},@@ -1046,17 +863,14 @@ describe('Options', () => {onSubmit: mockOnSubmit,}- // Actconst { container } = render(<Options {...props} />)const form = container.querySelector('form')!fireEvent.submit(form)- // Assertexpect(mockOnSubmit).toHaveBeenCalled()})it('should not call onSubmit when validation fails', () => {- // Arrangeconst mockOnSubmit = vi.fn()const failingSchema = {safeParse: vi.fn().mockReturnValue({@@ -1076,17 +890,14 @@ describe('Options', () => {onSubmit: mockOnSubmit,}- // Actconst { container } = render(<Options {...props} />)const form = container.querySelector('form')!fireEvent.submit(form)- // Assertexpect(mockOnSubmit).not.toHaveBeenCalled()})it('should show toast error when validation fails', () => {- // Arrangeconst failingSchema = {safeParse: vi.fn().mockReturnValue({success: false,@@ -1105,12 +916,10 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actconst { container } = render(<Options {...props} />)const form = container.querySelector('form')!fireEvent.submit(form)- // Assertexpect(mockToastNotify).toHaveBeenCalledWith({type: 'error',message: 'Path: name Error: Name is required',@@ -1118,7 +927,6 @@ describe('Options', () => {})it('should format error message with multiple path segments', () => {- // Arrangeconst failingSchema = {safeParse: vi.fn().mockReturnValue({success: false,@@ -1137,12 +945,10 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actconst { container } = render(<Options {...props} />)const form = container.querySelector('form')!fireEvent.submit(form)- // Assertexpect(mockToastNotify).toHaveBeenCalledWith({type: 'error',message: 'Path: user.profile.email Error: Invalid email format',@@ -1150,7 +956,6 @@ describe('Options', () => {})it('should only show first validation error when multiple errors exist', () => {- // Arrangeconst failingSchema = {safeParse: vi.fn().mockReturnValue({success: false,@@ -1171,12 +976,10 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actconst { container } = render(<Options {...props} />)const form = container.querySelector('form')!fireEvent.submit(form)- // Assert - should only show first errorexpect(mockToastNotify).toHaveBeenCalledTimes(1)expect(mockToastNotify).toHaveBeenCalledWith({type: 'error',@@ -1185,7 +988,6 @@ describe('Options', () => {})it('should handle empty path in validation error', () => {- // Arrangeconst failingSchema = {safeParse: vi.fn().mockReturnValue({success: false,@@ -1204,12 +1006,10 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actconst { container } = render(<Options {...props} />)const form = container.querySelector('form')!fireEvent.submit(form)- // Assertexpect(mockToastNotify).toHaveBeenCalledWith({type: 'error',message: 'Path: Error: Form validation failed',@@ -1219,7 +1019,6 @@ describe('Options', () => {describe('Field Rendering', () => {it('should render fields in correct order', () => {- // Arrangeconst configurations = [createBaseConfiguration({ variable: 'first', label: 'First' }),createBaseConfiguration({ variable: 'second', label: 'Second' }),@@ -1233,22 +1032,18 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actrender(<Options {...props} />)- // Assert - check that each field container exists with correct orderexpect(screen.getByTestId('field-first')).toBeInTheDocument()expect(screen.getByTestId('field-second')).toBeInTheDocument()expect(screen.getByTestId('field-third')).toBeInTheDocument()- // Verify order by checking labels within each fieldexpect(screen.getByTestId('field-label-first')).toHaveTextContent('First')expect(screen.getByTestId('field-label-second')).toHaveTextContent('Second')expect(screen.getByTestId('field-label-third')).toHaveTextContent('Third')})it('should pass config to BaseField', () => {- // Arrangeconst configurations = [createBaseConfiguration({variable: 'test',@@ -1265,10 +1060,8 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actrender(<Options {...props} />)- // Assertexpect(screen.getByTestId('field-label-test')).toHaveTextContent('Test Label')expect(screen.getByTestId('field-type-test')).toHaveTextContent(BaseFieldType.textInput)expect(screen.getByTestId('field-required-test')).toHaveTextContent('true')@@ -1277,7 +1070,6 @@ describe('Options', () => {describe('Edge Cases', () => {it('should handle empty initialData', () => {- // Arrangeconst props = {initialData: {},configurations: [createBaseConfiguration()],@@ -1286,15 +1078,12 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actconst { container } = render(<Options {...props} />)- // Assertexpect(container.querySelector('form')).toBeInTheDocument()})it('should handle empty configurations', () => {- // Arrangeconst props = {initialData: {},configurations: [],@@ -1303,15 +1092,12 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actrender(<Options {...props} />)- // Assertexpect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()})it('should handle configurations with all field types', () => {- // Arrangeconst configurations = [createBaseConfiguration({ type: BaseFieldType.textInput, variable: 'text' }),createBaseConfiguration({ type: BaseFieldType.paragraph, variable: 'paragraph' }),@@ -1333,10 +1119,8 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actrender(<Options {...props} />)- // Assertexpect(screen.getByTestId('field-text')).toBeInTheDocument()expect(screen.getByTestId('field-paragraph')).toBeInTheDocument()expect(screen.getByTestId('field-number')).toBeInTheDocument()@@ -1345,7 +1129,6 @@ describe('Options', () => {})it('should handle large number of configurations', () => {- // Arrangeconst configurations = Array.from({ length: 20 }, (_, i) =>createBaseConfiguration({ variable: `field_${i}`, label: `Field ${i}` }))const props = {@@ -1356,21 +1139,14 @@ describe('Options', () => {onSubmit: vi.fn(),}- // Actrender(<Options {...props} />)- // Assertexpect(screen.getAllByTestId(/^field-field_/)).toHaveLength(20)})})})-// ============================================================================-// useInputVariables Hook Tests-// ============================================================================-describe('useInputVariables Hook', () => {- // Import hook directly for isolated testing// Note: The hook is tested via component tests above, but we add specific hook tests herebeforeEach(() => {@@ -1382,10 +1158,8 @@ describe('useInputVariables Hook', () => {describe('Return Values', () => {it('should return isFetchingParams state', () => {- // ArrangesetupMocks({ isFetchingParams: true })- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1395,17 +1169,14 @@ describe('useInputVariables Hook', () => {/>,)- // Assert - verified by checking process button is disabledconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})it('should return paramsConfig when data is loaded', () => {- // Arrangeconst variables = [createRAGPipelineVariable()]setupMocks({ paramsConfig: { variables } })- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1415,18 +1186,15 @@ describe('useInputVariables Hook', () => {/>,)- // Assertexpect(mockUseInitialData).toHaveBeenCalledWith(variables)})})describe('Query Behavior', () => {it('should use pipelineId from store', () => {- // ArrangemockPipelineId = 'custom-pipeline-id'setupMocks()- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1436,16 +1204,13 @@ describe('useInputVariables Hook', () => {/>,)- // Assert - component renders successfully with the pipelineIdexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})it('should handle null pipelineId gracefully', () => {- // ArrangemockPipelineId = nullsetupMocks({ pipelineId: null })- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1455,16 +1220,11 @@ describe('useInputVariables Hook', () => {/>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})})})-// ============================================================================-// Integration Tests-// ============================================================================-describe('DocumentProcessing Integration', () => {beforeEach(() => {vi.clearAllMocks()@@ -1473,7 +1233,6 @@ describe('DocumentProcessing Integration', () => {describe('Full Flow', () => {it('should integrate hooks, Options, and Actions correctly', () => {- // Arrangeconst variables = [createRAGPipelineVariable({ variable: 'input1', label: 'Input 1' }),createRAGPipelineVariable({ variable: 'input2', label: 'Input 2' }),@@ -1488,7 +1247,6 @@ describe('DocumentProcessing Integration', () => {initialData: { input1: '', input2: '' },})- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1498,7 +1256,6 @@ describe('DocumentProcessing Integration', () => {/>,)- // Assertexpect(screen.getByTestId('field-input1')).toBeInTheDocument()expect(screen.getByTestId('field-input2')).toBeInTheDocument()expect(screen.getByText('datasetPipeline.operations.backToDataSource')).toBeInTheDocument()@@ -1506,12 +1263,10 @@ describe('DocumentProcessing Integration', () => {})it('should pass data through the component hierarchy', () => {- // Arrangeconst mockOnProcess = vi.fn()const mockOnBack = vi.fn()setupMocks()- // ActrenderWithQueryClient(<DocumentProcessingdataSourceNodeId="test-node"@@ -1520,22 +1275,18 @@ describe('DocumentProcessing Integration', () => {/>,)- // Click back buttonfireEvent.click(screen.getByText('datasetPipeline.operations.backToDataSource'))- // Assertexpect(mockOnBack).toHaveBeenCalled()})})describe('State Synchronization', () => {it('should update when workflow running status changes', () => {- // ArrangesetupMocks({workflowRunningData: { result: { status: WorkflowRunningStatus.Running } },})- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1545,16 +1296,13 @@ describe('DocumentProcessing Integration', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})it('should update when fetching params status changes', () => {- // ArrangesetupMocks({ isFetchingParams: true })- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1564,17 +1312,12 @@ describe('DocumentProcessing Integration', () => {/>,)- // Assertconst processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()})})})-// ============================================================================-// Prop Variations Tests-// ============================================================================-describe('Prop Variations', () => {beforeEach(() => {vi.clearAllMocks()@@ -1589,7 +1332,6 @@ describe('Prop Variations', () => {['node.with.dots'],['very-long-node-id-that-could-potentially-cause-issues-if-not-handled-properly'],])('should handle dataSourceNodeId: %s', (nodeId) => {- // ActrenderWithQueryClient(<DocumentProcessingdataSourceNodeId={nodeId}@@ -1598,18 +1340,15 @@ describe('Prop Variations', () => {/>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})})describe('Callback Variations', () => {it('should work with synchronous onProcess', () => {- // Arrangeconst syncCallback = vi.fn()setupMocks()- // ActrenderWithQueryClient(<DocumentProcessingdataSourceNodeId="test-node"@@ -1618,16 +1357,13 @@ describe('Prop Variations', () => {/>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})it('should work with async onProcess', () => {- // Arrangeconst asyncCallback = vi.fn().mockResolvedValue(undefined)setupMocks()- // ActrenderWithQueryClient(<DocumentProcessingdataSourceNodeId="test-node"@@ -1636,20 +1372,17 @@ describe('Prop Variations', () => {/>,)- // Assertexpect(screen.getByTestId('form-actions')).toBeInTheDocument()})})describe('Configuration Variations', () => {it('should handle required fields', () => {- // Arrangeconst configurations = [createBaseConfiguration({ variable: 'required', required: true }),]setupMocks({ configurations })- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1659,18 +1392,15 @@ describe('Prop Variations', () => {/>,)- // Assertexpect(screen.getByTestId('field-required-required')).toHaveTextContent('true')})it('should handle optional fields', () => {- // Arrangeconst configurations = [createBaseConfiguration({ variable: 'optional', required: false }),]setupMocks({ configurations })- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1680,12 +1410,10 @@ describe('Prop Variations', () => {/>,)- // Assertexpect(screen.getByTestId('field-required-optional')).toHaveTextContent('false')})it('should handle mixed required and optional fields', () => {- // Arrangeconst configurations = [createBaseConfiguration({ variable: 'required1', required: true }),createBaseConfiguration({ variable: 'optional1', required: false }),@@ -1693,7 +1421,6 @@ describe('Prop Variations', () => {]setupMocks({ configurations })- // ActrenderWithQueryClient(<DocumentProcessing {...{dataSourceNodeId: 'test-node',@@ -1703,7 +1430,6 @@ describe('Prop Variations', () => {/>,)- // Assertexpect(screen.getByTestId('field-required-required1')).toHaveTextContent('true')expect(screen.getByTestId('field-required-optional1')).toHaveTextContent('false')expect(screen.getByTestId('field-required-required2')).toHaveTextContent('true')diff --git a/web/app/components/rag-pipeline/components/panel/test-run/result/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/result/__tests__/index.spec.tsxsimilarity index 81%rename from web/app/components/rag-pipeline/components/panel/test-run/result/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/test-run/result/__tests__/index.spec.tsxindex d3204ae29a8..249a13023c2 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/result/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/result/__tests__/index.spec.tsx@@ -5,41 +5,19 @@ import * as React from 'react'import { BlockEnum, WorkflowRunningStatus } from '@/app/components/workflow/types'import { RAG_PIPELINE_PREVIEW_CHUNK_NUM } from '@/config'import { ChunkingMode } from '@/models/datasets'-import Result from './index'-import ResultPreview from './result-preview'-import { formatPreviewChunks } from './result-preview/utils'-import Tabs from './tabs'-import Tab from './tabs/tab'--// ============================================================================-// Pre-declare variables used in mocks (hoisting)-// ============================================================================+import Result from '../index'+import ResultPreview from '../result-preview'+import { formatPreviewChunks } from '../result-preview/utils'+import Tabs from '../tabs'+import Tab from '../tabs/tab'let mockWorkflowRunningData: WorkflowRunningData | undefined-// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock react-i18next-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, options?: { ns?: string, count?: number }) => {- const ns = options?.ns ? `${options.ns}.` : ''- if (options?.count !== undefined)- return `${ns}${key} (count: ${options.count})`- return `${ns}${key}`- },- }),-}))--// Mock workflow storevi.mock('@/app/components/workflow/store', () => ({useStore: <T,>(selector: (state: { workflowRunningData: WorkflowRunningData | undefined }) => T) =>selector({ workflowRunningData: mockWorkflowRunningData }),}))-// Mock child componentsvi.mock('@/app/components/workflow/run/result-panel', () => ({default: ({inputs,@@ -102,10 +80,6 @@ vi.mock('@/app/components/rag-pipeline/components/chunk-card-list', () => ({),}))-// ============================================================================-// Test Data Factories-// ============================================================================-const createMockWorkflowRunningData = (overrides?: Partial<WorkflowRunningData>,): WorkflowRunningData => ({@@ -191,26 +165,15 @@ const createQAChunkOutputs = (qaCount: number = 5) => ({})),})-// ============================================================================-// Helper Functions-// ============================================================================-const resetAllMocks = () => {mockWorkflowRunningData = undefined}-// ============================================================================-// Tab Component Tests-// ============================================================================-describe('Tab', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render tab with label', () => {const mockOnClick = vi.fn()@@ -283,9 +246,6 @@ describe('Tab', () => {})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onClick with value when clicked', () => {const mockOnClick = vi.fn()@@ -325,9 +285,6 @@ describe('Tab', () => {})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should maintain stable handleClick callback reference', () => {const mockOnClick = vi.fn()@@ -353,33 +310,26 @@ describe('Tab', () => {})})- // -------------------------------------------------------------------------- // Props Variation Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should render with all combinations of isActive and workflowRunningData', () => {const mockOnClick = vi.fn()const workflowData = createMockWorkflowRunningData()- // Active with dataconst { rerender } = render(<Tab isActive={true} label="Tab" value="tab" workflowRunningData={workflowData} onClick={mockOnClick} />,)expect(screen.getByRole('button')).not.toBeDisabled()- // Inactive with datarerender(<Tab isActive={false} label="Tab" value="tab" workflowRunningData={workflowData} onClick={mockOnClick} />,)expect(screen.getByRole('button')).not.toBeDisabled()- // Active without datarerender(<Tab isActive={true} label="Tab" value="tab" workflowRunningData={undefined} onClick={mockOnClick} />,)expect(screen.getByRole('button')).toBeDisabled()- // Inactive without datarerender(<Tab isActive={false} label="Tab" value="tab" workflowRunningData={undefined} onClick={mockOnClick} />,)@@ -388,18 +338,11 @@ describe('Tab', () => {})})-// ============================================================================-// Tabs Component Tests-// ============================================================================-describe('Tabs', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render all three tabs', () => {render(@@ -440,18 +383,12 @@ describe('Tabs', () => {)const buttons = screen.getAllByRole('button')- // RESULT tabexpect(buttons[0]).toHaveClass('border-transparent')- // DETAIL tab (active)expect(buttons[1]).toHaveClass('border-util-colors-blue-brand-blue-brand-600')- // TRACING tabexpect(buttons[2]).toHaveClass('border-transparent')})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call switchTab when RESULT tab is clicked', () => {const mockSwitchTab = vi.fn()@@ -522,9 +459,6 @@ describe('Tabs', () => {})})- // -------------------------------------------------------------------------- // Props Variation Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should handle all currentTab values', () => {const mockSwitchTab = vi.fn()@@ -554,14 +488,7 @@ describe('Tabs', () => {})})-// ============================================================================-// formatPreviewChunks Utility Tests-// ============================================================================-describe('formatPreviewChunks', () => {- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should return undefined when outputs is null', () => {expect(formatPreviewChunks(null)).toBeUndefined()@@ -581,9 +508,6 @@ describe('formatPreviewChunks', () => {})})- // -------------------------------------------------------------------------- // General Chunks Tests- // -------------------------------------------------------------------------describe('General Chunks (text mode)', () => {it('should format general chunks correctly', () => {const outputs = createGeneralChunkOutputs(3)@@ -613,9 +537,6 @@ describe('formatPreviewChunks', () => {})})- // -------------------------------------------------------------------------- // Parent-Child Chunks Tests- // -------------------------------------------------------------------------describe('Parent-Child Chunks (hierarchical mode)', () => {it('should format paragraph mode chunks correctly', () => {const outputs = createParentChildChunkOutputs('paragraph', 3)@@ -678,9 +599,6 @@ describe('formatPreviewChunks', () => {})})- // -------------------------------------------------------------------------- // QA Chunks Tests- // -------------------------------------------------------------------------describe('QA Chunks (qa mode)', () => {it('should format QA chunks correctly', () => {const outputs = createQAChunkOutputs(3)@@ -710,18 +628,11 @@ describe('formatPreviewChunks', () => {})})-// ============================================================================-// ResultPreview Component Tests-// ============================================================================-describe('ResultPreview', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render loading state when isRunning is true and no outputs', () => {render(@@ -778,7 +689,7 @@ describe('ResultPreview', () => {)expect(- screen.getByText(`pipeline.result.resultPreview.footerTip (count: ${RAG_PIPELINE_PREVIEW_CHUNK_NUM})`),+ screen.getByText(`pipeline.result.resultPreview.footerTip:{"count":${RAG_PIPELINE_PREVIEW_CHUNK_NUM}}`),).toBeInTheDocument()})@@ -799,9 +710,6 @@ describe('ResultPreview', () => {})})- // -------------------------------------------------------------------------- // User Interaction Tests- // -------------------------------------------------------------------------describe('User Interactions', () => {it('should call onSwitchToDetail when view details button is clicked', () => {const mockOnSwitchToDetail = vi.fn()@@ -821,9 +729,6 @@ describe('ResultPreview', () => {})})- // -------------------------------------------------------------------------- // Props Variation Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {it('should render with general chunks output', () => {const outputs = createGeneralChunkOutputs(3)@@ -874,9 +779,6 @@ describe('ResultPreview', () => {})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle outputs with no previewChunks result', () => {const outputs = {@@ -893,7 +795,6 @@ describe('ResultPreview', () => {/>,)- // Should not render chunk card list when formatPreviewChunks returns undefinedexpect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()})@@ -907,14 +808,10 @@ describe('ResultPreview', () => {/>,)- // Error section should not render when isRunning is trueexpect(screen.queryByText('pipeline.result.resultPreview.error')).not.toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should memoize previewChunks calculation', () => {const outputs = createGeneralChunkOutputs(3)@@ -927,7 +824,6 @@ describe('ResultPreview', () => {/>,)- // Re-render with same outputs - should use memoized valuererender(<ResultPreviewisRunning={false}@@ -942,19 +838,12 @@ describe('ResultPreview', () => {})})-// ============================================================================-// Result Component Tests (Main Component)-// ============================================================================-describe('Result', () => {beforeEach(() => {vi.clearAllMocks()resetAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render tabs and result preview by default', () => {mockWorkflowRunningData = createMockWorkflowRunningData({@@ -967,7 +856,6 @@ describe('Result', () => {render(<Result />)- // Tabs should be renderedexpect(screen.getByText('runLog.result')).toBeInTheDocument()expect(screen.getByText('runLog.detail')).toBeInTheDocument()expect(screen.getByText('runLog.tracing')).toBeInTheDocument()@@ -1003,9 +891,6 @@ describe('Result', () => {})})- // -------------------------------------------------------------------------- // Tab Switching Tests- // -------------------------------------------------------------------------describe('Tab Switching', () => {it('should switch to DETAIL tab when clicked', async () => {mockWorkflowRunningData = createMockWorkflowRunningData()@@ -1042,13 +927,11 @@ describe('Result', () => {render(<Result />)- // Switch to DETAILfireEvent.click(screen.getByText('runLog.detail'))await waitFor(() => {expect(screen.getByTestId('result-panel')).toBeInTheDocument()})- // Switch back to RESULTfireEvent.click(screen.getByText('runLog.result'))await waitFor(() => {expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()@@ -1056,9 +939,6 @@ describe('Result', () => {})})- // -------------------------------------------------------------------------- // DETAIL Tab Content Tests- // -------------------------------------------------------------------------describe('DETAIL Tab Content', () => {it('should render ResultPanel with correct props', async () => {mockWorkflowRunningData = createMockWorkflowRunningData({@@ -1109,9 +989,6 @@ describe('Result', () => {})})- // -------------------------------------------------------------------------- // TRACING Tab Content Tests- // -------------------------------------------------------------------------describe('TRACING Tab Content', () => {it('should render TracingPanel with tracing data', async () => {mockWorkflowRunningData = createMockWorkflowRunningData()@@ -1137,15 +1014,11 @@ describe('Result', () => {fireEvent.click(screen.getByText('runLog.tracing'))await waitFor(() => {- // Both TracingPanel and Loading should be renderedexpect(screen.getByTestId('tracing-panel')).toBeInTheDocument()})})})- // -------------------------------------------------------------------------- // Switch to Detail from Result Preview Tests- // -------------------------------------------------------------------------describe('Switch to Detail from Result Preview', () => {it('should switch to DETAIL tab when onSwitchToDetail is triggered from ResultPreview', async () => {mockWorkflowRunningData = createMockWorkflowRunningData({@@ -1159,7 +1032,6 @@ describe('Result', () => {render(<Result />)- // Click the view details button in error statefireEvent.click(screen.getByText('pipeline.result.resultPreview.viewDetails'))await waitFor(() => {@@ -1168,16 +1040,12 @@ describe('Result', () => {})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle undefined workflowRunningData', () => {mockWorkflowRunningData = undefinedrender(<Result />)- // All tabs should be disabledconst buttons = screen.getAllByRole('button')buttons.forEach((button) => {expect(button).toBeDisabled()@@ -1193,7 +1061,6 @@ describe('Result', () => {render(<Result />)- // Should show loading in RESULT tab (isRunning condition)expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()})@@ -1223,36 +1090,28 @@ describe('Result', () => {render(<Result />)- // Should show error when stoppedexpect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // State Management Tests- // -------------------------------------------------------------------------describe('State Management', () => {it('should maintain tab state across re-renders', async () => {mockWorkflowRunningData = createMockWorkflowRunningData()const { rerender } = render(<Result />)- // Switch to DETAIL tabfireEvent.click(screen.getByText('runLog.detail'))await waitFor(() => {expect(screen.getByTestId('result-panel')).toBeInTheDocument()})- // Re-render componentrerender(<Result />)- // Should still be on DETAIL tabexpect(screen.getByTestId('result-panel')).toBeInTheDocument()})it('should render different states based on workflowRunningData', () => {- // Test 1: Running state with no outputsmockWorkflowRunningData = createMockWorkflowRunningData({result: {...createMockWorkflowRunningData().result,@@ -1265,7 +1124,6 @@ describe('Result', () => {expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()unmount()- // Test 2: Completed state with outputsconst outputs = createGeneralChunkOutputs(3)mockWorkflowRunningData = createMockWorkflowRunningData({result: {@@ -1280,19 +1138,14 @@ describe('Result', () => {})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {it('should be memoized', () => {mockWorkflowRunningData = createMockWorkflowRunningData()const { rerender } = render(<Result />)- // Re-render without changesrerender(<Result />)- // Component should still be rendered correctlyexpect(screen.getByText('runLog.result')).toBeInTheDocument()})})diff --git a/web/app/components/rag-pipeline/components/panel/test-run/result/result-preview/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/result/result-preview/__tests__/index.spec.tsxsimilarity index 79%rename from web/app/components/rag-pipeline/components/panel/test-run/result/result-preview/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/test-run/result/result-preview/__tests__/index.spec.tsxindex 8dd0bf759fa..1245d2aca5b 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/result/result-preview/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/result/result-preview/__tests__/index.spec.tsx@@ -1,32 +1,15 @@-import type { ChunkInfo, GeneralChunks, ParentChildChunks, QAChunks } from '../../../../chunk-card-list/types'+import type { ChunkInfo, GeneralChunks, ParentChildChunks, QAChunks } from '../../../../../chunk-card-list/types'import { fireEvent, render, screen } from '@testing-library/react'import * as React from 'react'import { ChunkingMode } from '@/models/datasets'-import ResultPreview from './index'-import { formatPreviewChunks } from './utils'--// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock react-i18next-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, options?: { ns?: string, count?: number }) => {- const ns = options?.ns ? `${options.ns}.` : ''- const count = options?.count !== undefined ? ` (count: ${options.count})` : ''- return `${ns}${key}${count}`- },- }),-}))+import ResultPreview from '../index'+import { formatPreviewChunks } from '../utils'-// Mock configvi.mock('@/config', () => ({RAG_PIPELINE_PREVIEW_CHUNK_NUM: 20,}))-// Mock ChunkCardList component-vi.mock('../../../../chunk-card-list', () => ({+vi.mock('../../../../../chunk-card-list', () => ({ChunkCardList: ({ chunkType, chunkInfo }: { chunkType: string, chunkInfo: ChunkInfo }) => (<div data-testid="chunk-card-list" data-chunk-type={chunkType} data-chunk-info={JSON.stringify(chunkInfo)}>ChunkCardList@@ -34,10 +17,6 @@ vi.mock('../../../../chunk-card-list', () => ({),}))-// ============================================================================-// Test Data Factories-// ============================================================================-/*** Factory for creating general chunk preview outputs*/@@ -98,52 +77,35 @@ const createMockQAChunks = (count: number): Array<{ question: string, answer: st}))}-// ============================================================================-// formatPreviewChunks Utility Tests-// ============================================================================-describe('formatPreviewChunks', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Null/Undefined Input Tests- // -------------------------------------------------------------------------describe('Null/Undefined Input', () => {it('should return undefined when outputs is undefined', () => {- // Arrange & Actconst result = formatPreviewChunks(undefined)- // Assertexpect(result).toBeUndefined()})it('should return undefined when outputs is null', () => {- // Arrange & Actconst result = formatPreviewChunks(null)- // Assertexpect(result).toBeUndefined()})})- // -------------------------------------------------------------------------- // General Chunks (text_model) Tests- // -------------------------------------------------------------------------describe('General Chunks (text_model)', () => {it('should format general chunks correctly', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'First chunk content' },{ content: 'Second chunk content' },{ content: 'Third chunk content' },])- // Actconst result = formatPreviewChunks(outputs) as GeneralChunks- // Assertexpect(result).toEqual([{ content: 'First chunk content', summary: undefined },{ content: 'Second chunk content', summary: undefined },@@ -152,40 +114,31 @@ describe('formatPreviewChunks', () => {})it('should limit general chunks to RAG_PIPELINE_PREVIEW_CHUNK_NUM (20)', () => {- // Arrangeconst outputs = createGeneralChunkOutputs(createMockGeneralChunks(30))- // Actconst result = formatPreviewChunks(outputs) as GeneralChunks- // Assertexpect(result).toHaveLength(20)expect((result as GeneralChunks)[0].content).toBe('Chunk content 1')expect((result as GeneralChunks)[19].content).toBe('Chunk content 20')})it('should handle empty preview array for general chunks', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([])- // Actconst result = formatPreviewChunks(outputs) as GeneralChunks- // Assertexpect(result).toEqual([])})it('should handle general chunks with empty content', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: '' },{ content: 'Valid content' },])- // Actconst result = formatPreviewChunks(outputs) as GeneralChunks- // Assertexpect(result).toEqual([{ content: '', summary: undefined },{ content: 'Valid content', summary: undefined },@@ -193,17 +146,14 @@ describe('formatPreviewChunks', () => {})it('should handle general chunks with special characters', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: '<script>alert("xss")</script>' },{ content: '中文内容 🎉' },{ content: 'Line1\nLine2\tTab' },])- // Actconst result = formatPreviewChunks(outputs) as GeneralChunks- // Assertexpect(result).toEqual([{ content: '<script>alert("xss")</script>', summary: undefined },{ content: '中文内容 🎉', summary: undefined },@@ -212,34 +162,25 @@ describe('formatPreviewChunks', () => {})it('should handle general chunks with very long content', () => {- // Arrangeconst longContent = 'A'.repeat(10000)const outputs = createGeneralChunkOutputs([{ content: longContent }])- // Actconst result = formatPreviewChunks(outputs) as GeneralChunks- // Assertexpect((result as GeneralChunks)[0].content).toHaveLength(10000)})})- // -------------------------------------------------------------------------- // Parent-Child Chunks (hierarchical_model) Tests- // -------------------------------------------------------------------------describe('Parent-Child Chunks (hierarchical_model)', () => {describe('Paragraph Mode', () => {it('should format parent-child chunks in paragraph mode correctly', () => {- // Arrangeconst outputs = createParentChildChunkOutputs([{ content: 'Parent 1', child_chunks: ['Child 1-1', 'Child 1-2'] },{ content: 'Parent 2', child_chunks: ['Child 2-1'] },], 'paragraph')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assertexpect(result.parent_mode).toBe('paragraph')expect(result.parent_child_chunks).toHaveLength(2)expect(result.parent_child_chunks[0]).toEqual({@@ -255,54 +196,42 @@ describe('formatPreviewChunks', () => {})it('should limit parent chunks to RAG_PIPELINE_PREVIEW_CHUNK_NUM (20) in paragraph mode', () => {- // Arrangeconst outputs = createParentChildChunkOutputs(createMockParentChildChunks(30, 2), 'paragraph')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assertexpect(result.parent_child_chunks).toHaveLength(20)})it('should NOT limit child chunks in paragraph mode', () => {- // Arrangeconst outputs = createParentChildChunkOutputs([{ content: 'Parent 1', child_chunks: Array.from({ length: 50 }, (_, i) => `Child ${i + 1}`) },], 'paragraph')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assertexpect(result.parent_child_chunks[0].child_contents).toHaveLength(50)})it('should handle empty child_chunks in paragraph mode', () => {- // Arrangeconst outputs = createParentChildChunkOutputs([{ content: 'Parent with no children', child_chunks: [] },], 'paragraph')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assertexpect(result.parent_child_chunks[0].child_contents).toEqual([])})})describe('Full-Doc Mode', () => {it('should format parent-child chunks in full-doc mode correctly', () => {- // Arrangeconst outputs = createParentChildChunkOutputs([{ content: 'Full Doc Parent', child_chunks: ['Child 1', 'Child 2', 'Child 3'] },], 'full-doc')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assertexpect(result.parent_mode).toBe('full-doc')expect(result.parent_child_chunks).toHaveLength(1)expect(result.parent_child_chunks[0].parent_content).toBe('Full Doc Parent')@@ -310,74 +239,56 @@ describe('formatPreviewChunks', () => {})it('should NOT limit parent chunks in full-doc mode', () => {- // Arrangeconst outputs = createParentChildChunkOutputs(createMockParentChildChunks(30, 2), 'full-doc')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assert - full-doc mode processes all parents (forEach without slice)expect(result.parent_child_chunks).toHaveLength(30)})it('should limit child chunks to RAG_PIPELINE_PREVIEW_CHUNK_NUM (20) in full-doc mode', () => {- // Arrangeconst outputs = createParentChildChunkOutputs([{ content: 'Parent', child_chunks: Array.from({ length: 50 }, (_, i) => `Child ${i + 1}`) },], 'full-doc')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assertexpect(result.parent_child_chunks[0].child_contents).toHaveLength(20)expect(result.parent_child_chunks[0].child_contents[0]).toBe('Child 1')expect(result.parent_child_chunks[0].child_contents[19]).toBe('Child 20')})it('should handle multiple parents with many children in full-doc mode', () => {- // Arrangeconst outputs = createParentChildChunkOutputs([{ content: 'Parent 1', child_chunks: Array.from({ length: 25 }, (_, i) => `P1-Child ${i + 1}`) },{ content: 'Parent 2', child_chunks: Array.from({ length: 30 }, (_, i) => `P2-Child ${i + 1}`) },], 'full-doc')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assertexpect(result.parent_child_chunks[0].child_contents).toHaveLength(20)expect(result.parent_child_chunks[1].child_contents).toHaveLength(20)})})it('should handle empty preview array for parent-child chunks', () => {- // Arrangeconst outputs = createParentChildChunkOutputs([], 'paragraph')- // Actconst result = formatPreviewChunks(outputs) as ParentChildChunks- // Assertexpect(result.parent_child_chunks).toEqual([])})})- // -------------------------------------------------------------------------- // QA Chunks (qa_model) Tests- // -------------------------------------------------------------------------describe('QA Chunks (qa_model)', () => {it('should format QA chunks correctly', () => {- // Arrangeconst outputs = createQAChunkOutputs([{ question: 'What is Dify?', answer: 'Dify is an LLM application platform.' },{ question: 'How to use it?', answer: 'You can create apps easily.' },])- // Actconst result = formatPreviewChunks(outputs) as QAChunks- // Assertexpect(result.qa_chunks).toHaveLength(2)expect(result.qa_chunks[0]).toEqual({question: 'What is Dify?',@@ -390,38 +301,29 @@ describe('formatPreviewChunks', () => {})it('should limit QA chunks to RAG_PIPELINE_PREVIEW_CHUNK_NUM (20)', () => {- // Arrangeconst outputs = createQAChunkOutputs(createMockQAChunks(30))- // Actconst result = formatPreviewChunks(outputs) as QAChunks- // Assertexpect(result.qa_chunks).toHaveLength(20)})it('should handle empty qa_preview array', () => {- // Arrangeconst outputs = createQAChunkOutputs([])- // Actconst result = formatPreviewChunks(outputs) as QAChunks- // Assertexpect(result.qa_chunks).toEqual([])})it('should handle QA chunks with empty question or answer', () => {- // Arrangeconst outputs = createQAChunkOutputs([{ question: '', answer: 'Answer without question' },{ question: 'Question without answer', answer: '' },])- // Actconst result = formatPreviewChunks(outputs) as QAChunks- // Assertexpect(result.qa_chunks[0].question).toBe('')expect(result.qa_chunks[0].answer).toBe('Answer without question')expect(result.qa_chunks[1].question).toBe('Question without answer')@@ -429,7 +331,6 @@ describe('formatPreviewChunks', () => {})it('should preserve all properties when spreading chunk', () => {- // Arrangeconst outputs = {chunk_structure: ChunkingMode.qa,qa_preview: [@@ -437,90 +338,63 @@ describe('formatPreviewChunks', () => {] as unknown as Array<{ question: string, answer: string }>,}- // Actconst result = formatPreviewChunks(outputs) as QAChunks- // Assertexpect(result.qa_chunks[0]).toEqual({ question: 'Q1', answer: 'A1', extra: 'should be preserved' })})})- // -------------------------------------------------------------------------- // Unknown Chunking Mode Tests- // -------------------------------------------------------------------------describe('Unknown Chunking Mode', () => {it('should return undefined for unknown chunking mode', () => {- // Arrangeconst outputs = {chunk_structure: 'unknown_mode' as ChunkingMode,preview: [],}- // Actconst result = formatPreviewChunks(outputs)- // Assertexpect(result).toBeUndefined()})it('should return undefined when chunk_structure is missing', () => {- // Arrangeconst outputs = {preview: [{ content: 'test' }],}- // Actconst result = formatPreviewChunks(outputs)- // Assertexpect(result).toBeUndefined()})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle exactly RAG_PIPELINE_PREVIEW_CHUNK_NUM (20) chunks', () => {- // Arrangeconst outputs = createGeneralChunkOutputs(createMockGeneralChunks(20))- // Actconst result = formatPreviewChunks(outputs) as GeneralChunks- // Assertexpect(result).toHaveLength(20)})it('should handle outputs with additional properties', () => {- // Arrangeconst outputs = {...createGeneralChunkOutputs([{ content: 'Test' }]),extra_field: 'should not affect result',metadata: { some: 'data' },}- // Actconst result = formatPreviewChunks(outputs) as GeneralChunks- // Assertexpect(result).toEqual([{ content: 'Test', summary: undefined }])})})})-// ============================================================================-// ResultPreview Component Tests-// ============================================================================-describe('ResultPreview', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Default Props Factory- // -------------------------------------------------------------------------const defaultProps = {isRunning: false,outputs: undefined,@@ -528,117 +402,85 @@ describe('ResultPreview', () => {onSwitchToDetail: vi.fn(),}- // -------------------------------------------------------------------------- // Rendering Tests- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing with minimal props', () => {- // Arrange & Actrender(<ResultPreview onSwitchToDetail={vi.fn()} />)- // Assert - Component renders (no visible content in empty state)expect(document.body).toBeInTheDocument()})it('should render loading state when isRunning and no outputs', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} isRunning={true} outputs={undefined} />)- // Assertexpect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()})it('should render loading spinner icon when loading', () => {- // Arrange & Actconst { container } = render(<ResultPreview {...defaultProps} isRunning={true} outputs={undefined} />)- // Assert - Check for animate-spin class (loading spinner)const spinner = container.querySelector('.animate-spin')expect(spinner).toBeInTheDocument()})it('should render error state when not running and error exists', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} isRunning={false} error="Something went wrong" />)- // Assertexpect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()expect(screen.getByRole('button', { name: /pipeline\.result\.resultPreview\.viewDetails/i })).toBeInTheDocument()})it('should render outputs when available', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Test chunk' }])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertexpect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()})it('should render footer tip when outputs available', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Test chunk' }])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertexpect(screen.getByText(/pipeline\.result\.resultPreview\.footerTip/)).toBeInTheDocument()})it('should not render loading when outputs exist even if isRunning', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Test' }])- // Actrender(<ResultPreview {...defaultProps} isRunning={true} outputs={outputs} />)- // Assert - Should show outputs, not loadingexpect(screen.queryByText('pipeline.result.resultPreview.loading')).not.toBeInTheDocument()expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()})it('should not render error when isRunning is true', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} isRunning={true} error="Error message" outputs={undefined} />)- // Assert - Should show loading, not errorexpect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()expect(screen.queryByText('pipeline.result.resultPreview.error')).not.toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Props Variations Tests- // -------------------------------------------------------------------------describe('Props Variations', () => {describe('isRunning prop', () => {it('should show loading when isRunning=true and no outputs', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} isRunning={true} />)- // Assertexpect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()})it('should not show loading when isRunning=false', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} isRunning={false} />)- // Assertexpect(screen.queryByText('pipeline.result.resultPreview.loading')).not.toBeInTheDocument()})it('should prioritize outputs over loading state', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Data' }])- // Actrender(<ResultPreview {...defaultProps} isRunning={true} outputs={outputs} />)- // Assertexpect(screen.queryByText('pipeline.result.resultPreview.loading')).not.toBeInTheDocument()expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()})@@ -646,28 +488,22 @@ describe('ResultPreview', () => {describe('outputs prop', () => {it('should pass chunk_structure to ChunkCardList', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Test' }])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst chunkList = screen.getByTestId('chunk-card-list')expect(chunkList).toHaveAttribute('data-chunk-type', ChunkingMode.text)})it('should format and pass previewChunks to ChunkCardList', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Chunk 1' },{ content: 'Chunk 2' },])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst chunkList = screen.getByTestId('chunk-card-list')const chunkInfo = JSON.parse(chunkList.getAttribute('data-chunk-info') || '[]')expect(chunkInfo).toEqual([@@ -677,29 +513,23 @@ describe('ResultPreview', () => {})it('should handle parent-child outputs', () => {- // Arrangeconst outputs = createParentChildChunkOutputs([{ content: 'Parent', child_chunks: ['Child 1', 'Child 2'] },])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst chunkList = screen.getByTestId('chunk-card-list')expect(chunkList).toHaveAttribute('data-chunk-type', ChunkingMode.parentChild)})it('should handle QA outputs', () => {- // Arrangeconst outputs = createQAChunkOutputs([{ question: 'Q1', answer: 'A1' },])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst chunkList = screen.getByTestId('chunk-card-list')expect(chunkList).toHaveAttribute('data-chunk-type', ChunkingMode.qa)})@@ -707,29 +537,22 @@ describe('ResultPreview', () => {describe('error prop', () => {it('should show error state when error is a non-empty string', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} error="Network error" />)- // Assertexpect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()})it('should show error state when error is an empty string', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} error="" />)- // Assert - Empty string is falsy, so error state should NOT showexpect(screen.queryByText('pipeline.result.resultPreview.error')).not.toBeInTheDocument()})it('should render both outputs and error when both exist (independent conditions)', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Data' }])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} error="Error" />)- // Assert - Both are rendered because conditions are independent in the componentexpect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()})@@ -737,65 +560,48 @@ describe('ResultPreview', () => {describe('onSwitchToDetail prop', () => {it('should be called when view details button is clicked', () => {- // Arrangeconst onSwitchToDetail = vi.fn()render(<ResultPreview {...defaultProps} error="Error" onSwitchToDetail={onSwitchToDetail} />)- // ActfireEvent.click(screen.getByRole('button', { name: /viewDetails/i }))- // Assertexpect(onSwitchToDetail).toHaveBeenCalledTimes(1)})it('should not be called automatically on render', () => {- // Arrangeconst onSwitchToDetail = vi.fn()- // Actrender(<ResultPreview {...defaultProps} error="Error" onSwitchToDetail={onSwitchToDetail} />)- // Assertexpect(onSwitchToDetail).not.toHaveBeenCalled()})})})- // -------------------------------------------------------------------------- // Memoization Tests- // -------------------------------------------------------------------------describe('Memoization', () => {describe('React.memo wrapper', () => {it('should be wrapped with React.memo', () => {- // Arrange & Actconst { rerender } = render(<ResultPreview {...defaultProps} />)rerender(<ResultPreview {...defaultProps} />)- // Assert - Component renders correctly after rerenderexpect(document.body).toBeInTheDocument()})it('should update when props change', () => {- // Arrangeconst { rerender } = render(<ResultPreview {...defaultProps} isRunning={false} />)- // Actrerender(<ResultPreview {...defaultProps} isRunning={true} />)- // Assertexpect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()})it('should update when outputs change', () => {- // Arrangeconst outputs1 = createGeneralChunkOutputs([{ content: 'First' }])const { rerender } = render(<ResultPreview {...defaultProps} outputs={outputs1} />)- // Actconst outputs2 = createGeneralChunkOutputs([{ content: 'Second' }])rerender(<ResultPreview {...defaultProps} outputs={outputs2} />)- // Assertconst chunkList = screen.getByTestId('chunk-card-list')const chunkInfo = JSON.parse(chunkList.getAttribute('data-chunk-info') || '[]')expect(chunkInfo).toEqual([{ content: 'Second' }])@@ -804,23 +610,19 @@ describe('ResultPreview', () => {describe('useMemo for previewChunks', () => {it('should compute previewChunks based on outputs', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Memoized chunk 1' },{ content: 'Memoized chunk 2' },])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst chunkList = screen.getByTestId('chunk-card-list')const chunkInfo = JSON.parse(chunkList.getAttribute('data-chunk-info') || '[]')expect(chunkInfo).toHaveLength(2)})it('should recompute when outputs reference changes', () => {- // Arrangeconst outputs1 = createGeneralChunkOutputs([{ content: 'Original' }])const { rerender } = render(<ResultPreview {...defaultProps} outputs={outputs1} />)@@ -828,64 +630,47 @@ describe('ResultPreview', () => {let chunkInfo = JSON.parse(chunkList.getAttribute('data-chunk-info') || '[]')expect(chunkInfo).toEqual([{ content: 'Original' }])- // Act - Change outputsconst outputs2 = createGeneralChunkOutputs([{ content: 'Updated' }])rerender(<ResultPreview {...defaultProps} outputs={outputs2} />)- // AssertchunkList = screen.getByTestId('chunk-card-list')chunkInfo = JSON.parse(chunkList.getAttribute('data-chunk-info') || '[]')expect(chunkInfo).toEqual([{ content: 'Updated' }])})it('should handle undefined outputs in useMemo', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} outputs={undefined} />)- // Assert - No chunk list renderedexpect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()})})})- // -------------------------------------------------------------------------- // Event Handlers Tests- // -------------------------------------------------------------------------describe('Event Handlers', () => {it('should call onSwitchToDetail when view details button is clicked', () => {- // Arrangeconst onSwitchToDetail = vi.fn()render(<ResultPreview {...defaultProps} error="Test error" onSwitchToDetail={onSwitchToDetail} />)- // ActfireEvent.click(screen.getByRole('button', { name: /viewDetails/i }))- // Assertexpect(onSwitchToDetail).toHaveBeenCalledTimes(1)})it('should handle multiple clicks on view details button', () => {- // Arrangeconst onSwitchToDetail = vi.fn()render(<ResultPreview {...defaultProps} error="Test error" onSwitchToDetail={onSwitchToDetail} />)const button = screen.getByRole('button', { name: /viewDetails/i })- // ActfireEvent.click(button)fireEvent.click(button)fireEvent.click(button)- // Assertexpect(onSwitchToDetail).toHaveBeenCalledTimes(3)})})- // -------------------------------------------------------------------------- // Edge Cases Tests- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle empty state (all props undefined/false)', () => {- // Arrange & Actconst { container } = render(<ResultPreviewisRunning={false}@@ -895,240 +680,178 @@ describe('ResultPreview', () => {/>,)- // Assert - Should render empty fragmentexpect(container.firstChild).toBeNull()})it('should handle outputs with empty preview chunks', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([])- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst chunkList = screen.getByTestId('chunk-card-list')const chunkInfo = JSON.parse(chunkList.getAttribute('data-chunk-info') || '[]')expect(chunkInfo).toEqual([])})it('should handle outputs that result in undefined previewChunks', () => {- // Arrangeconst outputs = {chunk_structure: 'invalid_mode' as ChunkingMode,preview: [],}- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assert - Should not render chunk list when previewChunks is undefinedexpect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()})it('should handle unmount cleanly', () => {- // Arrangeconst { unmount } = render(<ResultPreview {...defaultProps} />)- // Assertexpect(() => unmount()).not.toThrow()})it('should handle rapid prop changes', () => {- // Arrangeconst { rerender } = render(<ResultPreview {...defaultProps} />)- // Act - Rapidly change propsrerender(<ResultPreview {...defaultProps} isRunning={true} />)rerender(<ResultPreview {...defaultProps} isRunning={false} error="Error" />)rerender(<ResultPreview {...defaultProps} outputs={createGeneralChunkOutputs([{ content: 'Test' }])} />)rerender(<ResultPreview {...defaultProps} />)- // Assertexpect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()})it('should handle very large number of chunks', () => {- // Arrangeconst outputs = createGeneralChunkOutputs(createMockGeneralChunks(1000))- // Actrender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assert - Should only show first 20 chunksconst chunkList = screen.getByTestId('chunk-card-list')const chunkInfo = JSON.parse(chunkList.getAttribute('data-chunk-info') || '[]')expect(chunkInfo).toHaveLength(20)})it('should throw when outputs has null preview (slice called on null)', () => {- // Arrangeconst outputs = {chunk_structure: ChunkingMode.text,preview: null as unknown as Array<{ content: string }>,}- // Act & Assert - Component throws because slice is called on null preview- // This is expected behavior - the component doesn't validate inputexpect(() => render(<ResultPreview {...defaultProps} outputs={outputs} />)).toThrow()})})- // -------------------------------------------------------------------------- // Integration Tests- // -------------------------------------------------------------------------describe('Integration', () => {it('should transition from loading to output state', () => {- // Arrangeconst { rerender } = render(<ResultPreview {...defaultProps} isRunning={true} />)expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()- // Actconst outputs = createGeneralChunkOutputs([{ content: 'Loaded data' }])rerender(<ResultPreview {...defaultProps} isRunning={false} outputs={outputs} />)- // Assertexpect(screen.queryByText('pipeline.result.resultPreview.loading')).not.toBeInTheDocument()expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()})it('should transition from loading to error state', () => {- // Arrangeconst { rerender } = render(<ResultPreview {...defaultProps} isRunning={true} />)expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()- // Actrerender(<ResultPreview {...defaultProps} isRunning={false} error="Failed to load" />)- // Assertexpect(screen.queryByText('pipeline.result.resultPreview.loading')).not.toBeInTheDocument()expect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()})it('should render both error and outputs when both props provided', () => {- // Arrangeconst { rerender } = render(<ResultPreview {...defaultProps} error="Initial error" />)expect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()- // Act - Outputs provided while error still existsconst outputs = createGeneralChunkOutputs([{ content: 'Success data' }])rerender(<ResultPreview {...defaultProps} error="Initial error" outputs={outputs} />)- // Assert - Both are rendered (component uses independent conditions)expect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()})it('should hide error when error prop is cleared', () => {- // Arrangeconst { rerender } = render(<ResultPreview {...defaultProps} error="Initial error" />)expect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()- // Act - Clear error and provide outputsconst outputs = createGeneralChunkOutputs([{ content: 'Success data' }])rerender(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assert - Only outputs shown when error is clearedexpect(screen.queryByText('pipeline.result.resultPreview.error')).not.toBeInTheDocument()expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()})it('should handle complete flow: empty -> loading -> outputs', () => {- // Arrangeconst { rerender, container } = render(<ResultPreview {...defaultProps} />)expect(container.firstChild).toBeNull()- // Act - Start loadingrerender(<ResultPreview {...defaultProps} isRunning={true} />)expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()- // Act - Receive outputsconst outputs = createGeneralChunkOutputs([{ content: 'Final data' }])rerender(<ResultPreview {...defaultProps} isRunning={false} outputs={outputs} />)- // Assertexpect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()})})- // -------------------------------------------------------------------------- // Styling Tests- // -------------------------------------------------------------------------describe('Styling', () => {it('should have correct container classes for loading state', () => {- // Arrange & Actconst { container } = render(<ResultPreview {...defaultProps} isRunning={true} />)- // Assertconst loadingContainer = container.querySelector('.flex.grow.flex-col.items-center.justify-center')expect(loadingContainer).toBeInTheDocument()})it('should have correct container classes for error state', () => {- // Arrange & Actconst { container } = render(<ResultPreview {...defaultProps} error="Error" />)- // Assertconst errorContainer = container.querySelector('.flex.grow.flex-col.items-center.justify-center')expect(errorContainer).toBeInTheDocument()})it('should have correct container classes for outputs state', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Test' }])- // Actconst { container } = render(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst outputContainer = container.querySelector('.flex.grow.flex-col.bg-background-body')expect(outputContainer).toBeInTheDocument()})it('should have gradient dividers in footer', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Test' }])- // Actconst { container } = render(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst gradientDividers = container.querySelectorAll('.bg-gradient-to-r, .bg-gradient-to-l')expect(gradientDividers.length).toBeGreaterThanOrEqual(2)})})- // -------------------------------------------------------------------------- // Accessibility Tests- // -------------------------------------------------------------------------describe('Accessibility', () => {it('should have accessible button in error state', () => {- // Arrange & Actrender(<ResultPreview {...defaultProps} error="Error" />)- // Assertconst button = screen.getByRole('button')expect(button).toBeInTheDocument()})it('should have title attribute on footer tip for long text', () => {- // Arrangeconst outputs = createGeneralChunkOutputs([{ content: 'Test' }])- // Actconst { container } = render(<ResultPreview {...defaultProps} outputs={outputs} />)- // Assertconst footerTip = container.querySelector('[title]')expect(footerTip).toBeInTheDocument()})})})-// ============================================================================-// State Transition Matrix Tests-// ============================================================================-describe('State Transition Matrix', () => {beforeEach(() => {vi.clearAllMocks()@@ -1147,7 +870,6 @@ describe('State Transition Matrix', () => {it.each(states)('should render $expected state when isRunning=$isRunning, outputs=$outputs, error=$error',({ isRunning, outputs, error, expected }) => {- // Arrange & Actconst { container } = render(<ResultPreviewisRunning={isRunning}@@ -1157,7 +879,6 @@ describe('State Transition Matrix', () => {/>,)- // Assertswitch (expected) {case 'empty':expect(container.firstChild).toBeNull()diff --git a/web/app/components/rag-pipeline/components/panel/test-run/result/tabs/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/result/tabs/__tests__/index.spec.tsxsimilarity index 81%rename from web/app/components/rag-pipeline/components/panel/test-run/result/tabs/index.spec.tsxrename to web/app/components/rag-pipeline/components/panel/test-run/result/tabs/__tests__/index.spec.tsxindex ec7d404f6ea..65dfd06cf68 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/result/tabs/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/result/tabs/__tests__/index.spec.tsx@@ -1,25 +1,8 @@import type { WorkflowRunningData } from '@/app/components/workflow/types'import { fireEvent, render, screen } from '@testing-library/react'import * as React from 'react'-import Tabs from './index'-import Tab from './tab'--// ============================================================================-// Mock External Dependencies-// ============================================================================--vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, options?: { ns?: string }) => {- const ns = options?.ns ? `${options.ns}.` : ''- return `${ns}${key}`- },- }),-}))--// ============================================================================-// Test Data Factories-// ============================================================================+import Tabs from '../index'+import Tab from '../tab'/*** Factory function to create mock WorkflowRunningData@@ -52,25 +35,16 @@ const createWorkflowRunningData = (...overrides,})-// ============================================================================-// Tab Component Tests-// ============================================================================-describe('Tab', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests - Verify basic component rendering- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render tab with label correctly', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -81,16 +55,13 @@ describe('Tab', () => {/>,)- // Assertexpect(screen.getByRole('button', { name: 'Test Label' })).toBeInTheDocument()})it('should render as button element with correct type', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -101,23 +72,17 @@ describe('Tab', () => {/>,)- // Assertconst button = screen.getByRole('button')expect(button).toHaveAttribute('type', 'button')})})- // -------------------------------------------------------------------------- // Props Tests - Verify different prop combinations- // -------------------------------------------------------------------------describe('Props', () => {describe('isActive prop', () => {it('should apply active styles when isActive is true', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={true}@@ -128,18 +93,15 @@ describe('Tab', () => {/>,)- // Assertconst button = screen.getByRole('button')expect(button).toHaveClass('border-util-colors-blue-brand-blue-brand-600')expect(button).toHaveClass('text-text-primary')})it('should apply inactive styles when isActive is false', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -150,7 +112,6 @@ describe('Tab', () => {/>,)- // Assertconst button = screen.getByRole('button')expect(button).toHaveClass('text-text-tertiary')expect(button).toHaveClass('border-transparent')@@ -159,11 +120,9 @@ describe('Tab', () => {describe('label prop', () => {it('should display the provided label text', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -174,16 +133,13 @@ describe('Tab', () => {/>,)- // Assertexpect(screen.getByText('Custom Label Text')).toBeInTheDocument()})it('should handle empty label', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -194,18 +150,15 @@ describe('Tab', () => {/>,)- // Assertexpect(screen.getByRole('button')).toBeInTheDocument()expect(screen.getByRole('button')).toHaveTextContent('')})it('should handle long label text', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()const longLabel = 'This is a very long label text for testing purposes'- // Actrender(<TabisActive={false}@@ -216,19 +169,16 @@ describe('Tab', () => {/>,)- // Assertexpect(screen.getByText(longLabel)).toBeInTheDocument()})})describe('value prop', () => {it('should pass value to onClick handler when clicked', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()const testValue = 'CUSTOM_VALUE'- // Actrender(<TabisActive={false}@@ -240,18 +190,15 @@ describe('Tab', () => {)fireEvent.click(screen.getByRole('button'))- // Assertexpect(mockOnClick).toHaveBeenCalledWith(testValue)})})describe('workflowRunningData prop', () => {it('should enable button when workflowRunningData is provided', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -262,15 +209,12 @@ describe('Tab', () => {/>,)- // Assertexpect(screen.getByRole('button')).not.toBeDisabled()})it('should disable button when workflowRunningData is undefined', () => {- // Arrangeconst mockOnClick = vi.fn()- // Actrender(<TabisActive={false}@@ -281,15 +225,12 @@ describe('Tab', () => {/>,)- // Assertexpect(screen.getByRole('button')).toBeDisabled()})it('should apply disabled styles when workflowRunningData is undefined', () => {- // Arrangeconst mockOnClick = vi.fn()- // Actrender(<TabisActive={false}@@ -300,18 +241,15 @@ describe('Tab', () => {/>,)- // Assertconst button = screen.getByRole('button')expect(button).toHaveClass('!cursor-not-allowed')expect(button).toHaveClass('opacity-30')})it('should not have disabled styles when workflowRunningData is provided', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -322,7 +260,6 @@ describe('Tab', () => {/>,)- // Assertconst button = screen.getByRole('button')expect(button).not.toHaveClass('!cursor-not-allowed')expect(button).not.toHaveClass('opacity-30')@@ -330,16 +267,11 @@ describe('Tab', () => {})})- // -------------------------------------------------------------------------- // Event Handlers Tests - Verify click behavior- // -------------------------------------------------------------------------describe('Event Handlers', () => {it('should call onClick with value when clicked', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -351,16 +283,13 @@ describe('Tab', () => {)fireEvent.click(screen.getByRole('button'))- // Assertexpect(mockOnClick).toHaveBeenCalledTimes(1)expect(mockOnClick).toHaveBeenCalledWith('RESULT')})it('should not call onClick when disabled (no workflowRunningData)', () => {- // Arrangeconst mockOnClick = vi.fn()- // Actrender(<TabisActive={false}@@ -372,16 +301,13 @@ describe('Tab', () => {)fireEvent.click(screen.getByRole('button'))- // Assertexpect(mockOnClick).not.toHaveBeenCalled()})it('should handle multiple clicks correctly', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -396,17 +322,12 @@ describe('Tab', () => {fireEvent.click(button)fireEvent.click(button)- // Assertexpect(mockOnClick).toHaveBeenCalledTimes(3)})})- // -------------------------------------------------------------------------- // Memoization Tests - Verify React.memo optimization- // -------------------------------------------------------------------------describe('Memoization', () => {it('should not re-render when props are the same', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()const renderSpy = vi.fn()@@ -417,7 +338,6 @@ describe('Tab', () => {}const MemoizedTabWithSpy = React.memo(TabWithSpy)- // Actconst { rerender } = render(<MemoizedTabWithSpyisActive={false}@@ -428,7 +348,6 @@ describe('Tab', () => {/>,)- // Re-render with same propsrerender(<MemoizedTabWithSpyisActive={false}@@ -439,16 +358,13 @@ describe('Tab', () => {/>,)- // Assert - React.memo should prevent re-render with same propsexpect(renderSpy).toHaveBeenCalledTimes(1)})it('should re-render when isActive prop changes', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actconst { rerender } = render(<TabisActive={false}@@ -459,10 +375,8 @@ describe('Tab', () => {/>,)- // Assert initial stateexpect(screen.getByRole('button')).toHaveClass('text-text-tertiary')- // Rerender with changed proprerender(<TabisActive={true}@@ -473,16 +387,13 @@ describe('Tab', () => {/>,)- // Assert updated stateexpect(screen.getByRole('button')).toHaveClass('text-text-primary')})it('should re-render when label prop changes', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actconst { rerender } = render(<TabisActive={false}@@ -493,10 +404,8 @@ describe('Tab', () => {/>,)- // Assert initial stateexpect(screen.getByText('Original Label')).toBeInTheDocument()- // Rerender with changed proprerender(<TabisActive={false}@@ -507,17 +416,14 @@ describe('Tab', () => {/>,)- // Assert updated stateexpect(screen.getByText('Updated Label')).toBeInTheDocument()expect(screen.queryByText('Original Label')).not.toBeInTheDocument()})it('should use stable handleClick callback with useCallback', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actconst { rerender } = render(<TabisActive={false}@@ -531,7 +437,6 @@ describe('Tab', () => {fireEvent.click(screen.getByRole('button'))expect(mockOnClick).toHaveBeenCalledWith('TEST_VALUE')- // Rerender with same value and onClickrerender(<TabisActive={true}@@ -548,17 +453,12 @@ describe('Tab', () => {})})- // -------------------------------------------------------------------------- // Edge Cases Tests - Verify boundary conditions- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle special characters in label', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()const specialLabel = 'Tab <>&"\''- // Actrender(<TabisActive={false}@@ -569,16 +469,13 @@ describe('Tab', () => {/>,)- // Assertexpect(screen.getByText(specialLabel)).toBeInTheDocument()})it('should handle special characters in value', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -590,16 +487,13 @@ describe('Tab', () => {)fireEvent.click(screen.getByRole('button'))- // Assertexpect(mockOnClick).toHaveBeenCalledWith('SPECIAL_VALUE_123')})it('should handle unicode in label', () => {- // Arrangeconst mockOnClick = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabisActive={false}@@ -610,15 +504,12 @@ describe('Tab', () => {/>,)- // Assertexpect(screen.getByText('结果 🚀')).toBeInTheDocument()})it('should combine isActive and disabled states correctly', () => {- // Arrangeconst mockOnClick = vi.fn()- // Act - Active but disabled (no workflowRunningData)render(<TabisActive={true}@@ -629,7 +520,6 @@ describe('Tab', () => {/>,)- // Assertconst button = screen.getByRole('button')expect(button).toBeDisabled()expect(button).toHaveClass('border-util-colors-blue-brand-blue-brand-600')@@ -639,25 +529,16 @@ describe('Tab', () => {})})-// ============================================================================-// Tabs Component Tests-// ============================================================================-describe('Tabs', () => {beforeEach(() => {vi.clearAllMocks()})- // -------------------------------------------------------------------------- // Rendering Tests - Verify basic component rendering- // -------------------------------------------------------------------------describe('Rendering', () => {it('should render all three tabs', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -666,18 +547,15 @@ describe('Tabs', () => {/>,)- // Assert - Check all three tabs are rendered with i18n keysexpect(screen.getByRole('button', { name: 'runLog.result' })).toBeInTheDocument()expect(screen.getByRole('button', { name: 'runLog.detail' })).toBeInTheDocument()expect(screen.getByRole('button', { name: 'runLog.tracing' })).toBeInTheDocument()})it('should render container with correct styles', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actconst { container } = render(<TabscurrentTab="RESULT"@@ -686,7 +564,6 @@ describe('Tabs', () => {/>,)- // Assertconst tabsContainer = container.firstChildexpect(tabsContainer).toHaveClass('flex')expect(tabsContainer).toHaveClass('shrink-0')@@ -698,11 +575,9 @@ describe('Tabs', () => {})it('should render exactly three tab buttons', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -711,23 +586,17 @@ describe('Tabs', () => {/>,)- // Assertconst buttons = screen.getAllByRole('button')expect(buttons).toHaveLength(3)})})- // -------------------------------------------------------------------------- // Props Tests - Verify different prop combinations- // -------------------------------------------------------------------------describe('Props', () => {describe('currentTab prop', () => {it('should set RESULT tab as active when currentTab is RESULT', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -736,7 +605,6 @@ describe('Tabs', () => {/>,)- // Assertconst resultTab = screen.getByRole('button', { name: 'runLog.result' })const detailTab = screen.getByRole('button', { name: 'runLog.detail' })const tracingTab = screen.getByRole('button', { name: 'runLog.tracing' })@@ -747,11 +615,9 @@ describe('Tabs', () => {})it('should set DETAIL tab as active when currentTab is DETAIL', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="DETAIL"@@ -760,7 +626,6 @@ describe('Tabs', () => {/>,)- // Assertconst resultTab = screen.getByRole('button', { name: 'runLog.result' })const detailTab = screen.getByRole('button', { name: 'runLog.detail' })const tracingTab = screen.getByRole('button', { name: 'runLog.tracing' })@@ -771,11 +636,9 @@ describe('Tabs', () => {})it('should set TRACING tab as active when currentTab is TRACING', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="TRACING"@@ -784,7 +647,6 @@ describe('Tabs', () => {/>,)- // Assertconst resultTab = screen.getByRole('button', { name: 'runLog.result' })const detailTab = screen.getByRole('button', { name: 'runLog.detail' })const tracingTab = screen.getByRole('button', { name: 'runLog.tracing' })@@ -795,11 +657,9 @@ describe('Tabs', () => {})it('should handle unknown currentTab gracefully', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="UNKNOWN"@@ -808,7 +668,6 @@ describe('Tabs', () => {/>,)- // Assert - All tabs should be inactiveconst resultTab = screen.getByRole('button', { name: 'runLog.result' })const detailTab = screen.getByRole('button', { name: 'runLog.detail' })const tracingTab = screen.getByRole('button', { name: 'runLog.tracing' })@@ -821,11 +680,9 @@ describe('Tabs', () => {describe('workflowRunningData prop', () => {it('should enable all tabs when workflowRunningData is provided', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -834,7 +691,6 @@ describe('Tabs', () => {/>,)- // Assertconst buttons = screen.getAllByRole('button')buttons.forEach((button) => {expect(button).not.toBeDisabled()@@ -842,10 +698,8 @@ describe('Tabs', () => {})it('should disable all tabs when workflowRunningData is undefined', () => {- // Arrangeconst mockSwitchTab = vi.fn()- // Actrender(<TabscurrentTab="RESULT"@@ -854,7 +708,6 @@ describe('Tabs', () => {/>,)- // Assertconst buttons = screen.getAllByRole('button')buttons.forEach((button) => {expect(button).toBeDisabled()@@ -863,11 +716,9 @@ describe('Tabs', () => {})it('should pass workflowRunningData to all Tab components', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -876,7 +727,6 @@ describe('Tabs', () => {/>,)- // Assert - All tabs should be enabled (workflowRunningData passed)const buttons = screen.getAllByRole('button')buttons.forEach((button) => {expect(button).not.toHaveClass('opacity-30')@@ -886,11 +736,9 @@ describe('Tabs', () => {describe('switchTab prop', () => {it('should pass switchTab function to Tab onClick', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -900,22 +748,16 @@ describe('Tabs', () => {)fireEvent.click(screen.getByRole('button', { name: 'runLog.detail' }))- // Assertexpect(mockSwitchTab).toHaveBeenCalledWith('DETAIL')})})})- // -------------------------------------------------------------------------- // Event Handlers Tests - Verify click behavior- // -------------------------------------------------------------------------describe('Event Handlers', () => {it('should call switchTab with RESULT when RESULT tab is clicked', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="DETAIL"@@ -925,16 +767,13 @@ describe('Tabs', () => {)fireEvent.click(screen.getByRole('button', { name: 'runLog.result' }))- // Assertexpect(mockSwitchTab).toHaveBeenCalledWith('RESULT')})it('should call switchTab with DETAIL when DETAIL tab is clicked', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -944,16 +783,13 @@ describe('Tabs', () => {)fireEvent.click(screen.getByRole('button', { name: 'runLog.detail' }))- // Assertexpect(mockSwitchTab).toHaveBeenCalledWith('DETAIL')})it('should call switchTab with TRACING when TRACING tab is clicked', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -963,15 +799,12 @@ describe('Tabs', () => {)fireEvent.click(screen.getByRole('button', { name: 'runLog.tracing' }))- // Assertexpect(mockSwitchTab).toHaveBeenCalledWith('TRACING')})it('should not call switchTab when tabs are disabled', () => {- // Arrangeconst mockSwitchTab = vi.fn()- // Actrender(<TabscurrentTab="RESULT"@@ -985,16 +818,13 @@ describe('Tabs', () => {fireEvent.click(button)})- // Assertexpect(mockSwitchTab).not.toHaveBeenCalled()})it('should allow clicking the currently active tab', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -1004,17 +834,12 @@ describe('Tabs', () => {)fireEvent.click(screen.getByRole('button', { name: 'runLog.result' }))- // Assertexpect(mockSwitchTab).toHaveBeenCalledWith('RESULT')})})- // -------------------------------------------------------------------------- // Memoization Tests - Verify React.memo optimization- // -------------------------------------------------------------------------describe('Memoization', () => {it('should not re-render when props are the same', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()const renderSpy = vi.fn()@@ -1025,7 +850,6 @@ describe('Tabs', () => {}const MemoizedTabsWithSpy = React.memo(TabsWithSpy)- // Actconst { rerender } = render(<MemoizedTabsWithSpycurrentTab="RESULT"@@ -1034,7 +858,6 @@ describe('Tabs', () => {/>,)- // Re-render with same propsrerender(<MemoizedTabsWithSpycurrentTab="RESULT"@@ -1043,16 +866,13 @@ describe('Tabs', () => {/>,)- // Assert - React.memo should prevent re-render with same propsexpect(renderSpy).toHaveBeenCalledTimes(1)})it('should re-render when currentTab changes', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actconst { rerender } = render(<TabscurrentTab="RESULT"@@ -1061,10 +881,8 @@ describe('Tabs', () => {/>,)- // Assert initial stateexpect(screen.getByRole('button', { name: 'runLog.result' })).toHaveClass('text-text-primary')- // Rerender with changed proprerender(<TabscurrentTab="DETAIL"@@ -1073,17 +891,14 @@ describe('Tabs', () => {/>,)- // Assert updated stateexpect(screen.getByRole('button', { name: 'runLog.result' })).toHaveClass('text-text-tertiary')expect(screen.getByRole('button', { name: 'runLog.detail' })).toHaveClass('text-text-primary')})it('should re-render when workflowRunningData changes from undefined to defined', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actconst { rerender } = render(<TabscurrentTab="RESULT"@@ -1092,13 +907,11 @@ describe('Tabs', () => {/>,)- // Assert initial disabled stateconst buttons = screen.getAllByRole('button')buttons.forEach((button) => {expect(button).toBeDisabled()})- // Rerender with workflowRunningDatarerender(<TabscurrentTab="RESULT"@@ -1107,7 +920,6 @@ describe('Tabs', () => {/>,)- // Assert enabled stateconst updatedButtons = screen.getAllByRole('button')updatedButtons.forEach((button) => {expect(button).not.toBeDisabled()@@ -1115,16 +927,11 @@ describe('Tabs', () => {})})- // -------------------------------------------------------------------------- // Edge Cases Tests - Verify boundary conditions- // -------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle empty string currentTab', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab=""@@ -1133,7 +940,6 @@ describe('Tabs', () => {/>,)- // Assert - All tabs should be inactiveconst buttons = screen.getAllByRole('button')buttons.forEach((button) => {expect(button).toHaveClass('text-text-tertiary')@@ -1141,11 +947,9 @@ describe('Tabs', () => {})it('should handle case-sensitive tab values', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Act - lowercase "result" should not match "RESULT"render(<TabscurrentTab="result"@@ -1154,16 +958,13 @@ describe('Tabs', () => {/>,)- // Assert - Result tab should not be active (case mismatch)expect(screen.getByRole('button', { name: 'runLog.result' })).toHaveClass('text-text-tertiary')})it('should handle whitespace in currentTab', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab=" RESULT "@@ -1172,12 +973,10 @@ describe('Tabs', () => {/>,)- // Assert - Should not match due to whitespaceexpect(screen.getByRole('button', { name: 'runLog.result' })).toHaveClass('text-text-tertiary')})it('should render correctly with minimal workflowRunningData', () => {- // Arrangeconst mockSwitchTab = vi.fn()const minimalWorkflowData: WorkflowRunningData = {result: {@@ -1188,7 +987,6 @@ describe('Tabs', () => {},}- // Actrender(<TabscurrentTab="RESULT"@@ -1197,7 +995,6 @@ describe('Tabs', () => {/>,)- // Assertconst buttons = screen.getAllByRole('button')buttons.forEach((button) => {expect(button).not.toBeDisabled()@@ -1205,11 +1002,9 @@ describe('Tabs', () => {})it('should maintain tab order (RESULT, DETAIL, TRACING)', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="RESULT"@@ -1218,7 +1013,6 @@ describe('Tabs', () => {/>,)- // Assertconst buttons = screen.getAllByRole('button')expect(buttons[0]).toHaveTextContent('runLog.result')expect(buttons[1]).toHaveTextContent('runLog.detail')@@ -1226,16 +1020,11 @@ describe('Tabs', () => {})})- // -------------------------------------------------------------------------- // Integration Tests - Verify Tab and Tabs work together- // -------------------------------------------------------------------------describe('Integration', () => {it('should correctly pass all props to child Tab components', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Actrender(<TabscurrentTab="DETAIL"@@ -1244,22 +1033,18 @@ describe('Tabs', () => {/>,)- // Assert - Verify each tab has correct propsconst resultTab = screen.getByRole('button', { name: 'runLog.result' })const detailTab = screen.getByRole('button', { name: 'runLog.detail' })const tracingTab = screen.getByRole('button', { name: 'runLog.tracing' })- // Check active statesexpect(resultTab).toHaveClass('text-text-tertiary')expect(detailTab).toHaveClass('text-text-primary')expect(tracingTab).toHaveClass('text-text-tertiary')- // Check enabled statesexpect(resultTab).not.toBeDisabled()expect(detailTab).not.toBeDisabled()expect(tracingTab).not.toBeDisabled()- // Check click handlersfireEvent.click(resultTab)expect(mockSwitchTab).toHaveBeenCalledWith('RESULT')@@ -1268,12 +1053,10 @@ describe('Tabs', () => {})it('should support full tab switching workflow', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()let currentTab = 'RESULT'- // Actconst { rerender } = render(<TabscurrentTab={currentTab}@@ -1282,11 +1065,9 @@ describe('Tabs', () => {/>,)- // Simulate clicking DETAIL tabfireEvent.click(screen.getByRole('button', { name: 'runLog.detail' }))expect(mockSwitchTab).toHaveBeenCalledWith('DETAIL')- // Update currentTab and rerender (simulating parent state update)currentTab = 'DETAIL'rerender(<Tabs@@ -1296,14 +1077,11 @@ describe('Tabs', () => {/>,)- // Assert DETAIL is now activeexpect(screen.getByRole('button', { name: 'runLog.detail' })).toHaveClass('text-text-primary')- // Simulate clicking TRACING tabfireEvent.click(screen.getByRole('button', { name: 'runLog.tracing' }))expect(mockSwitchTab).toHaveBeenCalledWith('TRACING')- // Update currentTab and rerendercurrentTab = 'TRACING'rerender(<Tabs@@ -1313,16 +1091,13 @@ describe('Tabs', () => {/>,)- // Assert TRACING is now activeexpect(screen.getByRole('button', { name: 'runLog.tracing' })).toHaveClass('text-text-primary')})it('should transition from disabled to enabled state', () => {- // Arrangeconst mockSwitchTab = vi.fn()const workflowData = createWorkflowRunningData()- // Act - Initial disabled stateconst { rerender } = render(<TabscurrentTab="RESULT"@@ -1331,11 +1106,9 @@ describe('Tabs', () => {/>,)- // Try clicking - should not triggerfireEvent.click(screen.getByRole('button', { name: 'runLog.detail' }))expect(mockSwitchTab).not.toHaveBeenCalled()- // Enable tabsrerender(<TabscurrentTab="RESULT"@@ -1344,7 +1117,6 @@ describe('Tabs', () => {/>,)- // Now click should workfireEvent.click(screen.getByRole('button', { name: 'runLog.detail' }))expect(mockSwitchTab).toHaveBeenCalledWith('DETAIL')})diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsxsimilarity index 84%rename from web/app/components/rag-pipeline/components/rag-pipeline-header/index.spec.tsxrename to web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsxindex 4f3465a9205..0b858eaaa77 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsx@@ -3,21 +3,12 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { createMockProviderContextValue } from '@/__mocks__/provider-context'import { WorkflowRunningStatus } from '@/app/components/workflow/types'-// ============================================================================-// Import Components After Mocks-// ============================================================================+import RagPipelineHeader from '../index'+import InputFieldButton from '../input-field-button'+import Publisher from '../publisher'+import Popup from '../publisher/popup'+import RunMode from '../run-mode'-import RagPipelineHeader from './index'-import InputFieldButton from './input-field-button'-import Publisher from './publisher'-import Popup from './publisher/popup'-import RunMode from './run-mode'--// ============================================================================-// Mock External Dependencies-// ============================================================================--// Mock workflow storeconst mockSetShowInputFieldPanel = vi.fn()const mockSetShowEnvPanel = vi.fn()const mockSetIsPreparingDataSource = vi.fn()@@ -51,7 +42,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock workflow hooksconst mockHandleSyncWorkflowDraft = vi.fn()const mockHandleCheckBeforePublish = vi.fn().mockResolvedValue(true)const mockHandleStopRun = vi.fn()@@ -72,7 +62,6 @@ vi.mock('@/app/components/workflow/hooks', () => ({}),}))-// Mock Header componentvi.mock('@/app/components/workflow/header', () => ({default: ({ normal, viewHistory }: {normal?: { components?: { left?: ReactNode, middle?: ReactNode }, runAndHistoryProps?: unknown }@@ -87,21 +76,18 @@ vi.mock('@/app/components/workflow/header', () => ({),}))-// Mock next/navigationconst mockPush = vi.fn()vi.mock('next/navigation', () => ({useParams: () => ({ datasetId: 'test-dataset-id' }),useRouter: () => ({ push: mockPush }),}))-// Mock next/linkvi.mock('next/link', () => ({default: ({ children, href, ...props }: PropsWithChildren<{ href: string }>) => (<a href={href} {...props}>{children}</a>),}))-// Mock service hooksconst mockPublishWorkflow = vi.fn().mockResolvedValue({ created_at: Date.now() })const mockPublishAsCustomizedPipeline = vi.fn().mockResolvedValue({})@@ -127,7 +113,6 @@ vi.mock('@/service/knowledge/use-dataset', () => ({useInvalidDatasetList: () => vi.fn(),}))-// Mock context hooksconst mockMutateDatasetRes = vi.fn()vi.mock('@/context/dataset-detail', () => ({useDatasetDetailContextWithSelector: () => mockMutateDatasetRes,@@ -145,7 +130,6 @@ vi.mock('@/context/provider-context', () => ({selector(mockProviderContextValue),}))-// Mock event emitter contextconst mockEventEmitter = {useSubscription: vi.fn(),}@@ -156,7 +140,6 @@ vi.mock('@/context/event-emitter', () => ({}),}))-// Mock hooksvi.mock('@/hooks/use-api-access-url', () => ({useDatasetApiAccessUrl: () => '/api/docs',}))@@ -167,12 +150,10 @@ vi.mock('@/hooks/use-format-time-from-now', () => ({}),}))-// Mock amplitude trackingvi.mock('@/app/components/base/amplitude', () => ({trackEvent: vi.fn(),}))-// Mock toast contextconst mockNotify = vi.fn()vi.mock('@/app/components/base/toast', () => ({useToastContext: () => ({@@ -180,13 +161,11 @@ vi.mock('@/app/components/base/toast', () => ({}),}))-// Mock workflow utilsvi.mock('@/app/components/workflow/utils', () => ({getKeyboardKeyCodeBySystem: (key: string) => key,getKeyboardKeyNameBySystem: (key: string) => key,}))-// Mock ahooksvi.mock('ahooks', () => ({useBoolean: (initial: boolean) => {let value = initial@@ -202,7 +181,6 @@ vi.mock('ahooks', () => ({useKeyPress: vi.fn(),}))-// Mock portal components - keep actual behavior for open statelet portalOpenState = falsevi.mock('@/app/components/base/portal-to-follow-elem', () => ({PortalToFollowElem: ({ children, open, onOpenChange: _onOpenChange }: PropsWithChildren<{@@ -224,8 +202,7 @@ vi.mock('@/app/components/base/portal-to-follow-elem', () => ({},}))-// Mock PublishAsKnowledgePipelineModal-vi.mock('../../publish-as-knowledge-pipeline-modal', () => ({+vi.mock('../../../publish-as-knowledge-pipeline-modal', () => ({default: ({ onConfirm, onCancel }: {onConfirm: (name: string, icon: unknown, description?: string) => voidonCancel: () => void@@ -238,10 +215,6 @@ vi.mock('../../publish-as-knowledge-pipeline-modal', () => ({),}))-// ============================================================================-// Test Suites-// ============================================================================-describe('RagPipelineHeader', () => {beforeEach(() => {vi.clearAllMocks()@@ -259,9 +232,6 @@ describe('RagPipelineHeader', () => {mockProviderContextValue = createMockProviderContextValue()})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render without crashing', () => {render(<RagPipelineHeader />)@@ -286,19 +256,14 @@ describe('RagPipelineHeader', () => {})})- // --------------------------------------------------------------------------- // Memoization Tests- // --------------------------------------------------------------------------describe('Memoization', () => {it('should compute viewHistoryProps based on pipelineId', () => {- // Test with first pipelineIdmockStoreState.pipelineId = 'pipeline-alpha'const { unmount } = render(<RagPipelineHeader />)let viewHistoryContent = screen.getByTestId('header-view-history').textContentexpect(viewHistoryContent).toContain('pipeline-alpha')unmount()- // Test with different pipelineIdmockStoreState.pipelineId = 'pipeline-beta'render(<RagPipelineHeader />)viewHistoryContent = screen.getByTestId('header-view-history').textContent@@ -320,9 +285,6 @@ describe('InputFieldButton', () => {mockStoreState.setShowEnvPanel = mockSetShowEnvPanel})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render button with correct text', () => {render(<InputFieldButton />)@@ -337,9 +299,6 @@ describe('InputFieldButton', () => {})})- // --------------------------------------------------------------------------- // Event Handler Tests- // --------------------------------------------------------------------------describe('Event Handlers', () => {it('should call setShowInputFieldPanel(true) when clicked', () => {render(<InputFieldButton />)@@ -367,16 +326,12 @@ describe('InputFieldButton', () => {})})- // --------------------------------------------------------------------------- // Edge Cases- // --------------------------------------------------------------------------describe('Edge Cases', () => {it('should handle undefined setShowInputFieldPanel gracefully', () => {mockStoreState.setShowInputFieldPanel = undefined as unknown as typeof mockSetShowInputFieldPanelrender(<InputFieldButton />)- // Should not throw when clickedexpect(() => fireEvent.click(screen.getByRole('button'))).not.toThrow()})})@@ -388,9 +343,6 @@ describe('Publisher', () => {portalOpenState = false})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render publish button', () => {render(<Publisher />)@@ -410,9 +362,6 @@ describe('Publisher', () => {})})- // --------------------------------------------------------------------------- // Interaction Tests- // --------------------------------------------------------------------------describe('Interactions', () => {it('should call handleSyncWorkflowDraft when opening', () => {render(<Publisher />)@@ -430,7 +379,6 @@ describe('Publisher', () => {fireEvent.click(screen.getByTestId('portal-trigger'))- // After click, handleOpenChange should be calledexpect(mockHandleSyncWorkflowDraft).toHaveBeenCalled()})})@@ -447,9 +395,6 @@ describe('Popup', () => {})})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render popup container', () => {render(<Popup />)@@ -475,7 +420,6 @@ describe('Popup', () => {it('should render keyboard shortcuts', () => {render(<Popup />)- // Should show the keyboard shortcut keysexpect(screen.getByText('ctrl')).toBeInTheDocument()expect(screen.getByText('⇧')).toBeInTheDocument()expect(screen.getByText('P')).toBeInTheDocument()@@ -500,9 +444,6 @@ describe('Popup', () => {})})- // --------------------------------------------------------------------------- // Button State Tests- // --------------------------------------------------------------------------describe('Button States', () => {it('should disable goToAddDocuments when not published', () => {mockStoreState.publishedAt = 0@@ -532,9 +473,6 @@ describe('Popup', () => {})})- // --------------------------------------------------------------------------- // Premium Badge Tests- // --------------------------------------------------------------------------describe('Premium Badge', () => {it('should show premium badge when not allowed to publish as template', () => {mockProviderContextValue = createMockProviderContextValue({@@ -557,9 +495,6 @@ describe('Popup', () => {})})- // --------------------------------------------------------------------------- // Interaction Tests- // --------------------------------------------------------------------------describe('Interactions', () => {it('should call handleCheckBeforePublish when publish button clicked', async () => {render(<Popup />)@@ -598,9 +533,6 @@ describe('Popup', () => {})})- // --------------------------------------------------------------------------- // Auto-save Display Tests- // --------------------------------------------------------------------------describe('Auto-save Display', () => {it('should show auto-saved time when not published', () => {mockStoreState.publishedAt = 0@@ -629,9 +561,6 @@ describe('RunMode', () => {mockEventEmitterEnabled = true})- // --------------------------------------------------------------------------- // Rendering Tests- // --------------------------------------------------------------------------describe('Rendering', () => {it('should render run button with default text', () => {render(<RunMode />)@@ -654,9 +583,6 @@ describe('RunMode', () => {})})- // --------------------------------------------------------------------------- // Running State Tests- // --------------------------------------------------------------------------describe('Running States', () => {it('should show processing state when running', () => {mockStoreState.workflowRunningData = {@@ -677,7 +603,6 @@ describe('RunMode', () => {render(<RunMode />)- // There should be two buttons: run button and stop buttonconst buttons = screen.getAllByRole('button')expect(buttons.length).toBe(2)})@@ -751,7 +676,6 @@ describe('RunMode', () => {render(<RunMode />)- // Should only have one button (run button)const buttons = screen.getAllByRole('button')expect(buttons.length).toBe(1)})@@ -781,9 +705,6 @@ describe('RunMode', () => {})})- // --------------------------------------------------------------------------- // Disabled State Tests- // --------------------------------------------------------------------------describe('Disabled States', () => {it('should be disabled when running', () => {mockStoreState.workflowRunningData = {@@ -818,9 +739,6 @@ describe('RunMode', () => {})})- // --------------------------------------------------------------------------- // Interaction Tests- // --------------------------------------------------------------------------describe('Interactions', () => {it('should call handleWorkflowStartRunInWorkflow when clicked', () => {render(<RunMode />)@@ -838,7 +756,6 @@ describe('RunMode', () => {render(<RunMode />)- // Click the stop button (second button)const buttons = screen.getAllByRole('button')fireEvent.click(buttons[1])@@ -850,7 +767,6 @@ describe('RunMode', () => {render(<RunMode />)- // Click the cancel button (second button)const buttons = screen.getAllByRole('button')fireEvent.click(buttons[1])@@ -883,14 +799,10 @@ describe('RunMode', () => {const runButton = screen.getAllByRole('button')[0]fireEvent.click(runButton)- // Should not be called because button is disabledexpect(mockHandleWorkflowStartRunInWorkflow).not.toHaveBeenCalled()})})- // --------------------------------------------------------------------------- // Event Emitter Tests- // --------------------------------------------------------------------------describe('Event Emitter', () => {it('should subscribe to event emitter', () => {render(<RunMode />)@@ -904,7 +816,6 @@ describe('RunMode', () => {result: { status: WorkflowRunningStatus.Running },}- // Capture the subscription callbacklet subscriptionCallback: ((v: { type: string }) => void) | null = nullmockEventEmitter.useSubscription.mockImplementation((callback: (v: { type: string }) => void) => {subscriptionCallback = callback@@ -912,7 +823,6 @@ describe('RunMode', () => {render(<RunMode />)- // Simulate the EVENT_WORKFLOW_STOP event (actual value is 'WORKFLOW_STOP')expect(subscriptionCallback).not.toBeNull()subscriptionCallback!({ type: 'WORKFLOW_STOP' })@@ -932,7 +842,6 @@ describe('RunMode', () => {render(<RunMode />)- // Simulate a different event typesubscriptionCallback!({ type: 'some_other_event' })expect(mockHandleStopRun).not.toHaveBeenCalled()@@ -941,7 +850,6 @@ describe('RunMode', () => {it('should handle undefined eventEmitter gracefully', () => {mockEventEmitterEnabled = false- // Should not throw when eventEmitter is undefinedexpect(() => render(<RunMode />)).not.toThrow()})@@ -951,14 +859,10 @@ describe('RunMode', () => {render(<RunMode />)- // useSubscription should not be calledexpect(mockEventEmitter.useSubscription).not.toHaveBeenCalled()})})- // --------------------------------------------------------------------------- // Style Tests- // --------------------------------------------------------------------------describe('Styles', () => {it('should have rounded-md class when not disabled', () => {render(<RunMode />)@@ -1053,21 +957,13 @@ describe('RunMode', () => {})})- // --------------------------------------------------------------------------- // Memoization Tests- // --------------------------------------------------------------------------describe('Memoization', () => {it('should be wrapped in React.memo', () => {- // RunMode is exported as default from run-mode.tsx with React.memo- // We can verify it's memoized by checking the component's $$typeof symbolexpect((RunMode as unknown as { $$typeof: symbol }).$$typeof).toBe(Symbol.for('react.memo'))})})})-// ============================================================================-// Integration Tests-// ============================================================================describe('Integration', () => {beforeEach(() => {vi.clearAllMocks()@@ -1087,10 +983,8 @@ describe('Integration', () => {it('should render all child components in RagPipelineHeader', () => {render(<RagPipelineHeader />)- // InputFieldButtonexpect(screen.getByText(/inputField/i)).toBeInTheDocument()- // Publisher (via header-middle slot)expect(screen.getByTestId('header-middle')).toBeInTheDocument()})@@ -1104,9 +998,6 @@ describe('Integration', () => {})})-// ============================================================================-// Edge Cases-// ============================================================================describe('Edge Cases', () => {beforeEach(() => {vi.clearAllMocks()@@ -1136,20 +1027,17 @@ describe('Edge Cases', () => {result: undefined as unknown as { status: WorkflowRunningStatus },}- // Component will crash when accessing result.status - this documents current behaviorexpect(() => render(<RunMode />)).toThrow()})})describe('RunMode Edge Cases', () => {beforeEach(() => {- // Ensure clean state for each testmockStoreState.workflowRunningData = nullmockStoreState.isPreparingDataSource = false})it('should handle both isPreparingDataSource and isRunning being true', () => {- // This shouldn't happen in practice, but test the prioritymockStoreState.isPreparingDataSource = truemockStoreState.workflowRunningData = {task_id: 'task-123',@@ -1158,7 +1046,6 @@ describe('Edge Cases', () => {render(<RunMode />)- // Button should be disabledconst runButton = screen.getAllByRole('button')[0]expect(runButton).toBeDisabled()})@@ -1169,7 +1056,6 @@ describe('Edge Cases', () => {render(<RunMode />)- // Verify the button is enabled and shows testRun textconst button = screen.getByRole('button')expect(button).not.toBeDisabled()expect(button.textContent).toContain('pipeline.common.testRun')@@ -1193,7 +1079,6 @@ describe('Edge Cases', () => {render(<RunMode text="Start Pipeline" />)- // Should show reRun, not custom textconst button = screen.getByRole('button')expect(button.textContent).toContain('pipeline.common.reRun')expect(screen.queryByText('Start Pipeline')).not.toBeInTheDocument()@@ -1205,7 +1090,6 @@ describe('Edge Cases', () => {render(<RunMode />)- // Verify keyboard shortcut elements existexpect(screen.getByText('alt')).toBeInTheDocument()expect(screen.getByText('R')).toBeInTheDocument()})@@ -1216,7 +1100,6 @@ describe('Edge Cases', () => {render(<RunMode />)- // Should have svg icon in the buttonconst button = screen.getByRole('button')expect(button.querySelector('svg')).toBeInTheDocument()})@@ -1229,7 +1112,6 @@ describe('Edge Cases', () => {render(<RunMode />)- // Should have animate-spin class on the loader iconconst runButton = screen.getAllByRole('button')[0]const spinningIcon = runButton.querySelector('.animate-spin')expect(spinningIcon).toBeInTheDocument()@@ -1252,7 +1134,6 @@ describe('Edge Cases', () => {render(<Popup />)- // Should render without crashingexpect(screen.getByText(/workflow.common.autoSaved/i)).toBeInTheDocument()})diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsxnew file mode 100644index 00000000000..9ac47aae02f--- /dev/null+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx@@ -0,0 +1,192 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import RunMode from '../run-mode'++const mockHandleWorkflowStartRunInWorkflow = vi.fn()+const mockHandleStopRun = vi.fn()+const mockSetIsPreparingDataSource = vi.fn()+const mockSetShowDebugAndPreviewPanel = vi.fn()++let mockWorkflowRunningData: { task_id: string, result: { status: string } } | undefined+let mockIsPreparingDataSource = false+vi.mock('@/app/components/workflow/hooks', () => ({+ useWorkflowRun: () => ({+ handleStopRun: mockHandleStopRun,+ }),+ useWorkflowStartRun: () => ({+ handleWorkflowStartRunInWorkflow: mockHandleWorkflowStartRunInWorkflow,+ }),+}))++vi.mock('@/app/components/workflow/shortcuts-name', () => ({+ default: ({ keys }: { keys: string[] }) => <span data-testid="shortcuts">{keys.join('+')}</span>,+}))++vi.mock('@/app/components/workflow/store', () => ({+ useStore: (selector: (state: Record<string, unknown>) => unknown) => {+ const state = {+ workflowRunningData: mockWorkflowRunningData,+ isPreparingDataSource: mockIsPreparingDataSource,+ }+ return selector(state)+ },+ useWorkflowStore: () => ({+ getState: () => ({+ setIsPreparingDataSource: mockSetIsPreparingDataSource,+ setShowDebugAndPreviewPanel: mockSetShowDebugAndPreviewPanel,+ }),+ }),+}))++vi.mock('@/app/components/workflow/types', () => ({+ WorkflowRunningStatus: { Running: 'running' },+}))++vi.mock('@/app/components/workflow/variable-inspect/types', () => ({+ EVENT_WORKFLOW_STOP: 'EVENT_WORKFLOW_STOP',+}))++vi.mock('@/context/event-emitter', () => ({+ useEventEmitterContextContext: () => ({+ eventEmitter: { useSubscription: vi.fn() },+ }),+}))++vi.mock('@/utils/classnames', () => ({+ cn: (...args: unknown[]) => args.filter(a => typeof a === 'string').join(' '),+}))++vi.mock('@remixicon/react', () => ({+ RiCloseLine: () => <span data-testid="close-icon" />,+ RiDatabase2Line: () => <span data-testid="database-icon" />,+ RiLoader2Line: () => <span data-testid="loader-icon" />,+ RiPlayLargeLine: () => <span data-testid="play-icon" />,+}))++vi.mock('@/app/components/base/icons/src/vender/line/mediaAndDevices', () => ({+ StopCircle: () => <span data-testid="stop-icon" />,+}))++describe('RunMode', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockWorkflowRunningData = undefined+ mockIsPreparingDataSource = false+ })++ describe('Idle state', () => {+ it('should render test run text when no data', () => {+ render(<RunMode />)++ expect(screen.getByText('pipeline.common.testRun')).toBeInTheDocument()+ })++ it('should render custom text when provided', () => {+ render(<RunMode text="Custom Run" />)++ expect(screen.getByText('Custom Run')).toBeInTheDocument()+ })++ it('should render play icon', () => {+ render(<RunMode />)++ expect(screen.getByTestId('play-icon')).toBeInTheDocument()+ })++ it('should render keyboard shortcuts', () => {+ render(<RunMode />)++ expect(screen.getByTestId('shortcuts')).toBeInTheDocument()+ })++ it('should call start run when button clicked', () => {+ render(<RunMode />)++ fireEvent.click(screen.getByText('pipeline.common.testRun'))++ expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalled()+ })+ })++ describe('Running state', () => {+ beforeEach(() => {+ mockWorkflowRunningData = {+ task_id: 'task-1',+ result: { status: 'running' },+ }+ })++ it('should show processing text', () => {+ render(<RunMode />)++ expect(screen.getByText('pipeline.common.processing')).toBeInTheDocument()+ })++ it('should show stop button', () => {+ render(<RunMode />)++ expect(screen.getByTestId('stop-icon')).toBeInTheDocument()+ })++ it('should disable run button', () => {+ render(<RunMode />)++ const button = screen.getByText('pipeline.common.processing').closest('button')+ expect(button).toBeDisabled()+ })++ it('should call handleStopRun with task_id when stop clicked', () => {+ render(<RunMode />)++ fireEvent.click(screen.getByTestId('stop-icon').closest('button')!)++ expect(mockHandleStopRun).toHaveBeenCalledWith('task-1')+ })+ })++ describe('After run completed', () => {+ it('should show reRun text when previous run data exists', () => {+ mockWorkflowRunningData = {+ task_id: 'task-1',+ result: { status: 'succeeded' },+ }+ render(<RunMode />)++ expect(screen.getByText('pipeline.common.reRun')).toBeInTheDocument()+ })+ })++ describe('Preparing data source state', () => {+ beforeEach(() => {+ mockIsPreparingDataSource = true+ })++ it('should show preparing text', () => {+ render(<RunMode />)++ expect(screen.getByText('pipeline.common.preparingDataSource')).toBeInTheDocument()+ })++ it('should show database icon', () => {+ render(<RunMode />)++ expect(screen.getByTestId('database-icon')).toBeInTheDocument()+ })++ it('should show cancel button with close icon', () => {+ render(<RunMode />)++ expect(screen.getByTestId('close-icon')).toBeInTheDocument()+ })++ it('should cancel preparing when close clicked', () => {+ render(<RunMode />)++ fireEvent.click(screen.getByTestId('close-icon').closest('button')!)++ expect(mockSetIsPreparingDataSource).toHaveBeenCalledWith(false)+ expect(mockSetShowDebugAndPreviewPanel).toHaveBeenCalledWith(false)+ })+ })+})diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsxsimilarity index 81%rename from web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.spec.tsxrename to web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsxindex 2a01218ee65..0fc3bda7b3b 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx@@ -3,29 +3,21 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import Publisher from './index'-import Popup from './popup'+import Publisher from '../index'+import Popup from '../popup'-// ================================-// Mock External Dependencies Only-// ================================--// Mock next/navigationconst mockPush = vi.fn()vi.mock('next/navigation', () => ({useParams: () => ({ datasetId: 'test-dataset-id' }),useRouter: () => ({ push: mockPush }),}))-// Mock next/linkvi.mock('next/link', () => ({default: ({ children, href, ...props }: { children: React.ReactNode, href: string }) => (<a href={href} {...props}>{children}</a>),}))-// Mock ahooks-// Store the keyboard shortcut callback for testinglet keyPressCallback: ((e: KeyboardEvent) => void) | null = nullvi.mock('ahooks', () => ({useBoolean: (defaultValue = false) => {@@ -37,17 +29,14 @@ vi.mock('ahooks', () => ({}]},useKeyPress: (key: string, callback: (e: KeyboardEvent) => void) => {- // Store the callback so we can invoke it in testskeyPressCallback = callback},}))-// Mock amplitude trackingvi.mock('@/app/components/base/amplitude', () => ({trackEvent: vi.fn(),}))-// Mock portal-to-follow-elemlet mockPortalOpen = falsevi.mock('@/app/components/base/portal-to-follow-elem', () => ({PortalToFollowElem: ({ children, open, onOpenChange: _onOpenChange }: {@@ -76,7 +65,6 @@ vi.mock('@/app/components/base/portal-to-follow-elem', () => ({},}))-// Mock workflow hooksconst mockHandleSyncWorkflowDraft = vi.fn()const mockHandleCheckBeforePublish = vi.fn().mockResolvedValue(true)vi.mock('@/app/components/workflow/hooks', () => ({@@ -88,7 +76,6 @@ vi.mock('@/app/components/workflow/hooks', () => ({}),}))-// Mock workflow storeconst mockPublishedAt = vi.fn(() => null as number | null)const mockDraftUpdatedAt = vi.fn(() => 1700000000)const mockPipelineId = vi.fn(() => 'test-pipeline-id')@@ -110,7 +97,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock dataset-detail contextconst mockMutateDatasetRes = vi.fn()vi.mock('@/context/dataset-detail', () => ({useDatasetDetailContextWithSelector: (selector: (s: Record<string, unknown>) => unknown) => {@@ -119,13 +105,11 @@ vi.mock('@/context/dataset-detail', () => ({},}))-// Mock modal-contextconst mockSetShowPricingModal = vi.fn()vi.mock('@/context/modal-context', () => ({useModalContextSelector: () => mockSetShowPricingModal,}))-// Mock provider-contextconst mockIsAllowPublishAsCustomKnowledgePipelineTemplate = vi.fn(() => true)vi.mock('@/context/provider-context', () => ({useProviderContext: () => ({@@ -135,7 +119,6 @@ vi.mock('@/context/provider-context', () => ({selector({ isAllowPublishAsCustomKnowledgePipelineTemplate: mockIsAllowPublishAsCustomKnowledgePipelineTemplate() }),}))-// Mock toast contextconst mockNotify = vi.fn()vi.mock('@/app/components/base/toast', () => ({useToastContext: () => ({@@ -143,12 +126,10 @@ vi.mock('@/app/components/base/toast', () => ({}),}))-// Mock API access URL hookvi.mock('@/hooks/use-api-access-url', () => ({useDatasetApiAccessUrl: () => 'https://api.dify.ai/v1/datasets/test-dataset-id',}))-// Mock format time hookvi.mock('@/hooks/use-format-time-from-now', () => ({useFormatTimeFromNow: () => ({formatTimeFromNow: (timestamp: number) => {@@ -162,7 +143,6 @@ vi.mock('@/hooks/use-format-time-from-now', () => ({}),}))-// Mock service hooksconst mockPublishWorkflow = vi.fn()const mockPublishAsCustomizedPipeline = vi.fn()const mockInvalidPublishedPipelineInfo = vi.fn()@@ -191,14 +171,12 @@ vi.mock('@/service/use-workflow', () => ({}),}))-// Mock workflow utilsvi.mock('@/app/components/workflow/utils', () => ({getKeyboardKeyCodeBySystem: (key: string) => key,getKeyboardKeyNameBySystem: (key: string) => key === 'ctrl' ? '⌘' : key,}))-// Mock PublishAsKnowledgePipelineModal-vi.mock('../../publish-as-knowledge-pipeline-modal', () => ({+vi.mock('../../../publish-as-knowledge-pipeline-modal', () => ({default: ({ confirmDisabled, onConfirm, onCancel }: {confirmDisabled: booleanonConfirm: (name: string, icon: IconInfo, description?: string) => void@@ -217,10 +195,6 @@ vi.mock('../../publish-as-knowledge-pipeline-modal', () => ({),}))-// ================================-// Test Data Factories-// ================================-const createQueryClient = () => new QueryClient({defaultOptions: {queries: {@@ -238,16 +212,11 @@ const renderWithQueryClient = (ui: React.ReactElement) => {)}-// ================================-// Test Suites-// ================================-describe('publisher', () => {beforeEach(() => {vi.clearAllMocks()mockPortalOpen = falsekeyPressCallback = null- // Reset mock return values to defaultsmockPublishedAt.mockReturnValue(null)mockDraftUpdatedAt.mockReturnValue(1700000000)mockPipelineId.mockReturnValue('test-pipeline-id')@@ -255,127 +224,90 @@ describe('publisher', () => {mockHandleCheckBeforePublish.mockResolvedValue(true)})- // ============================================================- // Publisher (index.tsx) - Main Entry Component Tests- // ============================================================describe('Publisher (index.tsx)', () => {- // --------------------------------- // Rendering Tests- // --------------------------------describe('Rendering', () => {it('should render publish button with correct text', () => {- // Arrange & ActrenderWithQueryClient(<Publisher />)- // Assertexpect(screen.getByRole('button')).toBeInTheDocument()expect(screen.getByText('workflow.common.publish')).toBeInTheDocument()})it('should render portal element in closed state by default', () => {- // Arrange & ActrenderWithQueryClient(<Publisher />)- // Assertexpect(screen.getByTestId('portal-elem')).toHaveAttribute('data-open', 'false')expect(screen.queryByTestId('portal-content')).not.toBeInTheDocument()})it('should render down arrow icon in button', () => {- // Arrange & ActrenderWithQueryClient(<Publisher />)- // Assertconst button = screen.getByRole('button')expect(button.querySelector('svg')).toBeInTheDocument()})})- // --------------------------------- // State Management Tests- // --------------------------------describe('State Management', () => {it('should open popup when trigger is clicked', async () => {- // ArrangerenderWithQueryClient(<Publisher />)- // ActfireEvent.click(screen.getByTestId('portal-trigger'))- // Assertawait waitFor(() => {expect(screen.getByTestId('portal-content')).toBeInTheDocument()})})it('should close popup when trigger is clicked again while open', async () => {- // ArrangerenderWithQueryClient(<Publisher />)fireEvent.click(screen.getByTestId('portal-trigger')) // open- // Actawait waitFor(() => {expect(screen.getByTestId('portal-content')).toBeInTheDocument()})fireEvent.click(screen.getByTestId('portal-trigger')) // close- // Assertawait waitFor(() => {expect(screen.queryByTestId('portal-content')).not.toBeInTheDocument()})})})- // --------------------------------- // Callback Stability and Memoization Tests- // --------------------------------describe('Callback Stability and Memoization', () => {it('should call handleSyncWorkflowDraft when popup opens', async () => {- // ArrangerenderWithQueryClient(<Publisher />)- // ActfireEvent.click(screen.getByTestId('portal-trigger'))- // Assertexpect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true)})it('should not call handleSyncWorkflowDraft when popup closes', async () => {- // ArrangerenderWithQueryClient(<Publisher />)fireEvent.click(screen.getByTestId('portal-trigger')) // openvi.clearAllMocks()- // Actawait waitFor(() => {expect(screen.getByTestId('portal-content')).toBeInTheDocument()})fireEvent.click(screen.getByTestId('portal-trigger')) // close- // Assertexpect(mockHandleSyncWorkflowDraft).not.toHaveBeenCalled()})it('should be memoized with React.memo', () => {- // Assertexpect(Publisher).toBeDefined()expect((Publisher as unknown as { $$typeof?: symbol }).$$typeof?.toString()).toContain('Symbol')})})- // --------------------------------- // User Interactions Tests- // --------------------------------describe('User Interactions', () => {it('should render popup content when opened', async () => {- // ArrangerenderWithQueryClient(<Publisher />)- // ActfireEvent.click(screen.getByTestId('portal-trigger'))- // Assertawait waitFor(() => {expect(screen.getByTestId('portal-content')).toBeInTheDocument()})@@ -383,68 +315,48 @@ describe('publisher', () => {})})- // ============================================================- // Popup (popup.tsx) - Main Popup Component Tests- // ============================================================describe('Popup (popup.tsx)', () => {- // --------------------------------- // Rendering Tests- // --------------------------------describe('Rendering', () => {it('should render unpublished state when publishedAt is null', () => {- // ArrangemockPublishedAt.mockReturnValue(null)- // ActrenderWithQueryClient(<Popup />)- // Assertexpect(screen.getByText('workflow.common.currentDraftUnpublished')).toBeInTheDocument()expect(screen.getByText(/workflow.common.autoSaved/)).toBeInTheDocument()})it('should render published state when publishedAt has value', () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)- // ActrenderWithQueryClient(<Popup />)- // Assertexpect(screen.getByText('workflow.common.latestPublished')).toBeInTheDocument()expect(screen.getByText(/workflow.common.publishedAt/)).toBeInTheDocument()})it('should render publish button with keyboard shortcuts', () => {- // Arrange & ActrenderWithQueryClient(<Popup />)- // Assertconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })expect(publishButton).toBeInTheDocument()})it('should render action buttons section', () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)- // ActrenderWithQueryClient(<Popup />)- // Assertexpect(screen.getByText('pipeline.common.goToAddDocuments')).toBeInTheDocument()expect(screen.getByText('workflow.common.accessAPIReference')).toBeInTheDocument()expect(screen.getByText('pipeline.common.publishAs')).toBeInTheDocument()})it('should disable action buttons when not published', () => {- // ArrangemockPublishedAt.mockReturnValue(null)- // ActrenderWithQueryClient(<Popup />)- // Assertconst addDocumentsButton = screen.getAllByRole('button').find(btn =>btn.textContent?.includes('pipeline.common.goToAddDocuments'),)@@ -452,13 +364,10 @@ describe('publisher', () => {})it('should enable action buttons when published', () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)- // ActrenderWithQueryClient(<Popup />)- // Assertconst addDocumentsButton = screen.getAllByRole('button').find(btn =>btn.textContent?.includes('pipeline.common.goToAddDocuments'),)@@ -466,137 +375,106 @@ describe('publisher', () => {})it('should show premium badge when publish as template is not allowed', () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false)- // ActrenderWithQueryClient(<Popup />)- // Assertexpect(screen.getByText('billing.upgradeBtn.encourageShort')).toBeInTheDocument()})it('should not show premium badge when publish as template is allowed', () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)- // ActrenderWithQueryClient(<Popup />)- // Assertexpect(screen.queryByText('billing.upgradeBtn.encourageShort')).not.toBeInTheDocument()})})- // --------------------------------- // State Management Tests- // --------------------------------describe('State Management', () => {it('should show confirm modal when first publish attempt on unpublished pipeline', async () => {- // ArrangemockPublishedAt.mockReturnValue(null)renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assertawait waitFor(() => {expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()})})it('should not show confirm modal when already published', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assert - should call publish directly without confirmawait waitFor(() => {expect(mockPublishWorkflow).toHaveBeenCalled()})})it('should update to published state after successful publish', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assertawait waitFor(() => {expect(screen.getByRole('button', { name: /workflow.common.published/i })).toBeInTheDocument()})})})- // --------------------------------- // User Interactions Tests- // --------------------------------describe('User Interactions', () => {it('should navigate to add documents when go to add documents is clicked', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)renderWithQueryClient(<Popup />)- // Actconst addDocumentsButton = screen.getAllByRole('button').find(btn =>btn.textContent?.includes('pipeline.common.goToAddDocuments'),)fireEvent.click(addDocumentsButton!)- // Assertexpect(mockPush).toHaveBeenCalledWith('/datasets/test-dataset-id/documents/create-from-pipeline')})it('should show pricing modal when publish as template is clicked without permission', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false)renderWithQueryClient(<Popup />)- // Actconst publishAsButton = screen.getAllByRole('button').find(btn =>btn.textContent?.includes('pipeline.common.publishAs'),)fireEvent.click(publishAsButton!)- // Assertexpect(mockSetShowPricingModal).toHaveBeenCalled()})it('should show publish as knowledge pipeline modal when permitted', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)renderWithQueryClient(<Popup />)- // Actconst publishAsButton = screen.getAllByRole('button').find(btn =>btn.textContent?.includes('pipeline.common.publishAs'),)fireEvent.click(publishAsButton!)- // Assertawait waitFor(() => {expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()})})it('should close publish as knowledge pipeline modal when cancel is clicked', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)renderWithQueryClient(<Popup />)@@ -610,17 +488,14 @@ describe('publisher', () => {expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()})- // ActfireEvent.click(screen.getByTestId('modal-cancel'))- // Assertawait waitFor(() => {expect(screen.queryByTestId('publish-as-knowledge-pipeline-modal')).not.toBeInTheDocument()})})it('should call publishAsCustomizedPipeline when confirm is clicked in modal', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishAsCustomizedPipeline.mockResolvedValue({})renderWithQueryClient(<Popup />)@@ -634,10 +509,8 @@ describe('publisher', () => {expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()})- // ActfireEvent.click(screen.getByTestId('modal-confirm'))- // Assertawait waitFor(() => {expect(mockPublishAsCustomizedPipeline).toHaveBeenCalledWith({pipelineId: 'test-pipeline-id',@@ -649,21 +522,15 @@ describe('publisher', () => {})})- // --------------------------------- // API Calls and Async Operations Tests- // --------------------------------describe('API Calls and Async Operations', () => {it('should call publishWorkflow API when publish button is clicked', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assertawait waitFor(() => {expect(mockPublishWorkflow).toHaveBeenCalledWith({url: '/rag/pipelines/test-pipeline-id/workflows/publish',@@ -674,16 +541,13 @@ describe('publisher', () => {})it('should show success notification after publish', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assertawait waitFor(() => {expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({@@ -695,32 +559,26 @@ describe('publisher', () => {})it('should update publishedAt in store after successful publish', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assertawait waitFor(() => {expect(mockSetPublishedAt).toHaveBeenCalledWith(1700100000)})})it('should invalidate caches after successful publish', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assertawait waitFor(() => {expect(mockMutateDatasetRes).toHaveBeenCalled()expect(mockInvalidPublishedPipelineInfo).toHaveBeenCalled()@@ -729,7 +587,6 @@ describe('publisher', () => {})it('should show success notification for publish as template', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishAsCustomizedPipeline.mockResolvedValue({})renderWithQueryClient(<Popup />)@@ -743,10 +600,8 @@ describe('publisher', () => {expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()})- // ActfireEvent.click(screen.getByTestId('modal-confirm'))- // Assertawait waitFor(() => {expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({@@ -758,7 +613,6 @@ describe('publisher', () => {})it('should invalidate customized template list after publish as template', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishAsCustomizedPipeline.mockResolvedValue({})renderWithQueryClient(<Popup />)@@ -772,31 +626,23 @@ describe('publisher', () => {expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()})- // ActfireEvent.click(screen.getByTestId('modal-confirm'))- // Assertawait waitFor(() => {expect(mockInvalidCustomizedTemplateList).toHaveBeenCalled()})})})- // --------------------------------- // Error Handling Tests- // --------------------------------describe('Error Handling', () => {it('should not proceed with publish when check fails', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockHandleCheckBeforePublish.mockResolvedValue(false)renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assert - publishWorkflow should not be called when check failsawait waitFor(() => {expect(mockHandleCheckBeforePublish).toHaveBeenCalled()})@@ -804,16 +650,13 @@ describe('publisher', () => {})it('should show error notification when publish fails', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockRejectedValue(new Error('Publish failed'))renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assertawait waitFor(() => {expect(mockNotify).toHaveBeenCalledWith({type: 'error',@@ -823,7 +666,6 @@ describe('publisher', () => {})it('should show error notification when publish as template fails', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishAsCustomizedPipeline.mockRejectedValue(new Error('Template publish failed'))renderWithQueryClient(<Popup />)@@ -837,10 +679,8 @@ describe('publisher', () => {expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()})- // ActfireEvent.click(screen.getByTestId('modal-confirm'))- // Assertawait waitFor(() => {expect(mockNotify).toHaveBeenCalledWith({type: 'error',@@ -850,7 +690,6 @@ describe('publisher', () => {})it('should close modal after publish as template error', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishAsCustomizedPipeline.mockRejectedValue(new Error('Template publish failed'))renderWithQueryClient(<Popup />)@@ -864,22 +703,16 @@ describe('publisher', () => {expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()})- // ActfireEvent.click(screen.getByTestId('modal-confirm'))- // Assertawait waitFor(() => {expect(screen.queryByTestId('publish-as-knowledge-pipeline-modal')).not.toBeInTheDocument()})})})- // --------------------------------- // Confirm Modal Tests- // --------------------------------describe('Confirm Modal', () => {it('should hide confirm modal when cancel is clicked', async () => {- // ArrangemockPublishedAt.mockReturnValue(null)renderWithQueryClient(<Popup />)@@ -890,7 +723,6 @@ describe('publisher', () => {expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()})- // Act - find and click cancel button in confirm modalconst cancelButtons = screen.getAllByRole('button')const cancelButton = cancelButtons.find(btn =>btn.className.includes('cancel') || btn.textContent?.includes('Cancel'),@@ -898,16 +730,11 @@ describe('publisher', () => {if (cancelButton)fireEvent.click(cancelButton)- // Trigger onCancel manually since we can't find the exact button- // The Confirm component has an onCancel prop that calls hideConfirm-- // Assert - modal should be dismissable// Note: This test verifies the confirm modal can be displayedexpect(screen.getByText('pipeline.common.confirmPublishContent')).toBeInTheDocument()})it('should publish when confirm is clicked in confirm modal', async () => {- // ArrangemockPublishedAt.mockReturnValue(null)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)@@ -919,28 +746,19 @@ describe('publisher', () => {expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()})- // Assert - confirm modal content is displayedexpect(screen.getByText('pipeline.common.confirmPublishContent')).toBeInTheDocument()})})- // --------------------------------- // Component Memoization Tests- // --------------------------------describe('Component Memoization', () => {it('should be memoized with React.memo', () => {- // Assertexpect(Popup).toBeDefined()expect((Popup as unknown as { $$typeof?: symbol }).$$typeof?.toString()).toContain('Symbol')})})- // --------------------------------- // Prop Variations Tests- // --------------------------------describe('Prop Variations', () => {it('should display correct width when permission is allowed', () => {- // Test with permissionmockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)const { container } = renderWithQueryClient(<Popup />)@@ -949,7 +767,6 @@ describe('publisher', () => {})it('should display correct width when permission is not allowed', () => {- // Test without permissionmockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false)const { container } = renderWithQueryClient(<Popup />)@@ -958,63 +775,45 @@ describe('publisher', () => {})it('should display draft updated time when not published', () => {- // ArrangemockPublishedAt.mockReturnValue(null)mockDraftUpdatedAt.mockReturnValue(1700000000)- // ActrenderWithQueryClient(<Popup />)- // Assertexpect(screen.getByText(/workflow.common.autoSaved/)).toBeInTheDocument()})it('should handle null draftUpdatedAt gracefully', () => {- // ArrangemockPublishedAt.mockReturnValue(null)mockDraftUpdatedAt.mockReturnValue(0)- // ActrenderWithQueryClient(<Popup />)- // Assertexpect(screen.getByText(/workflow.common.autoSaved/)).toBeInTheDocument()})})- // --------------------------------- // API Reference Link Tests- // --------------------------------describe('API Reference Link', () => {it('should render API reference link with correct href', () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)- // ActrenderWithQueryClient(<Popup />)- // Assertconst apiLink = screen.getByRole('link')expect(apiLink).toHaveAttribute('href', 'https://api.dify.ai/v1/datasets/test-dataset-id')expect(apiLink).toHaveAttribute('target', '_blank')})})- // --------------------------------- // Keyboard Shortcut Tests- // --------------------------------describe('Keyboard Shortcuts', () => {it('should trigger publish when keyboard shortcut is pressed', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Act - simulate keyboard shortcutconst mockEvent = { preventDefault: vi.fn() } as unknown as KeyboardEventkeyPressCallback?.(mockEvent)- // Assertexpect(mockEvent.preventDefault).toHaveBeenCalled()await waitFor(() => {expect(mockPublishWorkflow).toHaveBeenCalled()@@ -1022,12 +821,10 @@ describe('publisher', () => {})it('should not trigger publish when already published in session', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // First publish via button click to set published stateconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)@@ -1037,32 +834,26 @@ describe('publisher', () => {vi.clearAllMocks()- // Act - simulate keyboard shortcut after already publishedconst mockEvent = { preventDefault: vi.fn() } as unknown as KeyboardEventkeyPressCallback?.(mockEvent)- // Assert - should return early without publishingexpect(mockEvent.preventDefault).toHaveBeenCalled()expect(mockPublishWorkflow).not.toHaveBeenCalled()})it('should show confirm modal when shortcut pressed on unpublished pipeline', async () => {- // ArrangemockPublishedAt.mockReturnValue(null)renderWithQueryClient(<Popup />)- // Act - simulate keyboard shortcutconst mockEvent = { preventDefault: vi.fn() } as unknown as KeyboardEventkeyPressCallback?.(mockEvent)- // Assertawait waitFor(() => {expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()})})it('should not trigger duplicate publish via shortcut when already publishing', async () => {- // Arrange - create a promise that we can controllet resolvePublish: () => void = () => {}mockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockImplementation(() => new Promise((resolve) => {@@ -1070,59 +861,45 @@ describe('publisher', () => {}))renderWithQueryClient(<Popup />)- // Act - trigger publish via keyboard shortcut firstconst mockEvent1 = { preventDefault: vi.fn() } as unknown as KeyboardEventkeyPressCallback?.(mockEvent1)- // Wait for the first publish to start (button becomes disabled)await waitFor(() => {const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })expect(publishButton).toBeDisabled()})- // Try to trigger again via shortcut while publishingconst mockEvent2 = { preventDefault: vi.fn() } as unknown as KeyboardEventkeyPressCallback?.(mockEvent2)- // Assert - only one call to publishWorkflowexpect(mockPublishWorkflow).toHaveBeenCalledTimes(1)- // Cleanup - resolve the promiseresolvePublish()})})- // --------------------------------- // Finally Block Cleanup Tests- // --------------------------------describe('Finally Block Cleanup', () => {it('should reset publishing state after successful publish', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assert - button should be disabled during publishing, then show publishedawait waitFor(() => {expect(screen.getByRole('button', { name: /workflow.common.published/i })).toBeInTheDocument()})})it('should reset publishing state after failed publish', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockRejectedValue(new Error('Publish failed'))renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assert - should show error and button should be enabled again (not showing "published")await waitFor(() => {expect(mockNotify).toHaveBeenCalledWith({type: 'error',@@ -1130,19 +907,16 @@ describe('publisher', () => {})})- // Button should still show publishUpdate since it wasn't successfully publishedawait waitFor(() => {expect(screen.getByRole('button', { name: /workflow.common.publishUpdate/i })).toBeInTheDocument()})})it('should hide confirm modal after publish from confirm', async () => {- // ArrangemockPublishedAt.mockReturnValue(null)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Show confirm modal firstconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)@@ -1150,25 +924,18 @@ describe('publisher', () => {expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()})- // Act - trigger publish again (which happens when confirm is clicked)- // The mock for workflow hooks returns handleCheckBeforePublish that resolves to true- // We need to simulate the confirm button click which calls handlePublish again- // Since confirmVisible is now true and publishedAt is null, it should proceed to publishfireEvent.click(publishButton)- // Assert - confirm modal should be hidden after publish completesawait waitFor(() => {expect(screen.getByRole('button', { name: /workflow.common.published/i })).toBeInTheDocument()})})it('should hide confirm modal after failed publish', async () => {- // ArrangemockPublishedAt.mockReturnValue(null)mockPublishWorkflow.mockRejectedValue(new Error('Publish failed'))renderWithQueryClient(<Popup />)- // Show confirm modal firstconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)@@ -1176,10 +943,8 @@ describe('publisher', () => {expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()})- // Act - trigger publish from confirm (call handlePublish when confirmVisible is true)fireEvent.click(publishButton)- // Assert - error notification should be shownawait waitFor(() => {expect(mockNotify).toHaveBeenCalledWith({type: 'error',@@ -1190,137 +955,104 @@ describe('publisher', () => {})})- // ============================================================- // Edge Cases- // ============================================================describe('Edge Cases', () => {it('should handle undefined pipelineId gracefully', () => {- // ArrangemockPipelineId.mockReturnValue('')- // ActrenderWithQueryClient(<Popup />)- // Assert - should render without crashingexpect(screen.getByText('workflow.common.currentDraftUnpublished')).toBeInTheDocument()})it('should handle empty publish response', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue(null)renderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assert - should not call setPublishedAt or notify when response is nullawait waitFor(() => {expect(mockPublishWorkflow).toHaveBeenCalled()})- // setPublishedAt should not be called because res is falsyexpect(mockSetPublishedAt).not.toHaveBeenCalled()})it('should prevent multiple simultaneous publish calls', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)- // Create a promise that never resolves to simulate ongoing publishmockPublishWorkflow.mockImplementation(() => new Promise(() => {}))renderWithQueryClient(<Popup />)- // Act - click publish button multiple times rapidlyconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Wait for button to become disabledawait waitFor(() => {expect(publishButton).toBeDisabled()})- // Try clicking againfireEvent.click(publishButton)fireEvent.click(publishButton)- // Assert - publishWorkflow should only be called once due to guardexpect(mockPublishWorkflow).toHaveBeenCalledTimes(1)})it('should disable publish button when already published in session', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Act - publish onceconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assert - button should show "published" stateawait waitFor(() => {expect(screen.getByRole('button', { name: /workflow.common.published/i })).toBeDisabled()})})it('should not trigger publish when already publishing', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishWorkflow.mockImplementation(() => new Promise(() => {})) // Never resolvesrenderWithQueryClient(<Popup />)- // Actconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // The button should be disabled while publishingawait waitFor(() => {expect(publishButton).toBeDisabled()})})})- // ============================================================- // Integration Tests- // ============================================================describe('Integration Tests', () => {it('should complete full publish flow for unpublished pipeline', async () => {- // ArrangemockPublishedAt.mockReturnValue(null)mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })renderWithQueryClient(<Popup />)- // Act - click publish to show confirmconst publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })fireEvent.click(publishButton)- // Assert - confirm modal should appearawait waitFor(() => {expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()})})it('should complete full publish as template flow', async () => {- // ArrangemockPublishedAt.mockReturnValue(1700000000)mockPublishAsCustomizedPipeline.mockResolvedValue({})renderWithQueryClient(<Popup />)- // Act - click publish as template buttonconst publishAsButton = screen.getAllByRole('button').find(btn =>btn.textContent?.includes('pipeline.common.publishAs'),)fireEvent.click(publishAsButton!)- // Assert - modal should appearawait waitFor(() => {expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()})- // Act - confirmfireEvent.click(screen.getByTestId('modal-confirm'))- // Assert - success notification and modal closesawait waitFor(() => {expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({@@ -1332,18 +1064,14 @@ describe('publisher', () => {})it('should show Publisher button and open popup with Popup component', async () => {- // Arrange & ActrenderWithQueryClient(<Publisher />)- // Click to open popupfireEvent.click(screen.getByTestId('portal-trigger'))- // Assertawait waitFor(() => {expect(screen.getByTestId('portal-content')).toBeInTheDocument()})- // Verify sync was called when openingexpect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true)})})diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsxnew file mode 100644index 00000000000..71707721a47--- /dev/null+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx@@ -0,0 +1,319 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import Popup from '../popup'++const mockPublishWorkflow = vi.fn().mockResolvedValue({ created_at: '2024-01-01T00:00:00Z' })+const mockPublishAsCustomizedPipeline = vi.fn().mockResolvedValue({})+const mockNotify = vi.fn()+const mockPush = vi.fn()+const mockHandleCheckBeforePublish = vi.fn().mockResolvedValue(true)+const mockSetPublishedAt = vi.fn()+const mockMutateDatasetRes = vi.fn()+const mockSetShowPricingModal = vi.fn()+const mockInvalidPublishedPipelineInfo = vi.fn()+const mockInvalidDatasetList = vi.fn()+const mockInvalidCustomizedTemplateList = vi.fn()++let mockPublishedAt: string | undefined = '2024-01-01T00:00:00Z'+let mockDraftUpdatedAt: string | undefined = '2024-06-01T00:00:00Z'+let mockPipelineId: string | undefined = 'pipeline-123'+let mockIsAllowPublishAsCustom = true+vi.mock('next/navigation', () => ({+ useParams: () => ({ datasetId: 'ds-123' }),+ useRouter: () => ({ push: mockPush }),+}))++vi.mock('next/link', () => ({+ default: ({ children, href }: { children: React.ReactNode, href: string }) => (+ <a href={href}>{children}</a>+ ),+}))++vi.mock('ahooks', () => ({+ useBoolean: (initial: boolean) => {+ const state = { value: initial }+ return [state.value, {+ setFalse: vi.fn(),+ setTrue: vi.fn(),+ }]+ },+ useKeyPress: vi.fn(),+}))++vi.mock('@/app/components/workflow/store', () => ({+ useStore: (selector: (state: Record<string, unknown>) => unknown) => {+ const state = {+ publishedAt: mockPublishedAt,+ draftUpdatedAt: mockDraftUpdatedAt,+ pipelineId: mockPipelineId,+ }+ return selector(state)+ },+ useWorkflowStore: () => ({+ getState: () => ({+ setPublishedAt: mockSetPublishedAt,+ }),+ }),+}))++vi.mock('@/app/components/base/toast', () => ({+ useToastContext: () => ({ notify: mockNotify }),+}))++vi.mock('@/app/components/base/button', () => ({+ default: ({ children, onClick, disabled, variant, className }: Record<string, unknown>) => (+ <button+ onClick={onClick as () => void}+ disabled={disabled as boolean}+ data-variant={variant as string}+ className={className as string}+ >+ {children as React.ReactNode}+ </button>+ ),+}))++vi.mock('@/app/components/base/confirm', () => ({+ default: ({ isShow, onConfirm, onCancel, title }: {+ isShow: boolean+ onConfirm: () => void+ onCancel: () => void+ title: string+ }) =>+ isShow+ ? (+ <div data-testid="confirm-modal">+ <span>{title}</span>+ <button data-testid="publish-confirm" onClick={onConfirm}>OK</button>+ <button data-testid="publish-cancel" onClick={onCancel}>Cancel</button>+ </div>+ )+ : null,+}))++vi.mock('@/app/components/base/divider', () => ({+ default: () => <hr />,+}))++vi.mock('@/app/components/base/amplitude', () => ({+ trackEvent: vi.fn(),+}))++vi.mock('@/app/components/base/icons/src/public/common', () => ({+ SparklesSoft: () => <span data-testid="sparkles" />,+}))++vi.mock('@/app/components/base/premium-badge', () => ({+ default: ({ children }: { children: React.ReactNode }) => <span data-testid="premium-badge">{children}</span>,+}))++vi.mock('@/app/components/workflow/hooks', () => ({+ useChecklistBeforePublish: () => ({+ handleCheckBeforePublish: mockHandleCheckBeforePublish,+ }),+}))++vi.mock('@/app/components/workflow/shortcuts-name', () => ({+ default: ({ keys }: { keys: string[] }) => <span data-testid="shortcuts">{keys.join('+')}</span>,+}))++vi.mock('@/app/components/workflow/utils', () => ({+ getKeyboardKeyCodeBySystem: () => 'ctrl',+}))++vi.mock('@/context/dataset-detail', () => ({+ useDatasetDetailContextWithSelector: () => mockMutateDatasetRes,+}))++vi.mock('@/context/i18n', () => ({+ useDocLink: () => () => 'https://docs.dify.ai',+}))++vi.mock('@/context/modal-context', () => ({+ useModalContextSelector: () => mockSetShowPricingModal,+}))++vi.mock('@/context/provider-context', () => ({+ useProviderContextSelector: () => mockIsAllowPublishAsCustom,+}))++vi.mock('@/hooks/use-api-access-url', () => ({+ useDatasetApiAccessUrl: () => '/api/datasets/ds-123',+}))++vi.mock('@/hooks/use-format-time-from-now', () => ({+ useFormatTimeFromNow: () => ({+ formatTimeFromNow: (time: string) => `formatted:${time}`,+ }),+}))++vi.mock('@/service/knowledge/use-dataset', () => ({+ useInvalidDatasetList: () => mockInvalidDatasetList,+}))++vi.mock('@/service/use-base', () => ({+ useInvalid: () => mockInvalidPublishedPipelineInfo,+}))++vi.mock('@/service/use-pipeline', () => ({+ publishedPipelineInfoQueryKeyPrefix: ['published-pipeline'],+ useInvalidCustomizedTemplateList: () => mockInvalidCustomizedTemplateList,+ usePublishAsCustomizedPipeline: () => ({+ mutateAsync: mockPublishAsCustomizedPipeline,+ }),+}))++vi.mock('@/service/use-workflow', () => ({+ usePublishWorkflow: () => ({+ mutateAsync: mockPublishWorkflow,+ }),+}))++vi.mock('@/utils/classnames', () => ({+ cn: (...args: string[]) => args.filter(Boolean).join(' '),+}))++vi.mock('../../../publish-as-knowledge-pipeline-modal', () => ({+ default: ({ onConfirm, onCancel }: { onConfirm: (name: string, icon: unknown, desc: string) => void, onCancel: () => void }) => (+ <div data-testid="publish-as-modal">+ <button data-testid="publish-as-confirm" onClick={() => onConfirm('My Pipeline', { icon_type: 'emoji' }, 'desc')}>+ Confirm+ </button>+ <button data-testid="publish-as-cancel" onClick={onCancel}>Cancel</button>+ </div>+ ),+}))++vi.mock('@remixicon/react', () => ({+ RiArrowRightUpLine: () => <span />,+ RiHammerLine: () => <span />,+ RiPlayCircleLine: () => <span />,+ RiTerminalBoxLine: () => <span />,+}))++describe('Popup', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockPublishedAt = '2024-01-01T00:00:00Z'+ mockDraftUpdatedAt = '2024-06-01T00:00:00Z'+ mockPipelineId = 'pipeline-123'+ mockIsAllowPublishAsCustom = true+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ describe('Rendering', () => {+ it('should render when published', () => {+ render(<Popup />)++ expect(screen.getByText('workflow.common.latestPublished')).toBeInTheDocument()+ expect(screen.getByText(/workflow\.common\.publishedAt/)).toBeInTheDocument()+ })++ it('should render unpublished state', () => {+ mockPublishedAt = undefined+ render(<Popup />)++ expect(screen.getByText('workflow.common.currentDraftUnpublished')).toBeInTheDocument()+ expect(screen.getByText(/workflow\.common\.autoSaved/)).toBeInTheDocument()+ })++ it('should render publish button with shortcuts', () => {+ render(<Popup />)++ expect(screen.getByText('workflow.common.publishUpdate')).toBeInTheDocument()+ expect(screen.getByTestId('shortcuts')).toBeInTheDocument()+ })++ it('should render "Go to Add Documents" button', () => {+ render(<Popup />)++ expect(screen.getByText('pipeline.common.goToAddDocuments')).toBeInTheDocument()+ })++ it('should render "API Reference" button', () => {+ render(<Popup />)++ expect(screen.getByText('workflow.common.accessAPIReference')).toBeInTheDocument()+ })++ it('should render "Publish As" button', () => {+ render(<Popup />)++ expect(screen.getByText('pipeline.common.publishAs')).toBeInTheDocument()+ })+ })++ describe('Premium Badge', () => {+ it('should not show premium badge when allowed', () => {+ mockIsAllowPublishAsCustom = true+ render(<Popup />)++ expect(screen.queryByTestId('premium-badge')).not.toBeInTheDocument()+ })++ it('should show premium badge when not allowed', () => {+ mockIsAllowPublishAsCustom = false+ render(<Popup />)++ expect(screen.getByTestId('premium-badge')).toBeInTheDocument()+ })+ })++ describe('Navigation', () => {+ it('should navigate to add documents page', () => {+ render(<Popup />)++ fireEvent.click(screen.getByText('pipeline.common.goToAddDocuments'))++ expect(mockPush).toHaveBeenCalledWith('/datasets/ds-123/documents/create-from-pipeline')+ })+ })++ describe('Button disable states', () => {+ it('should disable add documents button when not published', () => {+ mockPublishedAt = undefined+ render(<Popup />)++ const btn = screen.getByText('pipeline.common.goToAddDocuments').closest('button')+ expect(btn).toBeDisabled()+ })++ it('should disable publish-as button when not published', () => {+ mockPublishedAt = undefined+ render(<Popup />)++ const btn = screen.getByText('pipeline.common.publishAs').closest('button')+ expect(btn).toBeDisabled()+ })+ })++ describe('Publish As Knowledge Pipeline', () => {+ it('should show pricing modal when not allowed', () => {+ mockIsAllowPublishAsCustom = false+ render(<Popup />)++ fireEvent.click(screen.getByText('pipeline.common.publishAs'))++ expect(mockSetShowPricingModal).toHaveBeenCalled()+ })+ })++ describe('Time formatting', () => {+ it('should format published time', () => {+ render(<Popup />)++ expect(screen.getByText(/formatted:2024-01-01/)).toBeInTheDocument()+ })++ it('should format draft updated time when unpublished', () => {+ mockPublishedAt = undefined+ render(<Popup />)++ expect(screen.getByText(/formatted:2024-06-01/)).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/rag-pipeline/hooks/index.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/index.spec.tssimilarity index 91%rename from web/app/components/rag-pipeline/hooks/index.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/index.spec.tsindex 7917275c18c..4c60e5133c0 100644--- a/web/app/components/rag-pipeline/hooks/index.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/index.spec.ts@@ -6,10 +6,6 @@ import { BlockEnum } from '@/app/components/workflow/types'import { Resolution, TransferMethod } from '@/types/app'import { FlowType } from '@/types/common'-// ============================================================================-// Import hooks after mocks-// ============================================================================-import {useAvailableNodesMetaData,useDSL,@@ -20,16 +16,11 @@ import {usePipelineRefreshDraft,usePipelineRun,usePipelineStartRun,-} from './index'-import { useConfigsMap } from './use-configs-map'-import { useConfigurations, useInitialData } from './use-input-fields'-import { usePipelineTemplate } from './use-pipeline-template'--// ============================================================================-// Mocks-// ============================================================================+} from '../index'+import { useConfigsMap } from '../use-configs-map'+import { useConfigurations, useInitialData } from '../use-input-fields'+import { usePipelineTemplate } from '../use-pipeline-template'-// Mock the workflow storeconst _mockGetState = vi.fn()const mockUseStore = vi.fn()const mockUseWorkflowStore = vi.fn()@@ -39,14 +30,6 @@ vi.mock('@/app/components/workflow/store', () => ({useWorkflowStore: () => mockUseWorkflowStore(),}))-// Mock react-i18next-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string) => key,- }),-}))--// Mock toast contextconst mockNotify = vi.fn()vi.mock('@/app/components/base/toast', () => ({useToastContext: () => ({@@ -54,7 +37,6 @@ vi.mock('@/app/components/base/toast', () => ({}),}))-// Mock event emitter contextconst mockEventEmit = vi.fn()vi.mock('@/context/event-emitter', () => ({useEventEmitterContextContext: () => ({@@ -64,19 +46,16 @@ vi.mock('@/context/event-emitter', () => ({}),}))-// Mock i18n docLinkvi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,}))-// Mock workflow constantsvi.mock('@/app/components/workflow/constants', () => ({DSL_EXPORT_CHECK: 'DSL_EXPORT_CHECK',WORKFLOW_DATA_UPDATE: 'WORKFLOW_DATA_UPDATE',START_INITIAL_POSITION: { x: 100, y: 100 },}))-// Mock workflow constants/nodevi.mock('@/app/components/workflow/constants/node', () => ({WORKFLOW_COMMON_NODES: [{@@ -90,7 +69,6 @@ vi.mock('@/app/components/workflow/constants/node', () => ({],}))-// Mock data source defaultsvi.mock('@/app/components/workflow/nodes/data-source-empty/default', () => ({default: {metaData: { type: BlockEnum.DataSourceEmpty },@@ -112,7 +90,6 @@ vi.mock('@/app/components/workflow/nodes/knowledge-base/default', () => ({},}))-// Mock workflow utils with all needed exportsvi.mock('@/app/components/workflow/utils', async (importOriginal) => {const actual = await importOriginal() as Record<string, unknown>return {@@ -123,7 +100,6 @@ vi.mock('@/app/components/workflow/utils', async (importOriginal) => {}})-// Mock pipeline serviceconst mockExportPipelineConfig = vi.fn()vi.mock('@/service/use-pipeline', () => ({useExportPipelineDSL: () => ({@@ -131,7 +107,6 @@ vi.mock('@/service/use-pipeline', () => ({}),}))-// Mock workflow servicevi.mock('@/service/workflow', () => ({fetchWorkflowDraft: vi.fn().mockResolvedValue({graph: { nodes: [], edges: [], viewport: {} },@@ -139,10 +114,6 @@ vi.mock('@/service/workflow', () => ({}),}))-// ============================================================================-// Tests-// ============================================================================-describe('useConfigsMap', () => {beforeEach(() => {vi.clearAllMocks()@@ -307,11 +278,10 @@ describe('useInputFieldPanel', () => {it('should set edit panel props when toggleInputFieldEditPanel is called', () => {const { result } = renderHook(() => useInputFieldPanel())- const editContent = { type: 'edit', data: {} }+ const editContent = { onClose: vi.fn(), onSubmit: vi.fn() }act(() => {- // eslint-disable-next-line ts/no-explicit-any- result.current.toggleInputFieldEditPanel(editContent as any)+ result.current.toggleInputFieldEditPanel(editContent)})expect(mockSetInputFieldEditPanelProps).toHaveBeenCalledWith(editContent)diff --git a/web/app/components/rag-pipeline/hooks/use-DSL.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.tssimilarity index 90%rename from web/app/components/rag-pipeline/hooks/use-DSL.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.tsindex 295ed20bd82..c0b983052d7 100644--- a/web/app/components/rag-pipeline/hooks/use-DSL.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts@@ -1,8 +1,7 @@import { act, renderHook, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { useDSL } from './use-DSL'+import { useDSL } from '../use-DSL'-// Mock dependenciesconst mockNotify = vi.fn()vi.mock('@/app/components/base/toast', () => ({useToastContext: () => ({ notify: mockNotify }),@@ -14,7 +13,7 @@ vi.mock('@/context/event-emitter', () => ({}))const mockDoSyncWorkflowDraft = vi.fn()-vi.mock('./use-nodes-sync-draft', () => ({+vi.mock('../use-nodes-sync-draft', () => ({useNodesSyncDraft: () => ({ doSyncWorkflowDraft: mockDoSyncWorkflowDraft }),}))@@ -37,21 +36,10 @@ const mockDownloadBlob = vi.fn()vi.mock('@/utils/download', () => ({downloadBlob: (...args: unknown[]) => mockDownloadBlob(...args),}))--vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string) => key,- }),-}))-vi.mock('@/app/components/workflow/constants', () => ({DSL_EXPORT_CHECK: 'DSL_EXPORT_CHECK',}))-// ============================================================================-// Tests-// ============================================================================-describe('useDSL', () => {let mockLink: { href: string, download: string, click: ReturnType<typeof vi.fn>, style: { display: string }, remove: ReturnType<typeof vi.fn> }let originalCreateElement: typeof document.createElement@@ -62,7 +50,6 @@ describe('useDSL', () => {beforeEach(() => {vi.clearAllMocks()- // Create a proper mock link element with all required properties for downloadBlobmockLink = {href: '',download: '',@@ -71,7 +58,6 @@ describe('useDSL', () => {remove: vi.fn(),}- // Save original and mock selectively - only intercept 'a' elementsoriginalCreateElement = document.createElement.bind(document)document.createElement = vi.fn((tagName: string) => {if (tagName === 'a') {@@ -80,15 +66,12 @@ describe('useDSL', () => {return originalCreateElement(tagName)}) as typeof document.createElement- // Mock document.body.appendChild for downloadBloboriginalAppendChild = document.body.appendChild.bind(document.body)document.body.appendChild = vi.fn(<T extends Node>(node: T): T => node) as typeof document.body.appendChild- // downloadBlob uses window.URL, not URLmockCreateObjectURL = vi.spyOn(window.URL, 'createObjectURL').mockReturnValue('blob:test-url')mockRevokeObjectURL = vi.spyOn(window.URL, 'revokeObjectURL').mockImplementation(() => {})- // Default store statemockGetState.mockReturnValue({pipelineId: 'test-pipeline-id',knowledgeName: 'Test Knowledge Base',@@ -170,7 +153,7 @@ describe('useDSL', () => {await waitFor(() => {expect(mockNotify).toHaveBeenCalledWith({type: 'error',- message: 'exportFailed',+ message: 'app.exportFailed',})})})@@ -251,7 +234,7 @@ describe('useDSL', () => {await waitFor(() => {expect(mockNotify).toHaveBeenCalledWith({type: 'error',- message: 'exportFailed',+ message: 'app.exportFailed',})})})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-available-nodes-meta-data.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-available-nodes-meta-data.spec.tsnew file mode 100644index 00000000000..f3d04533da3--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-available-nodes-meta-data.spec.ts@@ -0,0 +1,130 @@+import { renderHook } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { BlockEnum } from '@/app/components/workflow/types'+import { useAvailableNodesMetaData } from '../use-available-nodes-meta-data'++vi.mock('@/context/i18n', () => ({+ useDocLink: () => (path?: string) => `https://docs.dify.ai${path || ''}`,+}))++vi.mock('@/app/components/workflow/constants/node', () => ({+ WORKFLOW_COMMON_NODES: [+ {+ metaData: { type: BlockEnum.LLM },+ defaultValue: { title: 'LLM' },+ },+ {+ metaData: { type: BlockEnum.HumanInput },+ defaultValue: { title: 'Human Input' },+ },+ {+ metaData: { type: BlockEnum.HttpRequest },+ defaultValue: { title: 'HTTP Request' },+ },+ ],+}))++vi.mock('@/app/components/workflow/nodes/data-source-empty/default', () => ({+ default: {+ metaData: { type: BlockEnum.DataSourceEmpty },+ defaultValue: { title: 'Data Source Empty' },+ },+}))++vi.mock('@/app/components/workflow/nodes/data-source/default', () => ({+ default: {+ metaData: { type: BlockEnum.DataSource },+ defaultValue: { title: 'Data Source' },+ },+}))++vi.mock('@/app/components/workflow/nodes/knowledge-base/default', () => ({+ default: {+ metaData: { type: BlockEnum.KnowledgeBase },+ defaultValue: { title: 'Knowledge Base' },+ },+}))++describe('useAvailableNodesMetaData', () => {+ it('should return nodes and nodesMap', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())++ expect(result.current.nodes).toBeDefined()+ expect(result.current.nodesMap).toBeDefined()+ })++ it('should filter out HumanInput node', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())+ const nodeTypes = result.current.nodes.map(n => n.metaData.type)++ expect(nodeTypes).not.toContain(BlockEnum.HumanInput)+ })++ it('should include DataSource with _dataSourceStartToAdd flag', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())+ const dsNode = result.current.nodes.find(n => n.metaData.type === BlockEnum.DataSource)++ expect(dsNode).toBeDefined()+ expect(dsNode!.defaultValue._dataSourceStartToAdd).toBe(true)+ })++ it('should include KnowledgeBase and DataSourceEmpty nodes', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())+ const nodeTypes = result.current.nodes.map(n => n.metaData.type)++ expect(nodeTypes).toContain(BlockEnum.KnowledgeBase)+ expect(nodeTypes).toContain(BlockEnum.DataSourceEmpty)+ })++ it('should translate title and description for each node', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())++ result.current.nodes.forEach((node) => {+ expect(node.metaData.title).toMatch(/^workflow\.blocks\./)+ expect(node.metaData.description).toMatch(/^workflow\.blocksAbout\./)+ })+ })++ it('should set helpLinkUri on each node metaData', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())++ result.current.nodes.forEach((node) => {+ expect(node.metaData.helpLinkUri).toContain('https://docs.dify.ai')+ expect(node.metaData.helpLinkUri).toContain('knowledge-pipeline')+ })+ })++ it('should set type and title on defaultValue', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())++ result.current.nodes.forEach((node) => {+ expect(node.defaultValue.type).toBe(node.metaData.type)+ expect(node.defaultValue.title).toBe(node.metaData.title)+ })+ })++ it('should build nodesMap indexed by BlockEnum type', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())+ const { nodesMap } = result.current++ expect(nodesMap[BlockEnum.LLM]).toBeDefined()+ expect(nodesMap[BlockEnum.DataSource]).toBeDefined()+ expect(nodesMap[BlockEnum.KnowledgeBase]).toBeDefined()+ })++ it('should alias VariableAssigner to VariableAggregator in nodesMap', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())+ const { nodesMap } = result.current++ expect(nodesMap[BlockEnum.VariableAssigner]).toBe(nodesMap[BlockEnum.VariableAggregator])+ })++ it('should include common nodes except HumanInput', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())+ const nodeTypes = result.current.nodes.map(n => n.metaData.type)++ expect(nodeTypes).toContain(BlockEnum.LLM)+ expect(nodeTypes).toContain(BlockEnum.HttpRequest)+ expect(nodeTypes).not.toContain(BlockEnum.HumanInput)+ })+})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-configs-map.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-configs-map.spec.tsnew file mode 100644index 00000000000..6e5bedd1225--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-configs-map.spec.ts@@ -0,0 +1,70 @@+import { renderHook } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'++import { useConfigsMap } from '../use-configs-map'++const mockPipelineId = 'pipeline-xyz'+const mockFileUploadConfig = { max_size: 10 }++vi.mock('@/app/components/workflow/store', () => ({+ useStore: (selector: (state: Record<string, unknown>) => unknown) => {+ const state = {+ pipelineId: mockPipelineId,+ fileUploadConfig: mockFileUploadConfig,+ }+ return selector(state)+ },+}))++vi.mock('@/types/app', () => ({+ Resolution: { high: 'high' },+ TransferMethod: { local_file: 'local_file', remote_url: 'remote_url' },+}))++vi.mock('@/types/common', () => ({+ FlowType: { ragPipeline: 'rag-pipeline' },+}))++describe('useConfigsMap', () => {+ it('should return flowId from pipelineId', () => {+ const { result } = renderHook(() => useConfigsMap())++ expect(result.current.flowId).toBe('pipeline-xyz')+ })++ it('should return ragPipeline as flowType', () => {+ const { result } = renderHook(() => useConfigsMap())++ expect(result.current.flowType).toBe('rag-pipeline')+ })++ it('should include file settings with image disabled', () => {+ const { result } = renderHook(() => useConfigsMap())++ expect(result.current.fileSettings.image.enabled).toBe(false)+ })++ it('should set image detail to high resolution', () => {+ const { result } = renderHook(() => useConfigsMap())++ expect(result.current.fileSettings.image.detail).toBe('high')+ })++ it('should set image number_limits to 3', () => {+ const { result } = renderHook(() => useConfigsMap())++ expect(result.current.fileSettings.image.number_limits).toBe(3)+ })++ it('should include both transfer methods for image', () => {+ const { result } = renderHook(() => useConfigsMap())++ expect(result.current.fileSettings.image.transfer_methods).toEqual(['local_file', 'remote_url'])+ })++ it('should pass through fileUploadConfig from store', () => {+ const { result } = renderHook(() => useConfigsMap())++ expect(result.current.fileSettings.fileUploadConfig).toEqual({ max_size: 10 })+ })+})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-get-run-and-trace-url.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-get-run-and-trace-url.spec.tsnew file mode 100644index 00000000000..10f31f55a6f--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-get-run-and-trace-url.spec.ts@@ -0,0 +1,45 @@+import { renderHook } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'++import { useGetRunAndTraceUrl } from '../use-get-run-and-trace-url'++vi.mock('@/app/components/workflow/store', () => ({+ useWorkflowStore: () => ({+ getState: () => ({+ pipelineId: 'pipeline-test-123',+ }),+ }),+}))++describe('useGetRunAndTraceUrl', () => {+ it('should return a function getWorkflowRunAndTraceUrl', () => {+ const { result } = renderHook(() => useGetRunAndTraceUrl())++ expect(typeof result.current.getWorkflowRunAndTraceUrl).toBe('function')+ })++ it('should generate correct runUrl', () => {+ const { result } = renderHook(() => useGetRunAndTraceUrl())+ const { runUrl } = result.current.getWorkflowRunAndTraceUrl('run-abc')++ expect(runUrl).toBe('/rag/pipelines/pipeline-test-123/workflow-runs/run-abc')+ })++ it('should generate correct traceUrl', () => {+ const { result } = renderHook(() => useGetRunAndTraceUrl())+ const { traceUrl } = result.current.getWorkflowRunAndTraceUrl('run-abc')++ expect(traceUrl).toBe('/rag/pipelines/pipeline-test-123/workflow-runs/run-abc/node-executions')+ })++ it('should handle different runIds', () => {+ const { result } = renderHook(() => useGetRunAndTraceUrl())++ const r1 = result.current.getWorkflowRunAndTraceUrl('id-1')+ const r2 = result.current.getWorkflowRunAndTraceUrl('id-2')++ expect(r1.runUrl).toContain('id-1')+ expect(r2.runUrl).toContain('id-2')+ expect(r1.runUrl).not.toBe(r2.runUrl)+ })+})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-input-field-panel.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-input-field-panel.spec.tsnew file mode 100644index 00000000000..d8c335e489a--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-input-field-panel.spec.ts@@ -0,0 +1,130 @@+import { act, renderHook } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { useInputFieldPanel } from '../use-input-field-panel'++const mockSetShowInputFieldPanel = vi.fn()+const mockSetShowInputFieldPreviewPanel = vi.fn()+const mockSetInputFieldEditPanelProps = vi.fn()++let mockShowInputFieldPreviewPanel = false+let mockInputFieldEditPanelProps: unknown = null++vi.mock('@/app/components/workflow/store', () => ({+ useWorkflowStore: () => ({+ getState: () => ({+ showInputFieldPreviewPanel: mockShowInputFieldPreviewPanel,+ setShowInputFieldPanel: mockSetShowInputFieldPanel,+ setShowInputFieldPreviewPanel: mockSetShowInputFieldPreviewPanel,+ setInputFieldEditPanelProps: mockSetInputFieldEditPanelProps,+ }),+ }),+ useStore: (selector: (state: Record<string, unknown>) => unknown) => {+ const state = {+ showInputFieldPreviewPanel: mockShowInputFieldPreviewPanel,+ inputFieldEditPanelProps: mockInputFieldEditPanelProps,+ }+ return selector(state)+ },+}))++describe('useInputFieldPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockShowInputFieldPreviewPanel = false+ mockInputFieldEditPanelProps = null+ })++ describe('isPreviewing', () => {+ it('should return false when preview panel is hidden', () => {+ mockShowInputFieldPreviewPanel = false+ const { result } = renderHook(() => useInputFieldPanel())++ expect(result.current.isPreviewing).toBe(false)+ })++ it('should return true when preview panel is shown', () => {+ mockShowInputFieldPreviewPanel = true+ const { result } = renderHook(() => useInputFieldPanel())++ expect(result.current.isPreviewing).toBe(true)+ })+ })++ describe('isEditing', () => {+ it('should return false when no edit panel props', () => {+ mockInputFieldEditPanelProps = null+ const { result } = renderHook(() => useInputFieldPanel())++ expect(result.current.isEditing).toBe(false)+ })++ it('should return true when edit panel props exist', () => {+ mockInputFieldEditPanelProps = { onSubmit: vi.fn(), onClose: vi.fn() }+ const { result } = renderHook(() => useInputFieldPanel())++ expect(result.current.isEditing).toBe(true)+ })+ })++ describe('closeAllInputFieldPanels', () => {+ it('should close all panels and clear edit props', () => {+ const { result } = renderHook(() => useInputFieldPanel())++ act(() => {+ result.current.closeAllInputFieldPanels()+ })++ expect(mockSetShowInputFieldPanel).toHaveBeenCalledWith(false)+ expect(mockSetShowInputFieldPreviewPanel).toHaveBeenCalledWith(false)+ expect(mockSetInputFieldEditPanelProps).toHaveBeenCalledWith(null)+ })+ })++ describe('toggleInputFieldPreviewPanel', () => {+ it('should toggle preview panel from false to true', () => {+ mockShowInputFieldPreviewPanel = false+ const { result } = renderHook(() => useInputFieldPanel())++ act(() => {+ result.current.toggleInputFieldPreviewPanel()+ })++ expect(mockSetShowInputFieldPreviewPanel).toHaveBeenCalledWith(true)+ })++ it('should toggle preview panel from true to false', () => {+ mockShowInputFieldPreviewPanel = true+ const { result } = renderHook(() => useInputFieldPanel())++ act(() => {+ result.current.toggleInputFieldPreviewPanel()+ })++ expect(mockSetShowInputFieldPreviewPanel).toHaveBeenCalledWith(false)+ })+ })++ describe('toggleInputFieldEditPanel', () => {+ it('should set edit panel props when given content', () => {+ const editContent = { onSubmit: vi.fn(), onClose: vi.fn() }+ const { result } = renderHook(() => useInputFieldPanel())++ act(() => {+ result.current.toggleInputFieldEditPanel(editContent)+ })++ expect(mockSetInputFieldEditPanelProps).toHaveBeenCalledWith(editContent)+ })++ it('should clear edit panel props when given null', () => {+ const { result } = renderHook(() => useInputFieldPanel())++ act(() => {+ result.current.toggleInputFieldEditPanel(null)+ })++ expect(mockSetInputFieldEditPanelProps).toHaveBeenCalledWith(null)+ })+ })+})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-input-fields.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-input-fields.spec.tsnew file mode 100644index 00000000000..ad6f97a2f4d--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-input-fields.spec.ts@@ -0,0 +1,221 @@+import type { RAGPipelineVariables } from '@/models/pipeline'+import { renderHook } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { BaseFieldType } from '@/app/components/base/form/form-scenarios/base/types'+import { useConfigurations, useInitialData } from '../use-input-fields'++vi.mock('@/models/pipeline', () => ({+ VAR_TYPE_MAP: {+ 'text-input': BaseFieldType.textInput,+ 'paragraph': BaseFieldType.paragraph,+ 'select': BaseFieldType.select,+ 'number': BaseFieldType.numberInput,+ 'checkbox': BaseFieldType.checkbox,+ 'file': BaseFieldType.file,+ 'file-list': BaseFieldType.fileList,+ },+}))++const makeVariable = (overrides: Record<string, unknown> = {}) => ({+ variable: 'test_var',+ label: 'Test Variable',+ type: 'text-input',+ required: true,+ max_length: 100,+ options: undefined,+ placeholder: '',+ tooltips: '',+ unit: '',+ default_value: undefined,+ allowed_file_types: undefined,+ allowed_file_extensions: undefined,+ allowed_file_upload_methods: undefined,+ ...overrides,+})++describe('useInitialData', () => {+ it('should initialize text-input with empty string by default', () => {+ const variables = [makeVariable({ type: 'text-input' })] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.test_var).toBe('')+ })++ it('should initialize paragraph with empty string by default', () => {+ const variables = [makeVariable({ type: 'paragraph', variable: 'para' })] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.para).toBe('')+ })++ it('should initialize select with empty string by default', () => {+ const variables = [makeVariable({ type: 'select', variable: 'sel' })] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.sel).toBe('')+ })++ it('should initialize number with 0 by default', () => {+ const variables = [makeVariable({ type: 'number', variable: 'num' })] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.num).toBe(0)+ })++ it('should initialize checkbox with false by default', () => {+ const variables = [makeVariable({ type: 'checkbox', variable: 'cb' })] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.cb).toBe(false)+ })++ it('should initialize file with empty array by default', () => {+ const variables = [makeVariable({ type: 'file', variable: 'f' })] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.f).toEqual([])+ })++ it('should initialize file-list with empty array by default', () => {+ const variables = [makeVariable({ type: 'file-list', variable: 'fl' })] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.fl).toEqual([])+ })++ it('should use default_value from variable when available', () => {+ const variables = [+ makeVariable({ type: 'text-input', default_value: 'hello' }),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.test_var).toBe('hello')+ })++ it('should prefer lastRunInputData over default_value', () => {+ const variables = [+ makeVariable({ type: 'text-input', default_value: 'default' }),+ ] as unknown as RAGPipelineVariables+ const lastRunInputData = { test_var: 'last-run-value' }+ const { result } = renderHook(() => useInitialData(variables, lastRunInputData))++ expect(result.current.test_var).toBe('last-run-value')+ })++ it('should handle multiple variables', () => {+ const variables = [+ makeVariable({ type: 'text-input', variable: 'name', default_value: 'Alice' }),+ makeVariable({ type: 'number', variable: 'age', default_value: 25 }),+ makeVariable({ type: 'checkbox', variable: 'agree' }),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useInitialData(variables))++ expect(result.current.name).toBe('Alice')+ expect(result.current.age).toBe(25)+ expect(result.current.agree).toBe(false)+ })+})++describe('useConfigurations', () => {+ it('should convert variables to BaseConfiguration format', () => {+ const variables = [+ makeVariable({+ type: 'text-input',+ variable: 'name',+ label: 'Name',+ required: true,+ max_length: 50,+ placeholder: 'Enter name',+ tooltips: 'Your full name',+ unit: '',+ }),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useConfigurations(variables))++ expect(result.current).toHaveLength(1)+ expect(result.current[0]).toMatchObject({+ type: BaseFieldType.textInput,+ variable: 'name',+ label: 'Name',+ required: true,+ maxLength: 50,+ placeholder: 'Enter name',+ tooltip: 'Your full name',+ })+ })++ it('should map select options correctly', () => {+ const variables = [+ makeVariable({+ type: 'select',+ variable: 'color',+ options: ['red', 'green', 'blue'],+ }),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useConfigurations(variables))++ expect(result.current[0].options).toEqual([+ { label: 'red', value: 'red' },+ { label: 'green', value: 'green' },+ { label: 'blue', value: 'blue' },+ ])+ })++ it('should handle undefined options', () => {+ const variables = [+ makeVariable({ type: 'text-input' }),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useConfigurations(variables))++ expect(result.current[0].options).toBeUndefined()+ })++ it('should include file-related fields for file type', () => {+ const variables = [+ makeVariable({+ type: 'file',+ variable: 'doc',+ allowed_file_types: ['pdf', 'docx'],+ allowed_file_extensions: ['.pdf', '.docx'],+ allowed_file_upload_methods: ['local', 'remote'],+ }),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useConfigurations(variables))++ expect(result.current[0].allowedFileTypes).toEqual(['pdf', 'docx'])+ expect(result.current[0].allowedFileExtensions).toEqual(['.pdf', '.docx'])+ expect(result.current[0].allowedFileUploadMethods).toEqual(['local', 'remote'])+ })++ it('should include showConditions as empty array', () => {+ const variables = [+ makeVariable(),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useConfigurations(variables))++ expect(result.current[0].showConditions).toEqual([])+ })++ it('should handle multiple variables', () => {+ const variables = [+ makeVariable({ variable: 'a', type: 'text-input' }),+ makeVariable({ variable: 'b', type: 'number' }),+ makeVariable({ variable: 'c', type: 'checkbox' }),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useConfigurations(variables))++ expect(result.current).toHaveLength(3)+ expect(result.current[0].variable).toBe('a')+ expect(result.current[1].variable).toBe('b')+ expect(result.current[2].variable).toBe('c')+ })++ it('should include unit field', () => {+ const variables = [+ makeVariable({ type: 'number', unit: 'px' }),+ ] as unknown as RAGPipelineVariables+ const { result } = renderHook(() => useConfigurations(variables))++ expect(result.current[0].unit).toBe('px')+ })+})diff --git a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.tssimilarity index 93%rename from web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.tsindex 5788c860d10..82635a75b3d 100644--- a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts@@ -2,17 +2,8 @@ import { renderHook } from '@testing-library/react'import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-// ============================================================================-// Import after mocks-// ============================================================================+import { useNodesSyncDraft } from '../use-nodes-sync-draft'-import { useNodesSyncDraft } from './use-nodes-sync-draft'--// ============================================================================-// Mocks-// ============================================================================--// Mock reactflowconst mockGetNodes = vi.fn()const mockStoreGetState = vi.fn()@@ -22,7 +13,6 @@ vi.mock('reactflow', () => ({}),}))-// Mock workflow storeconst mockWorkflowStoreGetState = vi.fn()vi.mock('@/app/components/workflow/store', () => ({useWorkflowStore: () => ({@@ -30,7 +20,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock useNodesReadOnlyconst mockGetNodesReadOnly = vi.fn()vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({useNodesReadOnly: () => ({@@ -38,7 +27,6 @@ vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({}),}))-// Mock useSerialAsyncCallback - must pass through argumentsvi.mock('@/app/components/workflow/hooks/use-serial-async-callback', () => ({useSerialAsyncCallback: (fn: (...args: unknown[]) => Promise<void>, checkFn: () => boolean) => {return (...args: unknown[]) => {@@ -49,13 +37,11 @@ vi.mock('@/app/components/workflow/hooks/use-serial-async-callback', () => ({},}))-// Mock serviceconst mockSyncWorkflowDraft = vi.fn()vi.mock('@/service/workflow', () => ({syncWorkflowDraft: (params: unknown) => mockSyncWorkflowDraft(params),}))-// Mock usePipelineRefreshDraftconst mockHandleRefreshWorkflowDraft = vi.fn()vi.mock('@/app/components/rag-pipeline/hooks', () => ({usePipelineRefreshDraft: () => ({@@ -63,26 +49,19 @@ vi.mock('@/app/components/rag-pipeline/hooks', () => ({}),}))-// Mock API_PREFIXvi.mock('@/config', () => ({API_PREFIX: '/api',}))-// Mock postWithKeepalive from service/fetchconst mockPostWithKeepalive = vi.fn()vi.mock('@/service/fetch', () => ({postWithKeepalive: (...args: unknown[]) => mockPostWithKeepalive(...args),}))-// ============================================================================-// Tests-// ============================================================================-describe('useNodesSyncDraft', () => {beforeEach(() => {vi.clearAllMocks()- // Default store statemockStoreGetState.mockReturnValue({getNodes: mockGetNodes,edges: [],@@ -204,7 +183,6 @@ describe('useNodesSyncDraft', () => {result.current.syncWorkflowDraftWhenPageClose()})- // Should not call postWithKeepalive because after filtering temp nodes, array is emptyexpect(mockPostWithKeepalive).not.toHaveBeenCalled()})@@ -347,7 +325,6 @@ describe('useNodesSyncDraft', () => {await result.current.doSyncWorkflowDraft(false)})- // Wait for json to be calledawait new Promise(resolve => setTimeout(resolve, 0))expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalled()@@ -371,7 +348,6 @@ describe('useNodesSyncDraft', () => {await result.current.doSyncWorkflowDraft(true)})- // Wait for json to be calledawait new Promise(resolve => setTimeout(resolve, 0))expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-config.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.tssimilarity index 92%rename from web/app/components/rag-pipeline/hooks/use-pipeline-config.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.tsindex 491d2828d88..0b2c68bf68a 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-config.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts@@ -1,17 +1,8 @@import { renderHook } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-// ============================================================================-// Import after mocks-// ============================================================================+import { usePipelineConfig } from '../use-pipeline-config'-import { usePipelineConfig } from './use-pipeline-config'--// ============================================================================-// Mocks-// ============================================================================--// Mock workflow storeconst mockUseStore = vi.fn()const mockWorkflowStoreGetState = vi.fn()@@ -22,27 +13,20 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock useWorkflowConfigconst mockUseWorkflowConfig = vi.fn()vi.mock('@/service/use-workflow', () => ({useWorkflowConfig: (url: string, callback: (data: unknown) => void) => mockUseWorkflowConfig(url, callback),}))-// Mock useDataSourceListconst mockUseDataSourceList = vi.fn()vi.mock('@/service/use-pipeline', () => ({useDataSourceList: (enabled: boolean, callback: (data: unknown) => void) => mockUseDataSourceList(enabled, callback),}))-// Mock basePathvi.mock('@/utils/var', () => ({basePath: '/base',}))-// ============================================================================-// Tests-// ============================================================================-describe('usePipelineConfig', () => {const mockSetNodesDefaultConfigs = vi.fn()const mockSetPublishedAt = vi.fn()@@ -239,7 +223,6 @@ describe('usePipelineConfig', () => {capturedCallback?.(dataSourceList)- // The callback modifies the array in placeexpect(dataSourceList[0].declaration.identity.icon).toBe('/base/icon.png')})@@ -274,7 +257,6 @@ describe('usePipelineConfig', () => {capturedCallback?.(dataSourceList)- // Should not modify object iconexpect(dataSourceList[0].declaration.identity.icon).toEqual({ url: '/icon.png' })})})diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-init.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tssimilarity index 92%rename from web/app/components/rag-pipeline/hooks/use-pipeline-init.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsindex 3938525311c..1ed50e820fc 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-init.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts@@ -1,17 +1,8 @@import { renderHook, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-// ============================================================================-// Import after mocks-// ============================================================================+import { usePipelineInit } from '../use-pipeline-init'-import { usePipelineInit } from './use-pipeline-init'--// ============================================================================-// Mocks-// ============================================================================--// Mock workflow storeconst mockWorkflowStoreGetState = vi.fn()const mockWorkflowStoreSetState = vi.fn()vi.mock('@/app/components/workflow/store', () => ({@@ -21,14 +12,12 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock dataset detail contextconst mockUseDatasetDetailContextWithSelector = vi.fn()vi.mock('@/context/dataset-detail', () => ({useDatasetDetailContextWithSelector: (selector: (state: Record<string, unknown>) => unknown) =>mockUseDatasetDetailContextWithSelector(selector),}))-// Mock workflow serviceconst mockFetchWorkflowDraft = vi.fn()const mockSyncWorkflowDraft = vi.fn()vi.mock('@/service/workflow', () => ({@@ -36,23 +25,17 @@ vi.mock('@/service/workflow', () => ({syncWorkflowDraft: (params: unknown) => mockSyncWorkflowDraft(params),}))-// Mock usePipelineConfig-vi.mock('./use-pipeline-config', () => ({+vi.mock('../use-pipeline-config', () => ({usePipelineConfig: vi.fn(),}))-// Mock usePipelineTemplate-vi.mock('./use-pipeline-template', () => ({+vi.mock('../use-pipeline-template', () => ({usePipelineTemplate: () => ({nodes: [{ id: 'template-node' }],edges: [],}),}))-// ============================================================================-// Tests-// ============================================================================-describe('usePipelineInit', () => {const mockSetEnvSecrets = vi.fn()const mockSetEnvironmentVariables = vi.fn()@@ -283,7 +266,6 @@ describe('usePipelineInit', () => {mockFetchWorkflowDraft.mockRejectedValueOnce(mockJsonError)mockSyncWorkflowDraft.mockResolvedValue({ updated_at: '2024-01-02T00:00:00Z' })- // Second fetch succeedsmockFetchWorkflowDraft.mockResolvedValueOnce({graph: { nodes: [], edges: [], viewport: {} },hash: 'new-hash',diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.tssimilarity index 90%rename from web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.tsindex efdb18b7d46..4ad8bc45827 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts@@ -2,17 +2,8 @@ import { renderHook, waitFor } from '@testing-library/react'import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-// ============================================================================-// Import after mocks-// ============================================================================+import { usePipelineRefreshDraft } from '../use-pipeline-refresh-draft'-import { usePipelineRefreshDraft } from './use-pipeline-refresh-draft'--// ============================================================================-// Mocks-// ============================================================================--// Mock workflow storeconst mockWorkflowStoreGetState = vi.fn()vi.mock('@/app/components/workflow/store', () => ({useWorkflowStore: () => ({@@ -20,7 +11,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock useWorkflowUpdateconst mockHandleUpdateWorkflowCanvas = vi.fn()vi.mock('@/app/components/workflow/hooks', () => ({useWorkflowUpdate: () => ({@@ -28,24 +18,18 @@ vi.mock('@/app/components/workflow/hooks', () => ({}),}))-// Mock workflow serviceconst mockFetchWorkflowDraft = vi.fn()vi.mock('@/service/workflow', () => ({fetchWorkflowDraft: (url: string) => mockFetchWorkflowDraft(url),}))-// Mock utils-vi.mock('../utils', () => ({+vi.mock('../../utils', () => ({processNodesWithoutDataSource: (nodes: unknown[], viewport: unknown) => ({nodes,viewport,}),}))-// ============================================================================-// Tests-// ============================================================================-describe('usePipelineRefreshDraft', () => {const mockSetSyncWorkflowDraftHash = vi.fn()const mockSetIsSyncingWorkflowDraft = vi.fn()diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-run.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.tssimilarity index 95%rename from web/app/components/rag-pipeline/hooks/use-pipeline-run.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.tsindex c8a4a0ebb70..ed6013f1c24 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-run.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts@@ -1,20 +1,11 @@-/* eslint-disable ts/no-explicit-any */+import type { VersionHistory } from '@/types/workflow'import { renderHook } from '@testing-library/react'import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { WorkflowRunningStatus } from '@/app/components/workflow/types'-// ============================================================================-// Import after mocks-// ============================================================================+import { usePipelineRun } from '../use-pipeline-run'-import { usePipelineRun } from './use-pipeline-run'--// ============================================================================-// Mocks-// ============================================================================--// Mock reactflowconst mockStoreGetState = vi.fn()const mockGetViewport = vi.fn()vi.mock('reactflow', () => ({@@ -26,7 +17,6 @@ vi.mock('reactflow', () => ({}),}))-// Mock workflow storeconst mockUseStore = vi.fn()const mockWorkflowStoreGetState = vi.fn()const mockWorkflowStoreSetState = vi.fn()@@ -38,15 +28,13 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock useNodesSyncDraftconst mockDoSyncWorkflowDraft = vi.fn()-vi.mock('./use-nodes-sync-draft', () => ({+vi.mock('../use-nodes-sync-draft', () => ({useNodesSyncDraft: () => ({doSyncWorkflowDraft: mockDoSyncWorkflowDraft,}),}))-// Mock workflow hooksvi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({useSetWorkflowVarsWithValue: () => ({fetchInspectVars: vi.fn(),@@ -80,7 +68,6 @@ vi.mock('@/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run}),}))-// Mock serviceconst mockSsePost = vi.fn()vi.mock('@/service/base', () => ({ssePost: (url: string, ...args: unknown[]) => mockSsePost(url, ...args),@@ -98,17 +85,12 @@ vi.mock('@/service/use-workflow', () => ({useInvalidateWorkflowRunHistory: () => mockInvalidateRunHistory,}))-// Mock FlowTypevi.mock('@/types/common', () => ({FlowType: {ragPipeline: 'rag-pipeline',},}))-// ============================================================================-// Tests-// ============================================================================-describe('usePipelineRun', () => {const mockSetNodes = vi.fn()const mockGetNodes = vi.fn()@@ -120,7 +102,6 @@ describe('usePipelineRun', () => {beforeEach(() => {vi.clearAllMocks()- // Mock DOM elementconst mockWorkflowContainer = document.createElement('div')mockWorkflowContainer.id = 'workflow-container'Object.defineProperty(mockWorkflowContainer, 'clientWidth', { value: 1000 })@@ -318,7 +299,7 @@ describe('usePipelineRun', () => {const { result } = renderHook(() => usePipelineRun())act(() => {- result.current.handleRestoreFromPublishedWorkflow(publishedWorkflow as any)+ result.current.handleRestoreFromPublishedWorkflow(publishedWorkflow as unknown as VersionHistory)})expect(mockHandleUpdateWorkflowCanvas).toHaveBeenCalledWith({@@ -342,7 +323,7 @@ describe('usePipelineRun', () => {const { result } = renderHook(() => usePipelineRun())act(() => {- result.current.handleRestoreFromPublishedWorkflow(publishedWorkflow as any)+ result.current.handleRestoreFromPublishedWorkflow(publishedWorkflow as unknown as VersionHistory)})expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([{ key: 'ENV', value: 'value' }])@@ -362,7 +343,7 @@ describe('usePipelineRun', () => {const { result } = renderHook(() => usePipelineRun())act(() => {- result.current.handleRestoreFromPublishedWorkflow(publishedWorkflow as any)+ result.current.handleRestoreFromPublishedWorkflow(publishedWorkflow as unknown as VersionHistory)})expect(mockSetRagPipelineVariables).toHaveBeenCalledWith([{ variable: 'query', type: 'text-input' }])@@ -382,7 +363,7 @@ describe('usePipelineRun', () => {const { result } = renderHook(() => usePipelineRun())act(() => {- result.current.handleRestoreFromPublishedWorkflow(publishedWorkflow as any)+ result.current.handleRestoreFromPublishedWorkflow(publishedWorkflow as unknown as VersionHistory)})expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([])@@ -468,7 +449,6 @@ describe('usePipelineRun', () => {await result.current.handleRun({ inputs: {} }, { onWorkflowStarted })})- // Trigger the callbackawait act(async () => {capturedCallbacks.onWorkflowStarted?.({ task_id: 'task-1' })})@@ -748,7 +728,6 @@ describe('usePipelineRun', () => {capturedCallbacks.onTextChunk?.({ text: 'chunk' })})- // Just verify it doesn't throwexpect(capturedCallbacks.onTextChunk).toBeDefined()})@@ -769,7 +748,6 @@ describe('usePipelineRun', () => {capturedCallbacks.onTextReplace?.({ text: 'replaced' })})- // Just verify it doesn't throwexpect(capturedCallbacks.onTextReplace).toBeDefined()})@@ -784,7 +762,7 @@ describe('usePipelineRun', () => {const { result } = renderHook(() => usePipelineRun())await act(async () => {- await result.current.handleRun({ inputs: {} }, { onData: customCallback } as any)+ await result.current.handleRun({ inputs: {} }, { onData: customCallback } as unknown as Parameters<typeof result.current.handleRun>[1])})expect(capturedCallbacks.onData).toBeDefined()@@ -799,12 +777,10 @@ describe('usePipelineRun', () => {const { result } = renderHook(() => usePipelineRun())- // Run without any optional callbacksawait act(async () => {await result.current.handleRun({ inputs: {} })})- // Trigger all callbacks - they should not throw even without optional handlersawait act(async () => {capturedCallbacks.onWorkflowStarted?.({ task_id: 'task-1' })capturedCallbacks.onWorkflowFinished?.({ status: 'succeeded' })@@ -823,7 +799,6 @@ describe('usePipelineRun', () => {capturedCallbacks.onTextReplace?.({ text: 'replaced' })})- // Verify ssePost was calledexpect(mockSsePost).toHaveBeenCalled()})})diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-start-run.spec.tssimilarity index 90%rename from web/app/components/rag-pipeline/hooks/use-pipeline-start-run.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-start-run.spec.tsindex 4266fb993df..11a1504c82f 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-start-run.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-start-run.spec.ts@@ -3,17 +3,8 @@ import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { WorkflowRunningStatus } from '@/app/components/workflow/types'-// ============================================================================-// Import after mocks-// ============================================================================+import { usePipelineStartRun } from '../use-pipeline-start-run'-import { usePipelineStartRun } from './use-pipeline-start-run'--// ============================================================================-// Mocks-// ============================================================================--// Mock workflow storeconst mockWorkflowStoreGetState = vi.fn()const mockWorkflowStoreSetState = vi.fn()vi.mock('@/app/components/workflow/store', () => ({@@ -23,7 +14,6 @@ vi.mock('@/app/components/workflow/store', () => ({}),}))-// Mock workflow interactionsconst mockHandleCancelDebugAndPreviewPanel = vi.fn()vi.mock('@/app/components/workflow/hooks', () => ({useWorkflowInteractions: () => ({@@ -31,7 +21,6 @@ vi.mock('@/app/components/workflow/hooks', () => ({}),}))-// Mock useNodesSyncDraftconst mockDoSyncWorkflowDraft = vi.fn()vi.mock('@/app/components/rag-pipeline/hooks', () => ({useNodesSyncDraft: () => ({@@ -42,10 +31,6 @@ vi.mock('@/app/components/rag-pipeline/hooks', () => ({}),}))-// ============================================================================-// Tests-// ============================================================================-describe('usePipelineStartRun', () => {const mockSetIsPreparingDataSource = vi.fn()const mockSetShowEnvPanel = vi.fn()@@ -210,7 +195,6 @@ describe('usePipelineStartRun', () => {result.current.handleStartWorkflowRun()})- // Should trigger the same workflow as handleWorkflowStartRunInWorkflowexpect(mockSetShowEnvPanel).toHaveBeenCalledWith(false)})})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-template.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-template.spec.tsnew file mode 100644index 00000000000..1214ea84c0d--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-template.spec.ts@@ -0,0 +1,61 @@+import { renderHook } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'++import { usePipelineTemplate } from '../use-pipeline-template'++vi.mock('@/app/components/workflow/constants', () => ({+ START_INITIAL_POSITION: { x: 100, y: 200 },+}))++vi.mock('@/app/components/workflow/nodes/knowledge-base/default', () => ({+ default: {+ metaData: { type: 'knowledge-base' },+ defaultValue: { title: 'Knowledge Base' },+ },+}))++vi.mock('@/app/components/workflow/utils', () => ({+ generateNewNode: ({ id, data, position }: { id: string, data: Record<string, unknown>, position: { x: number, y: number } }) => ({+ newNode: { id, data, position, type: 'custom' },+ }),+}))++describe('usePipelineTemplate', () => {+ it('should return nodes array with one knowledge base node', () => {+ const { result } = renderHook(() => usePipelineTemplate())++ expect(result.current.nodes).toHaveLength(1)+ expect(result.current.nodes[0].id).toBe('knowledgeBase')+ })++ it('should return empty edges array', () => {+ const { result } = renderHook(() => usePipelineTemplate())++ expect(result.current.edges).toEqual([])+ })++ it('should set node type from knowledge-base default', () => {+ const { result } = renderHook(() => usePipelineTemplate())++ expect(result.current.nodes[0].data.type).toBe('knowledge-base')+ })++ it('should set node as selected', () => {+ const { result } = renderHook(() => usePipelineTemplate())++ expect(result.current.nodes[0].data.selected).toBe(true)+ })++ it('should position node offset from START_INITIAL_POSITION', () => {+ const { result } = renderHook(() => usePipelineTemplate())++ expect(result.current.nodes[0].position.x).toBe(600)+ expect(result.current.nodes[0].position.y).toBe(200)+ })++ it('should translate node title', () => {+ const { result } = renderHook(() => usePipelineTemplate())++ expect(result.current.nodes[0].data.title).toBe('workflow.blocks.knowledge-base')+ })+})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline.spec.tsnew file mode 100644index 00000000000..bca23fa6020--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline.spec.ts@@ -0,0 +1,321 @@+import { renderHook } from '@testing-library/react'+import { act } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { usePipeline } from '../use-pipeline'++const mockGetNodes = vi.fn()+const mockSetNodes = vi.fn()+const mockEdges: Array<{ id: string, source: string, target: string }> = []++vi.mock('reactflow', () => ({+ useStoreApi: () => ({+ getState: () => ({+ getNodes: mockGetNodes,+ setNodes: mockSetNodes,+ edges: mockEdges,+ }),+ }),+ getOutgoers: (node: { id: string }, nodes: Array<{ id: string }>, edges: Array<{ source: string, target: string }>) => {+ return nodes.filter(n => edges.some(e => e.source === node.id && e.target === n.id))+ },+}))++const mockFindUsedVarNodes = vi.fn()+const mockUpdateNodeVars = vi.fn()+vi.mock('../../../workflow/nodes/_base/components/variable/utils', () => ({+ findUsedVarNodes: (...args: unknown[]) => mockFindUsedVarNodes(...args),+ updateNodeVars: (...args: unknown[]) => mockUpdateNodeVars(...args),+}))++vi.mock('../../../workflow/types', () => ({+ BlockEnum: {+ DataSource: 'data-source',+ },+}))++vi.mock('es-toolkit/compat', () => ({+ uniqBy: (arr: Array<{ id: string }>, key: string) => {+ const seen = new Set<string>()+ return arr.filter((item) => {+ const val = item[key as keyof typeof item] as string+ if (seen.has(val))+ return false+ seen.add(val)+ return true+ })+ },+}))++function createNode(id: string, type: string) {+ return { id, data: { type }, position: { x: 0, y: 0 } }+}++describe('usePipeline', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockEdges.length = 0+ })++ afterEach(() => {+ vi.clearAllMocks()+ })++ describe('hook initialization', () => {+ it('should return handleInputVarRename function', () => {+ mockGetNodes.mockReturnValue([])+ const { result } = renderHook(() => usePipeline())++ expect(result.current.handleInputVarRename).toBeDefined()+ expect(typeof result.current.handleInputVarRename).toBe('function')+ })++ it('should return isVarUsedInNodes function', () => {+ mockGetNodes.mockReturnValue([])+ const { result } = renderHook(() => usePipeline())++ expect(result.current.isVarUsedInNodes).toBeDefined()+ expect(typeof result.current.isVarUsedInNodes).toBe('function')+ })++ it('should return removeUsedVarInNodes function', () => {+ mockGetNodes.mockReturnValue([])+ const { result } = renderHook(() => usePipeline())++ expect(result.current.removeUsedVarInNodes).toBeDefined()+ expect(typeof result.current.removeUsedVarInNodes).toBe('function')+ })+ })++ describe('isVarUsedInNodes', () => {+ it('should return true when variable is used in downstream nodes', () => {+ const dsNode = createNode('ds-1', 'data-source')+ const downstreamNode = createNode('node-2', 'llm')+ mockGetNodes.mockReturnValue([dsNode, downstreamNode])+ mockEdges.push({ id: 'e1', source: 'ds-1', target: 'node-2' })+ mockFindUsedVarNodes.mockReturnValue([downstreamNode])++ const { result } = renderHook(() => usePipeline())++ const isUsed = result.current.isVarUsedInNodes(['rag', 'ds-1', 'var1'])+ expect(isUsed).toBe(true)+ expect(mockFindUsedVarNodes).toHaveBeenCalledWith(+ ['rag', 'ds-1', 'var1'],+ expect.any(Array),+ )+ })++ it('should return false when variable is not used', () => {+ const dsNode = createNode('ds-1', 'data-source')+ mockGetNodes.mockReturnValue([dsNode])+ mockFindUsedVarNodes.mockReturnValue([])++ const { result } = renderHook(() => usePipeline())++ const isUsed = result.current.isVarUsedInNodes(['rag', 'ds-1', 'var1'])+ expect(isUsed).toBe(false)+ })++ it('should handle shared nodeId by collecting all datasource nodes', () => {+ const ds1 = createNode('ds-1', 'data-source')+ const ds2 = createNode('ds-2', 'data-source')+ const node3 = createNode('node-3', 'llm')+ mockGetNodes.mockReturnValue([ds1, ds2, node3])+ mockEdges.push({ id: 'e1', source: 'ds-1', target: 'node-3' })+ mockFindUsedVarNodes.mockReturnValue([node3])++ const { result } = renderHook(() => usePipeline())++ const isUsed = result.current.isVarUsedInNodes(['rag', 'shared', 'var1'])+ expect(isUsed).toBe(true)+ })++ it('should return false for shared nodeId when no datasource nodes exist', () => {+ mockGetNodes.mockReturnValue([createNode('node-1', 'llm')])+ mockFindUsedVarNodes.mockReturnValue([])++ const { result } = renderHook(() => usePipeline())++ const isUsed = result.current.isVarUsedInNodes(['rag', 'shared', 'var1'])+ expect(isUsed).toBe(false)+ })+ })++ describe('handleInputVarRename', () => {+ it('should rename variable in affected nodes', () => {+ const dsNode = createNode('ds-1', 'data-source')+ const node2 = createNode('node-2', 'llm')+ const updatedNode2 = { ...node2, data: { ...node2.data, renamed: true } }+ mockGetNodes.mockReturnValue([dsNode, node2])+ mockEdges.push({ id: 'e1', source: 'ds-1', target: 'node-2' })+ mockFindUsedVarNodes.mockReturnValue([node2])+ mockUpdateNodeVars.mockReturnValue(updatedNode2)++ const { result } = renderHook(() => usePipeline())++ act(() => {+ result.current.handleInputVarRename(+ 'ds-1',+ ['rag', 'ds-1', 'oldVar'],+ ['rag', 'ds-1', 'newVar'],+ )+ })++ expect(mockFindUsedVarNodes).toHaveBeenCalledWith(+ ['rag', 'ds-1', 'oldVar'],+ expect.any(Array),+ )+ expect(mockUpdateNodeVars).toHaveBeenCalledWith(+ node2,+ ['rag', 'ds-1', 'oldVar'],+ ['rag', 'ds-1', 'newVar'],+ )+ expect(mockSetNodes).toHaveBeenCalled()+ })++ it('should not call setNodes when no nodes are affected', () => {+ const dsNode = createNode('ds-1', 'data-source')+ mockGetNodes.mockReturnValue([dsNode])+ mockFindUsedVarNodes.mockReturnValue([])++ const { result } = renderHook(() => usePipeline())++ act(() => {+ result.current.handleInputVarRename(+ 'ds-1',+ ['rag', 'ds-1', 'oldVar'],+ ['rag', 'ds-1', 'newVar'],+ )+ })++ expect(mockSetNodes).not.toHaveBeenCalled()+ })++ it('should only update affected nodes, leave others unchanged', () => {+ const dsNode = createNode('ds-1', 'data-source')+ const node2 = createNode('node-2', 'llm')+ const node3 = createNode('node-3', 'end')+ mockGetNodes.mockReturnValue([dsNode, node2, node3])+ mockEdges.push(+ { id: 'e1', source: 'ds-1', target: 'node-2' },+ { id: 'e2', source: 'node-2', target: 'node-3' },+ )+ mockFindUsedVarNodes.mockReturnValue([node2])+ const updatedNode2 = { ...node2, updated: true }+ mockUpdateNodeVars.mockReturnValue(updatedNode2)++ const { result } = renderHook(() => usePipeline())++ act(() => {+ result.current.handleInputVarRename(+ 'ds-1',+ ['rag', 'ds-1', 'var1'],+ ['rag', 'ds-1', 'var2'],+ )+ })++ const setNodesArg = mockSetNodes.mock.calls[0][0]+ expect(setNodesArg).toContain(dsNode)+ expect(setNodesArg).toContain(updatedNode2)+ expect(setNodesArg).toContain(node3)+ })+ })++ describe('removeUsedVarInNodes', () => {+ it('should remove variable references from affected nodes', () => {+ const dsNode = createNode('ds-1', 'data-source')+ const node2 = createNode('node-2', 'llm')+ const cleanedNode2 = { ...node2, data: { ...node2.data, cleaned: true } }+ mockGetNodes.mockReturnValue([dsNode, node2])+ mockEdges.push({ id: 'e1', source: 'ds-1', target: 'node-2' })+ mockFindUsedVarNodes.mockReturnValue([node2])+ mockUpdateNodeVars.mockReturnValue(cleanedNode2)++ const { result } = renderHook(() => usePipeline())++ act(() => {+ result.current.removeUsedVarInNodes(['rag', 'ds-1', 'var1'])+ })++ expect(mockUpdateNodeVars).toHaveBeenCalledWith(+ node2,+ ['rag', 'ds-1', 'var1'],+ [], // Empty array removes the variable+ )+ expect(mockSetNodes).toHaveBeenCalled()+ })++ it('should not call setNodes when no nodes use the variable', () => {+ const dsNode = createNode('ds-1', 'data-source')+ mockGetNodes.mockReturnValue([dsNode])+ mockFindUsedVarNodes.mockReturnValue([])++ const { result } = renderHook(() => usePipeline())++ act(() => {+ result.current.removeUsedVarInNodes(['rag', 'ds-1', 'var1'])+ })++ expect(mockSetNodes).not.toHaveBeenCalled()+ })+ })++ describe('getAllNodesInSameBranch — edge cases', () => {+ it('should traverse multi-level downstream nodes', () => {+ const ds = createNode('ds-1', 'data-source')+ const n2 = createNode('node-2', 'llm')+ const n3 = createNode('node-3', 'end')+ mockGetNodes.mockReturnValue([ds, n2, n3])+ mockEdges.push(+ { id: 'e1', source: 'ds-1', target: 'node-2' },+ { id: 'e2', source: 'node-2', target: 'node-3' },+ )+ mockFindUsedVarNodes.mockReturnValue([n3])+ mockUpdateNodeVars.mockReturnValue(n3)++ const { result } = renderHook(() => usePipeline())++ const isUsed = result.current.isVarUsedInNodes(['rag', 'ds-1', 'var1'])+ expect(isUsed).toBe(true)++ const nodesArg = mockFindUsedVarNodes.mock.calls[0][1] as Array<{ id: string }>+ const nodeIds = nodesArg.map(n => n.id)+ expect(nodeIds).toContain('ds-1')+ expect(nodeIds).toContain('node-2')+ expect(nodeIds).toContain('node-3')+ })++ it('should return empty array for non-existent node', () => {+ mockGetNodes.mockReturnValue([createNode('ds-1', 'data-source')])+ mockFindUsedVarNodes.mockReturnValue([])++ const { result } = renderHook(() => usePipeline())++ const isUsed = result.current.isVarUsedInNodes(['rag', 'non-existent', 'var1'])+ expect(isUsed).toBe(false)+ })++ it('should deduplicate nodes when traversal finds shared nodes', () => {+ const ds = createNode('ds-1', 'data-source')+ const n2 = createNode('node-2', 'llm')+ const n3 = createNode('node-3', 'llm')+ const n4 = createNode('node-4', 'end')+ mockGetNodes.mockReturnValue([ds, n2, n3, n4])+ mockEdges.push(+ { id: 'e1', source: 'ds-1', target: 'node-2' },+ { id: 'e2', source: 'ds-1', target: 'node-3' },+ { id: 'e3', source: 'node-2', target: 'node-4' },+ { id: 'e4', source: 'node-3', target: 'node-4' },+ )+ mockFindUsedVarNodes.mockReturnValue([])++ const { result } = renderHook(() => usePipeline())++ result.current.isVarUsedInNodes(['rag', 'ds-1', 'var1'])++ const nodesArg = mockFindUsedVarNodes.mock.calls[0][1] as Array<{ id: string }>+ const nodeIds = nodesArg.map(n => n.id)+ const uniqueIds = [...new Set(nodeIds)]+ expect(nodeIds.length).toBe(uniqueIds.length)+ })+ })+})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-rag-pipeline-search.spec.tsx b/web/app/components/rag-pipeline/hooks/__tests__/use-rag-pipeline-search.spec.tsxnew file mode 100644index 00000000000..a06d1ba334b--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-rag-pipeline-search.spec.tsx@@ -0,0 +1,221 @@+import { renderHook } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { BlockEnum } from '@/app/components/workflow/types'+import { useRagPipelineSearch } from '../use-rag-pipeline-search'++const mockNodes: Array<{ id: string, data: Record<string, unknown> }> = []+vi.mock('@/app/components/workflow/store/workflow/use-nodes', () => ({+ default: () => mockNodes,+}))++const mockHandleNodeSelect = vi.fn()+vi.mock('@/app/components/workflow/hooks/use-nodes-interactions', () => ({+ useNodesInteractions: () => ({+ handleNodeSelect: mockHandleNodeSelect,+ }),+}))++vi.mock('@/app/components/workflow/hooks/use-tool-icon', () => ({+ useGetToolIcon: () => () => null,+}))++vi.mock('@/app/components/workflow/block-icon', () => ({+ default: () => null,+}))++type MockSearchResult = {+ title: string+ type: string+ description?: string+ metadata?: { nodeId: string }+}++const mockRagPipelineNodesAction = vi.hoisted(() => {+ return { searchFn: undefined as undefined | ((query: string) => MockSearchResult[]) }+})+vi.mock('@/app/components/goto-anything/actions/rag-pipeline-nodes', () => ({+ ragPipelineNodesAction: mockRagPipelineNodesAction,+}))++const mockCleanupListener = vi.fn()+vi.mock('@/app/components/workflow/utils/node-navigation', () => ({+ setupNodeSelectionListener: () => mockCleanupListener,+}))++describe('useRagPipelineSearch', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockNodes.length = 0+ mockRagPipelineNodesAction.searchFn = undefined+ })++ afterEach(() => {+ vi.clearAllMocks()+ })++ describe('hook lifecycle', () => {+ it('should return null', () => {+ const { result } = renderHook(() => useRagPipelineSearch())+ expect(result.current).toBeNull()+ })++ it('should register search function when nodes exist', () => {+ mockNodes.push({+ id: 'node-1',+ data: { type: BlockEnum.LLM, title: 'LLM Node', desc: '' },+ })++ renderHook(() => useRagPipelineSearch())++ expect(mockRagPipelineNodesAction.searchFn).toBeDefined()+ })++ it('should not register search function when no nodes', () => {+ renderHook(() => useRagPipelineSearch())++ expect(mockRagPipelineNodesAction.searchFn).toBeUndefined()+ })++ it('should cleanup search function on unmount', () => {+ mockNodes.push({+ id: 'node-1',+ data: { type: BlockEnum.Start, title: 'Start', desc: '' },+ })++ const { unmount } = renderHook(() => useRagPipelineSearch())++ expect(mockRagPipelineNodesAction.searchFn).toBeDefined()++ unmount()++ expect(mockRagPipelineNodesAction.searchFn).toBeUndefined()+ })++ it('should setup node selection listener', () => {+ const { unmount } = renderHook(() => useRagPipelineSearch())++ unmount()++ expect(mockCleanupListener).toHaveBeenCalled()+ })+ })++ describe('search functionality', () => {+ beforeEach(() => {+ mockNodes.push(+ {+ id: 'node-1',+ data: { type: BlockEnum.LLM, title: 'GPT Model', desc: 'Language model' },+ },+ {+ id: 'node-2',+ data: { type: BlockEnum.KnowledgeRetrieval, title: 'Knowledge Base', desc: 'Search knowledge', dataset_ids: ['ds1', 'ds2'] },+ },+ {+ id: 'node-3',+ data: { type: BlockEnum.Tool, title: 'Web Search', desc: '', tool_description: 'Search the web', tool_label: 'WebSearch' },+ },+ {+ id: 'node-4',+ data: { type: BlockEnum.Start, title: 'Start Node', desc: 'Pipeline entry' },+ },+ )+ })++ it('should find nodes by title', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('GPT')++ expect(results.length).toBeGreaterThan(0)+ expect(results[0].title).toBe('GPT Model')+ })++ it('should find nodes by type', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn(BlockEnum.LLM)++ expect(results.some(r => r.title === 'GPT Model')).toBe(true)+ })++ it('should find nodes by description', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('knowledge')++ expect(results.some(r => r.title === 'Knowledge Base')).toBe(true)+ })++ it('should return all nodes when search term is empty', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('')++ expect(results.length).toBe(4)+ })++ it('should sort by alphabetical order when no search term', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('')+ const titles = results.map(r => r.title)++ const sortedTitles = [...titles].sort((a, b) => a.localeCompare(b))+ expect(titles).toEqual(sortedTitles)+ })++ it('should sort by relevance score when search term provided', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('Search')++ expect(results[0].title).toBe('Web Search')+ })++ it('should return empty array when no nodes match', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('nonexistent-xyz-12345')++ expect(results).toEqual([])+ })++ it('should enhance Tool node description from tool_description', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('web')++ const toolResult = results.find(r => r.title === 'Web Search')+ expect(toolResult).toBeDefined()+ expect(toolResult?.description).toContain('Search the web')+ })++ it('should include metadata with nodeId', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('Start')++ const startResult = results.find(r => r.title === 'Start Node')+ expect(startResult?.metadata?.nodeId).toBe('node-4')+ })++ it('should set result type as workflow-node', () => {+ renderHook(() => useRagPipelineSearch())++ const searchFn = mockRagPipelineNodesAction.searchFn!+ const results = searchFn('Start')++ expect(results[0].type).toBe('workflow-node')+ })+ })+})diff --git a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.tssimilarity index 94%rename from web/app/components/rag-pipeline/hooks/use-update-dsl-modal.spec.tsrename to web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.tsindex adf756c10f0..942e337ad88 100644--- a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts@@ -1,9 +1,8 @@import { act, renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { DSLImportMode, DSLImportStatus } from '@/models/app'-import { useUpdateDSLModal } from './use-update-dsl-modal'+import { useUpdateDSLModal } from '../use-update-dsl-modal'-// --- FileReader stub ---class MockFileReader {onload: ((this: FileReader, event: ProgressEvent<FileReader>) => void) | null = null@@ -14,18 +13,12 @@ class MockFileReader {}vi.stubGlobal('FileReader', MockFileReader as unknown as typeof FileReader)-// --- Module-level mock functions ---const mockNotify = vi.fn()const mockEmit = vi.fn()const mockImportDSL = vi.fn()const mockImportDSLConfirm = vi.fn()const mockHandleCheckPluginDependencies = vi.fn()-// --- Mocks ----vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}))-vi.mock('use-context-selector', () => ({useContext: () => ({ notify: mockNotify }),}))@@ -74,10 +67,8 @@ vi.mock('@/service/workflow', () => ({}),}))-// --- Helpers ---const createFile = () => new File(['test content'], 'test.pipeline', { type: 'text/yaml' })-// Cast MouseEventHandler to a plain callable for tests (event param is unused)type AsyncFn = () => Promise<void>describe('useUpdateDSLModal', () => {@@ -102,7 +93,6 @@ describe('useUpdateDSLModal', () => {mockHandleCheckPluginDependencies.mockResolvedValue(undefined)})- // Initial state valuesdescribe('initial state', () => {it('should return correct defaults', () => {const { result } = renderUpdateDSLModal()@@ -115,7 +105,6 @@ describe('useUpdateDSLModal', () => {})})- // File handlingdescribe('handleFile', () => {it('should set currentFile when file is provided', () => {const { result } = renderUpdateDSLModal()@@ -142,7 +131,6 @@ describe('useUpdateDSLModal', () => {})})- // Modal state managementdescribe('modal state', () => {it('should allow toggling showErrorModal', () => {const { result } = renderUpdateDSLModal()@@ -161,7 +149,6 @@ describe('useUpdateDSLModal', () => {})})- // Import flowdescribe('handleImport', () => {it('should call importDSL with correct parameters', async () => {const { result } = renderUpdateDSLModal()@@ -191,7 +178,6 @@ describe('useUpdateDSLModal', () => {expect(mockImportDSL).not.toHaveBeenCalled()})- // COMPLETED statusit('should notify success on COMPLETED status', async () => {const { result } = renderUpdateDSLModal()act(() => {@@ -257,7 +243,6 @@ describe('useUpdateDSLModal', () => {expect(mockHandleCheckPluginDependencies).toHaveBeenCalledWith('test-pipeline-id', true)})- // COMPLETED_WITH_WARNINGS statusit('should notify warning on COMPLETED_WITH_WARNINGS status', async () => {mockImportDSL.mockResolvedValue({id: 'import-id',@@ -277,7 +262,6 @@ describe('useUpdateDSLModal', () => {expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'warning' }))})- // PENDING status (version mismatch)it('should switch to version mismatch modal on PENDING status', async () => {vi.useFakeTimers({ shouldAdvanceTime: true })@@ -338,7 +322,6 @@ describe('useUpdateDSLModal', () => {vi.useRealTimers()})- // FAILED / unknown statusit('should notify error on FAILED status', async () => {mockImportDSL.mockResolvedValue({id: 'import-id',@@ -358,7 +341,6 @@ describe('useUpdateDSLModal', () => {expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})- // Exceptionit('should notify error when importDSL throws', async () => {mockImportDSL.mockRejectedValue(new Error('Network error'))@@ -374,7 +356,6 @@ describe('useUpdateDSLModal', () => {expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))})- // Missing pipeline_idit('should notify error when pipeline_id is missing on success', async () => {mockImportDSL.mockResolvedValue({id: 'import-id',@@ -395,9 +376,7 @@ describe('useUpdateDSLModal', () => {})})- // Confirm flow (after PENDING → version mismatch)describe('onUpdateDSLConfirm', () => {- // Helper: drive the hook into PENDING state so importId is setconst setupPendingState = async (result: { current: ReturnType<typeof useUpdateDSLModal> }) => {vi.useFakeTimers({ shouldAdvanceTime: true })@@ -520,7 +499,6 @@ describe('useUpdateDSLModal', () => {it('should not call importDSLConfirm when importId is not set', async () => {const { result } = renderUpdateDSLModal()- // No pending state → importId is undefinedawait act(async () => {await (result.current.onUpdateDSLConfirm as unknown as AsyncFn)()})@@ -529,7 +507,6 @@ describe('useUpdateDSLModal', () => {})})- // Optional onImport callbackdescribe('optional onImport', () => {it('should work without onImport callback', async () => {const { result } = renderHook(() =>@@ -544,7 +521,6 @@ describe('useUpdateDSLModal', () => {await (result.current.handleImport as unknown as AsyncFn)()})- // Should succeed without throwingexpect(mockOnCancel).toHaveBeenCalled()})})diff --git a/web/app/components/rag-pipeline/store/index.spec.ts b/web/app/components/rag-pipeline/store/__tests__/index.spec.tssimilarity index 65%rename from web/app/components/rag-pipeline/store/index.spec.tsrename to web/app/components/rag-pipeline/store/__tests__/index.spec.tsindex c8c0a35330b..c978332a717 100644--- a/web/app/components/rag-pipeline/store/index.spec.ts+++ b/web/app/components/rag-pipeline/store/__tests__/index.spec.ts@@ -1,9 +1,12 @@-/* eslint-disable ts/no-explicit-any */+import type { InputFieldEditorProps } from '../../components/panel/input-field/editor'+import type { RagPipelineSliceShape } from '../index'import type { DataSourceItem } from '@/app/components/workflow/block-selector/types'+import type { RAGPipelineVariables } from '@/models/pipeline'import { describe, expect, it, vi } from 'vitest'-import { createRagPipelineSliceSlice } from './index'+import { PipelineInputVarType } from '@/models/pipeline'++import { createRagPipelineSliceSlice } from '../index'-// Mock the transformDataSourceToTool functionvi.mock('@/app/components/workflow/block-selector/utils', () => ({transformDataSourceToTool: (item: DataSourceItem) => ({...item,@@ -11,60 +14,68 @@ vi.mock('@/app/components/workflow/block-selector/utils', () => ({}),}))+type SliceCreatorParams = Parameters<typeof createRagPipelineSliceSlice>+const unusedGet = vi.fn() as unknown as SliceCreatorParams[1]+const unusedApi = vi.fn() as unknown as SliceCreatorParams[2]++function createSlice(mockSet = vi.fn()) {+ return createRagPipelineSliceSlice(mockSet as unknown as SliceCreatorParams[0], unusedGet, unusedApi)+}+describe('createRagPipelineSliceSlice', () => {const mockSet = vi.fn()describe('initial state', () => {it('should have empty pipelineId', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.pipelineId).toBe('')})it('should have empty knowledgeName', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.knowledgeName).toBe('')})it('should have showInputFieldPanel as false', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.showInputFieldPanel).toBe(false)})it('should have showInputFieldPreviewPanel as false', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.showInputFieldPreviewPanel).toBe(false)})it('should have inputFieldEditPanelProps as null', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.inputFieldEditPanelProps).toBeNull()})it('should have empty nodesDefaultConfigs', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.nodesDefaultConfigs).toEqual({})})it('should have empty ragPipelineVariables', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.ragPipelineVariables).toEqual([])})it('should have empty dataSourceList', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.dataSourceList).toEqual([])})it('should have isPreparingDataSource as false', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)expect(slice.isPreparingDataSource).toBe(false)})@@ -72,25 +83,24 @@ describe('createRagPipelineSliceSlice', () => {describe('setShowInputFieldPanel', () => {it('should call set with showInputFieldPanel true', () => {- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setShowInputFieldPanel(true)expect(mockSet).toHaveBeenCalledWith(expect.any(Function))- // Get the setter function and execute it- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ showInputFieldPanel: true })})it('should call set with showInputFieldPanel false', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setShowInputFieldPanel(false)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ showInputFieldPanel: false })})@@ -99,22 +109,22 @@ describe('createRagPipelineSliceSlice', () => {describe('setShowInputFieldPreviewPanel', () => {it('should call set with showInputFieldPreviewPanel true', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setShowInputFieldPreviewPanel(true)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ showInputFieldPreviewPanel: true })})it('should call set with showInputFieldPreviewPanel false', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setShowInputFieldPreviewPanel(false)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ showInputFieldPreviewPanel: false })})@@ -123,23 +133,23 @@ describe('createRagPipelineSliceSlice', () => {describe('setInputFieldEditPanelProps', () => {it('should call set with inputFieldEditPanelProps object', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)- const props = { type: 'create' as const }+ const slice = createSlice(mockSet)+ const props = { onClose: vi.fn(), onSubmit: vi.fn() } as unknown as InputFieldEditorProps- slice.setInputFieldEditPanelProps(props as any)+ slice.setInputFieldEditPanelProps(props)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ inputFieldEditPanelProps: props })})it('should call set with inputFieldEditPanelProps null', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setInputFieldEditPanelProps(null)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ inputFieldEditPanelProps: null })})@@ -148,23 +158,23 @@ describe('createRagPipelineSliceSlice', () => {describe('setNodesDefaultConfigs', () => {it('should call set with nodesDefaultConfigs', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)- const configs = { node1: { key: 'value' } }+ const slice = createSlice(mockSet)+ const configs: Record<string, unknown> = { node1: { key: 'value' } }slice.setNodesDefaultConfigs(configs)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ nodesDefaultConfigs: configs })})it('should call set with empty nodesDefaultConfigs', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setNodesDefaultConfigs({})- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ nodesDefaultConfigs: {} })})@@ -173,25 +183,25 @@ describe('createRagPipelineSliceSlice', () => {describe('setRagPipelineVariables', () => {it('should call set with ragPipelineVariables', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)- const variables = [- { type: 'text-input', variable: 'var1', label: 'Var 1', required: true },+ const slice = createSlice(mockSet)+ const variables: RAGPipelineVariables = [+ { type: PipelineInputVarType.textInput, variable: 'var1', label: 'Var 1', required: true, belong_to_node_id: 'node-1' },]- slice.setRagPipelineVariables(variables as any)+ slice.setRagPipelineVariables(variables)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ ragPipelineVariables: variables })})it('should call set with empty ragPipelineVariables', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setRagPipelineVariables([])- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ ragPipelineVariables: [] })})@@ -200,7 +210,7 @@ describe('createRagPipelineSliceSlice', () => {describe('setDataSourceList', () => {it('should transform and set dataSourceList', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)const dataSourceList: DataSourceItem[] = [{ name: 'source1', key: 'key1' } as unknown as DataSourceItem,{ name: 'source2', key: 'key2' } as unknown as DataSourceItem,@@ -208,20 +218,20 @@ describe('createRagPipelineSliceSlice', () => {slice.setDataSourceList(dataSourceList)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result.dataSourceList).toHaveLength(2)- expect(result.dataSourceList[0]).toEqual({ name: 'source1', key: 'key1', transformed: true })- expect(result.dataSourceList[1]).toEqual({ name: 'source2', key: 'key2', transformed: true })+ expect(result.dataSourceList![0]).toEqual({ name: 'source1', key: 'key1', transformed: true })+ expect(result.dataSourceList![1]).toEqual({ name: 'source2', key: 'key2', transformed: true })})it('should set empty dataSourceList', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setDataSourceList([])- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result.dataSourceList).toEqual([])})@@ -230,22 +240,22 @@ describe('createRagPipelineSliceSlice', () => {describe('setIsPreparingDataSource', () => {it('should call set with isPreparingDataSource true', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setIsPreparingDataSource(true)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ isPreparingDataSource: true })})it('should call set with isPreparingDataSource false', () => {mockSet.mockClear()- const slice = createRagPipelineSliceSlice(mockSet, vi.fn() as any, vi.fn() as any)+ const slice = createSlice(mockSet)slice.setIsPreparingDataSource(false)- const setterFn = mockSet.mock.calls[0][0]+ const setterFn = mockSet.mock.calls[0][0] as () => Partial<RagPipelineSliceShape>const result = setterFn()expect(result).toEqual({ isPreparingDataSource: false })})@@ -254,9 +264,8 @@ describe('createRagPipelineSliceSlice', () => {describe('RagPipelineSliceShape type', () => {it('should define all required properties', () => {- const slice = createRagPipelineSliceSlice(vi.fn(), vi.fn() as any, vi.fn() as any)+ const slice = createSlice()- // Check all properties existexpect(slice).toHaveProperty('pipelineId')expect(slice).toHaveProperty('knowledgeName')expect(slice).toHaveProperty('showInputFieldPanel')@@ -276,7 +285,7 @@ describe('RagPipelineSliceShape type', () => {})it('should have all setters as functions', () => {- const slice = createRagPipelineSliceSlice(vi.fn(), vi.fn() as any, vi.fn() as any)+ const slice = createSlice()expect(typeof slice.setShowInputFieldPanel).toBe('function')expect(typeof slice.setShowInputFieldPreviewPanel).toBe('function')diff --git a/web/app/components/rag-pipeline/utils/index.spec.ts b/web/app/components/rag-pipeline/utils/__tests__/index.spec.tssimilarity index 93%rename from web/app/components/rag-pipeline/utils/index.spec.tsrename to web/app/components/rag-pipeline/utils/__tests__/index.spec.tsindex 9d816af685d..787cc018b9f 100644--- a/web/app/components/rag-pipeline/utils/index.spec.ts+++ b/web/app/components/rag-pipeline/utils/__tests__/index.spec.ts@@ -2,9 +2,8 @@ import type { Viewport } from 'reactflow'import type { Node } from '@/app/components/workflow/types'import { describe, expect, it, vi } from 'vitest'import { BlockEnum } from '@/app/components/workflow/types'-import { processNodesWithoutDataSource } from './nodes'+import { processNodesWithoutDataSource } from '../nodes'-// Mock constantsvi.mock('@/app/components/workflow/constants', () => ({CUSTOM_NODE: 'custom',NODE_WIDTH_X_OFFSET: 400,@@ -121,8 +120,6 @@ describe('processNodesWithoutDataSource', () => {const result = processNodesWithoutDataSource(nodes, viewport)- // New nodes should be positioned based on the leftmost node (x: 200)- // startX = 200 - 400 = -200expect(result.nodes[0].position.x).toBe(-200)expect(result.nodes[0].position.y).toBe(100)})@@ -140,10 +137,6 @@ describe('processNodesWithoutDataSource', () => {const result = processNodesWithoutDataSource(nodes, viewport)- // startX = 300 - 400 = -100- // startY = 200- // viewport.x = (100 - (-100)) * 1 = 200- // viewport.y = (100 - 200) * 1 = -100expect(result.viewport).toEqual({x: 200,y: -100,@@ -164,10 +157,6 @@ describe('processNodesWithoutDataSource', () => {const result = processNodesWithoutDataSource(nodes, viewport)- // startX = 300 - 400 = -100- // startY = 200- // viewport.x = (100 - (-100)) * 2 = 400- // viewport.y = (100 - 200) * 2 = -200expect(result.viewport).toEqual({x: 400,y: -200,@@ -202,7 +191,6 @@ describe('processNodesWithoutDataSource', () => {const result = processNodesWithoutDataSource(nodes)- // Data source empty node positionconst dataSourceEmptyNode = result.nodes[0]const noteNode = result.nodes[1]@@ -276,7 +264,6 @@ describe('processNodesWithoutDataSource', () => {const result = processNodesWithoutDataSource(nodes, viewport)- // No custom nodes to find leftmost, so no new nodes are addedexpect(result.nodes).toBe(nodes)expect(result.viewport).toBe(viewport)})@@ -301,7 +288,6 @@ describe('processNodesWithoutDataSource', () => {const result = processNodesWithoutDataSource(nodes)- // First node should be used as leftNodeexpect(result.nodes.length).toBe(4)})@@ -317,7 +303,6 @@ describe('processNodesWithoutDataSource', () => {const result = processNodesWithoutDataSource(nodes)- // startX = -100 - 400 = -500expect(result.nodes[0].position.x).toBe(-500)expect(result.nodes[0].position.y).toBe(-50)})diff --git a/web/eslint-suppressions.json b/web/eslint-suppressions.jsonindex eff3e27589c..90571e49472 100644--- a/web/eslint-suppressions.json+++ b/web/eslint-suppressions.json@@ -5359,11 +5359,6 @@"count": 3}},- "app/components/rag-pipeline/components/panel/input-field/field-list/index.spec.tsx": {- "ts/no-explicit-any": {- "count": 1- }- },"app/components/rag-pipeline/components/panel/input-field/hooks.ts": {"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 1@@ -5523,11 +5518,6 @@"count": 1}},- "app/components/rag-pipeline/index.spec.tsx": {- "ts/no-explicit-any": {- "count": 8- }- },"app/components/rag-pipeline/store/index.ts": {"ts/no-explicit-any": {"count": 2