Skip to content

armgit / dify

Public Imported from GitHub
0

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.

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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.tsx
similarity index 86%
rename from web/app/components/rag-pipeline/index.spec.tsx
rename to web/app/components/rag-pipeline/__tests__/index.spec.tsx
index 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 manipulation
import { 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 values
vi.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 providers
vi.mock('@/app/components/workflow', () => ({
default: ({ children }: { children: React.ReactNode }) => (
<div data-testid="workflow-default-context">{children}</div>
),
}))
-// Mock: Context provider
vi.mock('@/app/components/workflow/context', () => ({
WorkflowContextProvider: ({ children }: { children: React.ReactNode }) => (
<div data-testid="workflow-context-provider">{children}</div>
),
}))
-// Type assertions for mocked functions
const 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_id
const 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 factory
const createMockWorkflowData = (overrides?: Partial<FetchWorkflowDraftResponse>): FetchWorkflowDraftResponse => ({
graph: {
nodes: [
@@ -157,7 +142,6 @@ describe('RagPipelineWrapper', () => {
describe('RagPipeline', () => {
beforeEach(() => {
- // Default setup for RagPipeline tests - execute real selector function
mockSelectorWithDataset('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 data
expect(screen.getByTestId('rag-pipeline-main')).toBeInTheDocument()
})
@@ -251,7 +232,6 @@ describe('RagPipeline', () => {
render(<RagPipelineWrapper />)
- // initialEdges is a real function - verify component renders with edges
expect(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 called
expect(mockProcessNodesWithoutDataSource).not.toHaveBeenCalled()
})
@@ -279,13 +258,10 @@ describe('RagPipeline', () => {
const { rerender } = render(<RagPipelineWrapper />)
- // Clear mock call count after initial render
mockProcessNodesWithoutDataSource.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 excessive
expect(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 state
mockUsePipelineInit.mockReturnValue({ data: undefined, isLoading: true })
const { rerender } = render(<RagPipelineWrapper />)
- // Real Loading component has role="status"
expect(screen.getByRole('status')).toBeInTheDocument()
- // Transition to loaded state
const 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 pipelineId
mockSelectorWithDataset(null)
mockUsePipelineInit.mockReturnValue({ data: undefined, isLoading: false })
@@ -491,13 +463,11 @@ describe('Conditional Rendering Flow', () => {
expect(screen.getByTestId('conversion-component')).toBeInTheDocument()
- // PipelineId becomes available
mockSelectorWithDataset('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 FetchWorkflowDraftResponse
mockUsePipelineInit.mockReturnValue({ data: mockData, isLoading: false })
- // Suppress console.error for expected error
const 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 array
expect(() => render(<RagPipelineWrapper />)).toThrow()
consoleSpy.mockRestore()
@@ -538,11 +505,8 @@ describe('Error Handling', () => {
mockUsePipelineInit.mockReturnValue({ data: mockData, isLoading: false })
- // Suppress console.error for expected error
const 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 present
expect(() => 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.tsx
new file mode 100644
index 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.tsx
similarity index 82%
rename from web/app/components/rag-pipeline/components/index.spec.tsx
rename to web/app/components/rag-pipeline/components/__tests__/index.spec.tsx
index 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/image
vi.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/dynamic
vi.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 state
let mockShowImportDSLModal = false
const 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.hoisted
const {
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-vars
vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({
useSetWorkflowVarsWithValue: () => ({
fetchInspectVars: vi.fn(),
}),
}))
-// Mock service hooks - with controllable convert function
let mockConvertFn = vi.fn()
let mockIsPending = false
vi.mock('@/service/use-pipeline', () => ({
@@ -253,7 +234,6 @@ vi.mock('@/service/workflow', () => ({
}),
}))
-// Mock event emitter context - with controllable subscription
let mockEventSubscriptionCallback: ((v: { type: string, payload?: { data?: EnvironmentVariable[] } }) => void) | null = null
const mockUseSubscription = vi.fn((callback: (v: { type: string, payload?: { data?: EnvironmentVariable[] } }) => void) => {
mockEventSubscriptionCallback = callback
@@ -267,7 +247,6 @@ vi.mock('@/context/event-emitter', () => ({
}),
}))
-// Mock toast
vi.mock('@/app/components/base/toast', () => ({
default: {
notify: vi.fn(),
@@ -280,33 +259,28 @@ vi.mock('@/app/components/base/toast', () => ({
},
}))
-// Mock useTheme hook
vi.mock('@/hooks/use-theme', () => ({
default: () => ({
theme: 'light',
}),
}))
-// Mock basePath
vi.mock('@/utils/var', () => ({
basePath: '/public',
}))
-// Mock provider context
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => createMockProviderContextValue(),
useProviderContextSelector: <T,>(selector: (state: ReturnType<typeof createMockProviderContextValue>) => T): T =>
selector(createMockProviderContextValue()),
}))
-// Mock WorkflowWithInnerContext
vi.mock('@/app/components/workflow', () => ({
WorkflowWithInnerContext: ({ children }: PropsWithChildren) => (
<div data-testid="workflow-inner-context">{children}</div>
),
}))
-// Mock workflow panel
vi.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 hooks
vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({
usePluginDependencies: () => ({
handleCheckPluginDependencies: vi.fn().mockResolvedValue(undefined),
}),
}))
-// Mock DSLExportConfirmModal
vi.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 constants
vi.mock('@/app/components/workflow/constants', () => ({
DSL_EXPORT_CHECK: 'DSL_EXPORT_CHECK',
WORKFLOW_DATA_UPDATE: 'WORKFLOW_DATA_UPDATE',
}))
-// Mock workflow utils
vi.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 component
vi.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 component
vi.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 component
vi.mock('@/app/components/base/input', () => ({
default: ({ value, onChange, placeholder }: {
value: string
@@ -412,7 +378,6 @@ vi.mock('@/app/components/base/input', () => ({
),
}))
-// Mock Textarea component
vi.mock('@/app/components/base/textarea', () => ({
default: ({ value, onChange, placeholder, className }: {
value: string
@@ -430,7 +395,6 @@ vi.mock('@/app/components/base/textarea', () => ({
),
}))
-// Mock AppIcon component
vi.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 component
vi.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 component
vi.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-selector
vi.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: () => void
onBackup: () => void
@@ -536,7 +494,6 @@ vi.mock('./update-dsl-modal', () => ({
),
}))
-// Mock DSLExportConfirmModal for RagPipelineChildren tests
vi.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 modal
const convertButton = screen.getByRole('button', { name: /datasetPipeline\.operations\.convert/i })
fireEvent.click(convertButton)
expect(screen.getByTestId('confirm-modal')).toBeInTheDocument()
- // Cancel modal
fireEvent.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 callback
mockConvertFn.mockImplementation((_datasetId: string, options: { onSuccess: (res: { status: string }) => void }) => {
options.onSuccess({ status: 'success' })
})
render(<Conversion />)
- // Open modal and confirm
const 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 failed
expect(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.memo
expect((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 callback
rerender(<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 crashing
expect(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 mock
expect(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 import
expect(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 values
fireEvent.change(screen.getByTestId('input'), { target: { value: ' Trimmed Name ' } })
fireEvent.change(screen.getByTestId('textarea'), { target: { value: ' Trimmed Description ' } })
- // Click publish
fireEvent.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 picker
fireEvent.click(screen.getByTestId('app-icon'))
- // Select emoji
fireEvent.click(screen.getByTestId('select-emoji'))
- // Picker should close
expect(screen.queryByTestId('app-icon-picker')).not.toBeInTheDocument()
})
it('should update icon when image is selected', () => {
render(<PublishAsKnowledgePipelineModal {...defaultProps} />)
- // Open picker
fireEvent.click(screen.getByTestId('app-icon'))
- // Select image
fireEvent.click(screen.getByTestId('select-image'))
- // Picker should close
expect(screen.queryByTestId('app-icon-picker')).not.toBeInTheDocument()
})
it('should close picker and restore icon when picker is closed', () => {
render(<PublishAsKnowledgePipelineModal {...defaultProps} />)
- // Open picker
fireEvent.click(screen.getByTestId('app-icon'))
expect(screen.getByTestId('app-icon-picker')).toBeInTheDocument()
- // Close picker
fireEvent.click(screen.getByTestId('close-picker'))
- // Picker should close
expect(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 name
fireEvent.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 name
fireEvent.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 issues
rerender(<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 event
const mockEnvVariables: EnvironmentVariable[] = [
{ id: '1', name: 'SECRET_KEY', value: 'test-secret', value_type: 'secret' as const, description: '' },
]
- // Trigger the subscription callback
if (mockEventSubscriptionCallback) {
mockEventSubscriptionCallback({
type: 'DSL_EXPORT_CHECK',
@@ -1116,7 +992,6 @@ describe('RagPipelineChildren', () => {
})
}
- // DSLExportConfirmModal should be rendered
await 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 type
if (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 secrets
const 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 modal
const 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 modal
fireEvent.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 modal
const 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 export
fireEvent.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 name
fireEvent.change(screen.getByTestId('input'), { target: { value: 'My Pipeline' } })
- // Add description
fireEvent.change(screen.getByTestId('textarea'), { target: { value: 'A great pipeline' } })
- // Change icon
fireEvent.click(screen.getByTestId('app-icon'))
fireEvent.click(screen.getByTestId('select-emoji'))
- // Publish
fireEvent.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 name
const 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.tsx
new file mode 100644
index 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.tsx
similarity index 69%
rename from web/app/components/rag-pipeline/components/publish-toast.spec.tsx
rename to web/app/components/rag-pipeline/components/__tests__/publish-toast.spec.tsx
index 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 state
let mockPublishedAt = 0
vi.mock('@/app/components/workflow/store', () => ({
useStore: (selector: (state: Record<string, unknown>) => unknown) => {
@@ -32,19 +24,19 @@ describe('PublishToast', () => {
mockPublishedAt = 0
render(<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 rendered
const 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 button
const 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 button
const 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 button
const 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.tsx
similarity index 94%
rename from web/app/components/rag-pipeline/components/rag-pipeline-main.spec.tsx
rename to web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsx
index 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 store
const 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 hooks
vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({
useSetWorkflowVarsWithValue: () => ({
fetchInspectVars: vi.fn(),
}),
}))
-// Mock WorkflowWithInnerContext
vi.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 successfully
expect(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.tsx
similarity index 77%
rename from web/app/components/rag-pipeline/components/update-dsl-modal.spec.tsx
rename to web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
index 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-selector
const mockNotify = vi.fn()
vi.mock('use-context-selector', () => ({
useContext: () => ({ notify: mockNotify }),
}))
-// Mock toast context
vi.mock('@/app/components/base/toast', () => ({
ToastContext: { Provider: ({ children }: PropsWithChildren) => children },
}))
-// Mock event emitter
const mockEmit = vi.fn()
vi.mock('@/context/event-emitter', () => ({
useEventEmitterContextContext: () => ({
@@ -41,7 +31,6 @@ vi.mock('@/context/event-emitter', () => ({
}),
}))
-// Mock workflow store
vi.mock('@/app/components/workflow/store', () => ({
useWorkflowStore: () => ({
getState: () => ({
@@ -50,13 +39,11 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-// Mock workflow utils
vi.mock('@/app/components/workflow/utils', () => ({
initialNodes: (nodes: unknown[]) => nodes,
initialEdges: (edges: unknown[]) => edges,
}))
-// Mock plugin dependencies
const 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 service
const 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 service
vi.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 Uploader
vi.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 Button
vi.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 Modal
vi.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 constants
vi.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 processed
await waitFor(() => {
expect(screen.getByTestId('uploader')).toBeInTheDocument()
})
@@ -261,14 +235,12 @@ describe('UpdateDSLModal', () => {
const clearButton = screen.getByTestId('clear-file')
fireEvent.click(clearButton)
- // File should be cleared
expect(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 file
const 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 file
const 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 file
const 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 process
await 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 called
await waitFor(() => {
expect(mockImportDSL).toHaveBeenCalled()
})
@@ -392,17 +357,16 @@ describe('UpdateDSLModal', () => {
render(<UpdateDSLModal {...defaultProps} />)
- // Select a file and click import
const 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 enabled
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(() => {
@@ -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 enabled
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(() => {
@@ -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 set
await 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 mockImportDSL
await Promise.resolve()
- // Advance past the 300ms setTimeout in the component
await 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 info
await 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 modal
await 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 closed
await 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 mockImportDSL
await Promise.resolve()
- // Advance past the 300ms setTimeout in the component
await 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 mockImportDSL
await Promise.resolve()
- // Advance past the 300ms setTimeout in the component
await 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 versions
await 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 first
render(<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 flow
expect(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.tsx
similarity index 98%
rename from web/app/components/rag-pipeline/components/version-mismatch-modal.spec.tsx
rename to web/app/components/rag-pipeline/components/__tests__/version-mismatch-modal.spec.tsx
index 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.tsx
new file mode 100644
index 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.tsx
similarity index 83%
rename from web/app/components/rag-pipeline/components/chunk-card-list/index.spec.tsx
rename to web/app/components/rag-pipeline/components/chunk-card-list/__tests__/index.spec.tsx
index 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 component
describe('Rendering', () => {
it('should render question type with Q prefix', () => {
- // Arrange & Act
render(<QAItem type={QAItemType.Question} text="What is this?" />)
- // Assert
expect(screen.getByText('Q')).toBeInTheDocument()
expect(screen.getByText('What is this?')).toBeInTheDocument()
})
it('should render answer type with A prefix', () => {
- // Arrange & Act
render(<QAItem type={QAItemType.Answer} text="This is the answer." />)
- // Assert
expect(screen.getByText('A')).toBeInTheDocument()
expect(screen.getByText('This is the answer.')).toBeInTheDocument()
})
})
- // Tests for different prop variations
describe('Props', () => {
it('should render with empty text', () => {
- // Arrange & Act
render(<QAItem type={QAItemType.Question} text="" />)
- // Assert
expect(screen.getByText('Q')).toBeInTheDocument()
})
it('should render with long text content', () => {
- // Arrange
const longText = 'A'.repeat(1000)
- // Act
render(<QAItem type={QAItemType.Answer} text={longText} />)
- // Assert
expect(screen.getByText(longText)).toBeInTheDocument()
})
it('should render with special characters in text', () => {
- // Arrange
const specialText = '<script>alert("xss")</script> & "quotes" \'apostrophe\''
- // Act
render(<QAItem type={QAItemType.Question} text={specialText} />)
- // Assert
expect(screen.getByText(specialText)).toBeInTheDocument()
})
})
- // Tests for memoization behavior
describe('Memoization', () => {
it('should be memoized with React.memo', () => {
- // Arrange & Act
const { rerender } = render(<QAItem type={QAItemType.Question} text="Test" />)
- // Assert - component should render consistently
expect(screen.getByText('Q')).toBeInTheDocument()
expect(screen.getByText('Test')).toBeInTheDocument()
- // Rerender with same props - should not cause issues
rerender(<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 types
describe('Rendering', () => {
it('should render text chunk type correctly', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -158,19 +126,16 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(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', () => {
- // Arrange
const qaContent: QAChunk = {
question: 'What is React?',
answer: 'React is a JavaScript library.',
}
- // Act
render(
<ChunkCard
chunkType={ChunkingMode.qa}
@@ -180,7 +145,6 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(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', () => {
- // Arrange
const childContents = ['Child 1 content', 'Child 2 content']
- // Act
render(
<ChunkCard
chunkType={ChunkingMode.parentChild}
@@ -202,7 +164,6 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(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 variations
describe('Parent Mode Variations', () => {
it('should show Parent-Chunk label prefix for paragraph mode', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.parentChild}
@@ -224,12 +183,10 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText(/Parent-Chunk-01/)).toBeInTheDocument()
})
it('should hide segment index tag for full-doc mode', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.parentChild}
@@ -240,13 +197,11 @@ describe('ChunkCard', () => {
/>,
)
- // Assert - should not show Chunk or Parent-Chunk label
expect(screen.queryByText(/Chunk/)).not.toBeInTheDocument()
expect(screen.queryByText(/Parent-Chunk/)).not.toBeInTheDocument()
})
it('should show Chunk label prefix for text mode', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -256,15 +211,12 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText(/Chunk-05/)).toBeInTheDocument()
})
})
- // Tests for word count display
describe('Word Count Display', () => {
it('should display formatted word count', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={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 & Act
render(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -289,12 +239,10 @@ describe('ChunkCard', () => {
/>,
)
- // Assert - translation key is returned as-is by mock
expect(screen.getByText(/100\s+(?:\S.*)?characters/)).toBeInTheDocument()
})
it('should not display word count info for full-doc mode', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.parentChild}
@@ -305,15 +253,12 @@ describe('ChunkCard', () => {
/>,
)
- // Assert - the header with word count should be hidden
expect(screen.queryByText(/500/)).not.toBeInTheDocument()
})
})
- // Tests for position ID variations
describe('Position ID', () => {
it('should handle numeric position ID', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -323,12 +268,10 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText(/Chunk-42/)).toBeInTheDocument()
})
it('should handle string position ID', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -338,12 +281,10 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText(/Chunk-99/)).toBeInTheDocument()
})
it('should pad single digit position ID', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -353,15 +294,12 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText(/Chunk-03/)).toBeInTheDocument()
})
})
- // Tests for memoization dependencies
describe('Memoization', () => {
it('should update isFullDoc memo when parentMode changes', () => {
- // Arrange
const { rerender } = render(
<ChunkCard
chunkType={ChunkingMode.parentChild}
@@ -372,10 +310,8 @@ describe('ChunkCard', () => {
/>,
)
- // Assert - paragraph mode shows label
expect(screen.getByText(/Parent-Chunk/)).toBeInTheDocument()
- // Act - change to full-doc
rerender(
<ChunkCard
chunkType={ChunkingMode.parentChild}
@@ -386,12 +322,10 @@ describe('ChunkCard', () => {
/>,
)
- // Assert - full-doc mode hides label
expect(screen.queryByText(/Parent-Chunk/)).not.toBeInTheDocument()
})
it('should update contentElement memo when content changes', () => {
- // Arrange
const initialContent = { content: 'Initial content' }
const updatedContent = { content: 'Updated content' }
@@ -404,10 +338,8 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText('Initial content')).toBeInTheDocument()
- // Act
rerender(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -417,13 +349,11 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText('Updated content')).toBeInTheDocument()
expect(screen.queryByText('Initial content')).not.toBeInTheDocument()
})
it('should update contentElement memo when chunkType changes', () => {
- // Arrange
const textContent = { content: 'Text content' }
const { rerender } = render(
<ChunkCard
@@ -434,10 +364,8 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText('Text content')).toBeInTheDocument()
- // Act - change to QA type
const qaContent: QAChunk = { question: 'Q?', answer: 'A.' }
rerender(
<ChunkCard
@@ -448,16 +376,13 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText('Q')).toBeInTheDocument()
expect(screen.getByText('Q?')).toBeInTheDocument()
})
})
- // Tests for edge cases
describe('Edge Cases', () => {
it('should handle empty child contents array', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.parentChild}
@@ -468,15 +393,12 @@ describe('ChunkCard', () => {
/>,
)
- // Assert - should render without errors
expect(screen.getByText(/Parent-Chunk-01/)).toBeInTheDocument()
})
it('should handle QA chunk with empty strings', () => {
- // Arrange
const emptyQA: QAChunk = { question: '', answer: '' }
- // Act
render(
<ChunkCard
chunkType={ChunkingMode.qa}
@@ -486,17 +408,14 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText('Q')).toBeInTheDocument()
expect(screen.getByText('A')).toBeInTheDocument()
})
it('should handle very long content', () => {
- // Arrange
const longContent = 'A'.repeat(10000)
const longContentChunk = { content: longContent }
- // Act
render(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -506,12 +425,10 @@ describe('ChunkCard', () => {
/>,
)
- // Assert
expect(screen.getByText(longContent)).toBeInTheDocument()
})
it('should handle zero word count', () => {
- // Arrange & Act
render(
<ChunkCard
chunkType={ChunkingMode.text}
@@ -521,28 +438,20 @@ describe('ChunkCard', () => {
/>,
)
- // Assert - formatNumber returns falsy for 0, so it shows 0
expect(screen.getByText(/0\s+(?:\S.*)?characters/)).toBeInTheDocument()
})
})
})
-// =============================================================================
-// ChunkCardList Component Tests
-// =============================================================================
-
describe('ChunkCardList', () => {
beforeEach(() => {
vi.clearAllMocks()
})
- // Tests for rendering with different chunk types
describe('Rendering', () => {
it('should render text chunks correctly', () => {
- // Arrange
const chunks = createGeneralChunks()
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -550,17 +459,14 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(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', () => {
- // Arrange
const chunks = createParentChildChunks()
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.parentChild}
@@ -569,17 +475,14 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert - should render child contents from parent-child chunks
expect(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', () => {
- // Arrange
const chunks = createQAChunks()
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.qa}
@@ -587,7 +490,6 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(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 memoization
describe('Memoization - chunkList', () => {
it('should extract chunks from GeneralChunks for text mode', () => {
- // Arrange
const chunks: GeneralChunks = [
{ content: 'Chunk 1' },
{ content: 'Chunk 2' },
]
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -612,20 +511,17 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(screen.getByText('Chunk 1')).toBeInTheDocument()
expect(screen.getByText('Chunk 2')).toBeInTheDocument()
})
it('should extract parent_child_chunks from ParentChildChunks for parentChild mode', () => {
- // Arrange
const chunks = createParentChildChunks({
parent_child_chunks: [
createParentChildChunk({ child_contents: ['Specific child'] }),
],
})
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.parentChild}
@@ -634,19 +530,16 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(screen.getByText('Specific child')).toBeInTheDocument()
})
it('should extract qa_chunks from QAChunks for qa mode', () => {
- // Arrange
const chunks: QAChunks = {
qa_chunks: [
{ question: 'Specific Q', answer: 'Specific A' },
],
}
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.qa}
@@ -654,13 +547,11 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(screen.getByText('Specific Q')).toBeInTheDocument()
expect(screen.getByText('Specific A')).toBeInTheDocument()
})
it('should update chunkList when chunkInfo changes', () => {
- // Arrange
const initialChunks = createGeneralChunks([{ content: 'Initial chunk' }])
const { rerender } = render(
@@ -670,10 +561,8 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert initial state
expect(screen.getByText('Initial chunk')).toBeInTheDocument()
- // Act - update chunks
const updatedChunks = createGeneralChunks([{ content: 'Updated chunk' }])
rerender(
<ChunkCardList
@@ -682,19 +571,15 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert updated state
expect(screen.getByText('Updated chunk')).toBeInTheDocument()
expect(screen.queryByText('Initial chunk')).not.toBeInTheDocument()
})
})
- // Tests for getWordCount function
describe('Word Count Calculation', () => {
it('should calculate word count for text chunks using string length', () => {
- // Arrange - "Hello" has 5 characters
const chunks = createGeneralChunks([{ content: 'Hello' }])
- // Act
render(
<ChunkCardList
chunkType={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 count
const chunks = createParentChildChunks({
parent_child_chunks: [
createParentChildChunk({
@@ -717,7 +600,6 @@ describe('ChunkCardList', () => {
],
})
- // Act
render(
<ChunkCardList
chunkType={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) = 5
const chunks: QAChunks = {
qa_chunks: [
{ question: 'Hi', answer: 'Bye' },
],
}
- // Act
render(
<ChunkCardList
chunkType={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 assignment
describe('Position ID', () => {
it('should assign 1-based position IDs to chunks', () => {
- // Arrange
const chunks = createGeneralChunks([
{ content: 'First' },
{ content: 'Second' },
{ content: 'Third' },
])
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -769,20 +644,16 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert - position IDs should be 1, 2, 3
expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()
expect(screen.getByText(/Chunk-02/)).toBeInTheDocument()
expect(screen.getByText(/Chunk-03/)).toBeInTheDocument()
})
})
- // Tests for className prop
describe('Custom className', () => {
it('should apply custom className to container', () => {
- // Arrange
const chunks = createGeneralChunks([{ content: 'Test' }])
- // Act
const { container } = render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -791,15 +662,12 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(container.firstChild).toHaveClass('custom-class')
})
it('should merge custom className with default classes', () => {
- // Arrange
const chunks = createGeneralChunks([{ content: 'Test' }])
- // Act
const { container } = render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -808,7 +676,6 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert - should have both default and custom classes
expect(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', () => {
- // Arrange
const chunks = createGeneralChunks([{ content: 'Test' }])
- // Act
const { container } = render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -827,19 +692,15 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert - should have default classes
expect(container.firstChild).toHaveClass('flex')
expect(container.firstChild).toHaveClass('w-full')
})
})
- // Tests for parentMode prop
describe('Parent Mode', () => {
it('should pass parentMode to ChunkCard for parent-child type', () => {
- // Arrange
const chunks = createParentChildChunks()
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.parentChild}
@@ -848,15 +709,12 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert - paragraph mode shows Parent-Chunk label
expect(screen.getAllByText(/Parent-Chunk/).length).toBeGreaterThan(0)
})
it('should handle full-doc parentMode', () => {
- // Arrange
const chunks = createParentChildChunks()
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.parentChild}
@@ -865,16 +723,13 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert - full-doc mode hides chunk labels
expect(screen.queryByText(/Parent-Chunk/)).not.toBeInTheDocument()
expect(screen.queryByText(/Chunk-/)).not.toBeInTheDocument()
})
it('should not use parentMode for text type', () => {
- // Arrange
const chunks = createGeneralChunks([{ content: 'Text' }])
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -883,18 +738,14 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert - should show Chunk label, not affected by parentMode
expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()
})
})
- // Tests for edge cases
describe('Edge Cases', () => {
it('should handle empty GeneralChunks array', () => {
- // Arrange
const chunks: GeneralChunks = []
- // Act
const { container } = render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -902,19 +753,16 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert - should render empty container
expect(container.firstChild).toBeInTheDocument()
expect(container.firstChild?.childNodes.length).toBe(0)
})
it('should handle empty ParentChildChunks', () => {
- // Arrange
const chunks: ParentChildChunks = {
parent_child_chunks: [],
parent_mode: 'paragraph',
}
- // Act
const { container } = render(
<ChunkCardList
chunkType={ChunkingMode.parentChild}
@@ -923,18 +771,15 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(container.firstChild).toBeInTheDocument()
expect(container.firstChild?.childNodes.length).toBe(0)
})
it('should handle empty QAChunks', () => {
- // Arrange
const chunks: QAChunks = {
qa_chunks: [],
}
- // Act
const { container } = render(
<ChunkCardList
chunkType={ChunkingMode.qa}
@@ -942,16 +787,13 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(container.firstChild).toBeInTheDocument()
expect(container.firstChild?.childNodes.length).toBe(0)
})
it('should handle single item in chunks', () => {
- // Arrange
const chunks = createGeneralChunks([{ content: 'Single chunk' }])
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -959,16 +801,13 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(screen.getByText('Single chunk')).toBeInTheDocument()
expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()
})
it('should handle large number of chunks', () => {
- // Arrange
const chunks = Array.from({ length: 100 }, (_, i) => ({ content: `Chunk number ${i + 1}` }))
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -976,23 +815,19 @@ describe('ChunkCardList', () => {
/>,
)
- // Assert
expect(screen.getByText('Chunk number 1')).toBeInTheDocument()
expect(screen.getByText('Chunk number 100')).toBeInTheDocument()
expect(screen.getByText(/Chunk-100/)).toBeInTheDocument()
})
})
- // Tests for key uniqueness
describe('Key Generation', () => {
it('should generate unique keys for chunks', () => {
- // Arrange - chunks with same content
const chunks = createGeneralChunks([
{ content: 'Same content' },
{ content: 'Same content' },
{ content: 'Same content' },
])
- // Act
const { container } = render(
<ChunkCardList
chunkType={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 scenarios
describe('Complete Workflows', () => {
it('should render complete text chunking workflow', () => {
- // Arrange
const textChunks = createGeneralChunks([
{ content: 'First paragraph of the document.' },
{ content: 'Second paragraph with more information.' },
{ content: 'Final paragraph concluding the content.' },
])
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.text}
@@ -1034,10 +861,8 @@ describe('ChunkCardList Integration', () => {
/>,
)
- // Assert
expect(screen.getByText('First paragraph of the document.')).toBeInTheDocument()
expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()
- // "First paragraph of the document." = 32 characters
expect(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', () => {
- // Arrange
const parentChildChunks = createParentChildChunks({
parent_child_chunks: [
{
@@ -1062,7 +886,6 @@ describe('ChunkCardList Integration', () => {
],
})
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.parentChild}
@@ -1071,7 +894,6 @@ describe('ChunkCardList Integration', () => {
/>,
)
- // Assert
expect(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', () => {
- // Arrange
const qaChunks = createQAChunks({
qa_chunks: [
{
@@ -1094,7 +915,6 @@ describe('ChunkCardList Integration', () => {
],
})
- // Act
render(
<ChunkCardList
chunkType={ChunkingMode.qa}
@@ -1102,7 +922,6 @@ describe('ChunkCardList Integration', () => {
/>,
)
- // Assert
const 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 scenarios
describe('Type Switching', () => {
it('should handle switching from text to QA type', () => {
- // Arrange
const textChunks = createGeneralChunks([{ content: 'Text content' }])
const qaChunks = createQAChunks()
@@ -1129,10 +946,8 @@ describe('ChunkCardList Integration', () => {
/>,
)
- // Assert initial text state
expect(screen.getByText('Text content')).toBeInTheDocument()
- // Act - switch to QA
rerender(
<ChunkCardList
chunkType={ChunkingMode.qa}
@@ -1140,13 +955,11 @@ describe('ChunkCardList Integration', () => {
/>,
)
- // Assert QA state
expect(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', () => {
- // Arrange
const textChunks = createGeneralChunks([{ content: 'Simple text' }])
const parentChildChunks = createParentChildChunks()
@@ -1157,11 +970,9 @@ describe('ChunkCardList Integration', () => {
/>,
)
- // Assert initial state
expect(screen.getByText('Simple text')).toBeInTheDocument()
expect(screen.getByText(/Chunk-01/)).toBeInTheDocument()
- // Act - switch to parent-child
rerender(
<ChunkCardList
chunkType={ChunkingMode.parentChild}
@@ -1170,9 +981,7 @@ describe('ChunkCardList Integration', () => {
/>,
)
- // Assert parent-child state
expect(screen.queryByText('Simple text')).not.toBeInTheDocument()
- // Multiple Parent-Chunk elements exist, so use getAllByText
expect(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.tsx
similarity index 76%
rename from web/app/components/rag-pipeline/components/panel/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx
index 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 error
vi.mock('reactflow', () => ({
useNodes: () => [],
useStoreApi: () => ({
@@ -26,20 +21,12 @@ vi.mock('reactflow', () => ({
},
}))
-// Use vi.hoisted to create variables that can be used in vi.mock
const { dynamicMocks, mockInputFieldEditorProps } = vi.hoisted(() => {
let counter = 0
const 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: GlobalVariablePanel
switch (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/dynamic
vi.mock('next/dynamic', () => ({
default: (_loader: () => Promise<{ default: React.ComponentType }>, _options?: Record<string, unknown>) => {
return dynamicMocks.createMockComponent()
},
}))
-// Mock workflow store
let mockHistoryWorkflowData: Record<string, unknown> | null = null
let mockShowDebugAndPreviewPanel = false
let mockShowGlobalVariablePanel = false
@@ -138,7 +123,6 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-// Mock Panel component to capture props and render children
let capturedPanelProps: PanelProps | null = null
vi.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> | null
showDebugAndPreviewPanel?: 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 () => {
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('workflow-panel')).toBeInTheDocument()
})
})
it('should render Panel component with correct structure', async () => {
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ pipelineId: 'my-pipeline-456' })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ pipelineId: 'pipeline-abc' })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(capturedPanelProps?.versionHistoryPanelProps?.getVersionListUrl).toBe(
'/rag/pipelines/pipeline-abc/workflows',
@@ -249,13 +209,10 @@ describe('RagPipelinePanel', () => {
})
it('should compute correct deleteVersionUrl function', async () => {
- // Arrange
setupMocks({ pipelineId: 'pipeline-xyz' })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ pipelineId: 'pipeline-def' })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(capturedPanelProps?.versionHistoryPanelProps?.latestVersionId).toBe('')
})
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests - panelProps
- // -------------------------------------------------------------------------
describe('Memoization - panelProps', () => {
it('should pass components.left to Panel', async () => {
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(capturedPanelProps?.components?.left).toBeDefined()
})
})
it('should pass components.right to Panel', async () => {
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(capturedPanelProps?.components?.right).toBeDefined()
})
})
it('should pass versionHistoryPanelProps to panelProps', async () => {
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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-rendered
const { rerender } = render(<RagPipelinePanel />)
- // Act - rerender without prop changes
rerender(<RagPipelinePanel />)
- // Assert - component should still render correctly
await 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 () => {
- // Arrange
setupMocks({ historyWorkflowData: { id: 'history-1' } })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('record-panel')).toBeInTheDocument()
})
})
it('should not render Record panel when historyWorkflowData is null', async () => {
- // Arrange
setupMocks({ historyWorkflowData: null })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.queryByTestId('record-panel')).not.toBeInTheDocument()
})
})
it('should not render Record panel when historyWorkflowData is undefined', async () => {
- // Arrange
setupMocks({ historyWorkflowData: undefined })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ showDebugAndPreviewPanel: true })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('test-run-panel')).toBeInTheDocument()
})
})
it('should not render TestRun panel when showDebugAndPreviewPanel is false', async () => {
- // Arrange
setupMocks({ showDebugAndPreviewPanel: false })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ showGlobalVariablePanel: true })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('global-variable-panel')).toBeInTheDocument()
})
})
it('should not render GlobalVariable panel when showGlobalVariablePanel is false', async () => {
- // Arrange
setupMocks({ showGlobalVariablePanel: false })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({
historyWorkflowData: { id: 'history-1' },
showDebugAndPreviewPanel: true,
showGlobalVariablePanel: true,
})
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({
historyWorkflowData: null,
showDebugAndPreviewPanel: false,
showGlobalVariablePanel: false,
})
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({
historyWorkflowData: { id: 'history-1' },
showDebugAndPreviewPanel: true,
showGlobalVariablePanel: false,
})
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ showInputFieldPreviewPanel: true })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('preview-panel')).toBeInTheDocument()
})
})
it('should not render Preview panel when showInputFieldPreviewPanel is false', async () => {
- // Arrange
setupMocks({ showInputFieldPreviewPanel: false })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
const editProps = {
onClose: vi.fn(),
onSubmit: vi.fn(),
@@ -574,30 +448,24 @@ describe('RagPipelinePanelOnLeft', () => {
}
setupMocks({ inputFieldEditPanelProps: editProps })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('input-field-editor-panel')).toBeInTheDocument()
})
})
it('should not render InputFieldEditor panel when inputFieldEditPanelProps is null', async () => {
- // Arrange
setupMocks({ inputFieldEditPanelProps: null })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.queryByTestId('input-field-editor-panel')).not.toBeInTheDocument()
})
})
it('should pass props to InputFieldEditor panel', async () => {
- // Arrange
const editProps = {
onClose: vi.fn(),
onSubmit: vi.fn(),
@@ -605,10 +473,8 @@ describe('RagPipelinePanelOnLeft', () => {
}
setupMocks({ inputFieldEditPanelProps: editProps })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ showInputFieldPanel: true })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('input-field-panel')).toBeInTheDocument()
})
})
it('should not render InputField panel when showInputFieldPanel is false', async () => {
- // Arrange
setupMocks({ showInputFieldPanel: false })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({
showInputFieldPreviewPanel: true,
inputFieldEditPanelProps: { onClose: vi.fn(), onSubmit: vi.fn() },
showInputFieldPanel: true,
})
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({
showInputFieldPreviewPanel: false,
inputFieldEditPanelProps: null,
showInputFieldPanel: false,
})
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({
showInputFieldPreviewPanel: true,
inputFieldEditPanelProps: null,
showInputFieldPanel: true,
})
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ pipelineId: '' })
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(capturedPanelProps?.versionHistoryPanelProps?.getVersionListUrl).toBe(
'/rag/pipelines//workflows',
@@ -745,13 +580,10 @@ describe('Edge Cases', () => {
})
it('should handle special characters in pipelineId', async () => {
- // Arrange
setupMocks({ pipelineId: 'pipeline-with-special_chars.123' })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
const customProps = {
onClose: vi.fn(),
onSubmit: vi.fn(),
@@ -778,10 +606,8 @@ describe('Edge Cases', () => {
}
setupMocks({ inputFieldEditPanelProps: customProps })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({
historyWorkflowData: { id: 'h1' },
showDebugAndPreviewPanel: true,
@@ -807,10 +629,8 @@ describe('Edge Cases', () => {
showInputFieldPanel: true,
})
- // Act
render(<RagPipelinePanel />)
- // Assert - All panels should be visible
await 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 () => {
- // Arrange
setupMocks({ pipelineId: 'stable-pipeline' })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
setupMocks({ pipelineId: 'stable-pipeline' })
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Act
render(<RagPipelinePanel />)
- // Assert - Check structure matches PanelProps
await waitFor(() => {
expect(capturedPanelProps).toHaveProperty('components')
expect(capturedPanelProps).toHaveProperty('versionHistoryPanelProps')
@@ -890,10 +694,8 @@ describe('Type Safety', () => {
})
it('should pass correct versionHistoryPanelProps structure', async () => {
- // Act
render(<RagPipelinePanel />)
- // Assert
await 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 () => {
- // Arrange
const { rerender } = render(<RagPipelinePanel />)
- // Act - Multiple rerenders
for (let i = 0; i < 10; i++)
rerender(<RagPipelinePanel />)
- // Assert - Component should still work
await 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 () => {
- // Arrange
setupMocks({
historyWorkflowData: { id: 'h1' },
showInputFieldPanel: true,
})
- // Act
render(<RagPipelinePanel />)
- // Assert
await waitFor(() => {
expect(capturedPanelProps?.components?.left).toBeDefined()
expect(capturedPanelProps?.components?.right).toBeDefined()
- // Check that the components are React elements
expect(React.isValidElement(capturedPanelProps?.components?.left)).toBe(true)
expect(React.isValidElement(capturedPanelProps?.components?.right)).toBe(true)
})
})
it('should correctly consume all store selectors', async () => {
- // Arrange
setupMocks({
historyWorkflowData: { id: 'test-history' },
showDebugAndPreviewPanel: true,
@@ -971,10 +757,8 @@ describe('Integration Tests', () => {
pipelineId: 'integration-test-pipeline',
})
- // Act
render(<RagPipelinePanel />)
- // Assert - All store-dependent rendering should work
await 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.tsx
similarity index 94%
rename from web/app/components/rag-pipeline/components/panel/input-field/footer-tip.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/input-field/__tests__/footer-tip.spec.tsx
index 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 rendered
const 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.ts
similarity index 87%
rename from web/app/components/rag-pipeline/components/panel/input-field/hooks.spec.ts
rename to web/app/components/rag-pipeline/components/panel/input-field/__tests__/hooks.spec.ts
index 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 reactflow
const 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/shallow
vi.mock('zustand/react/shallow', () => ({
useShallow: (fn: (...args: unknown[]) => unknown) => fn,
}))
-// Mock workflow store
let mockNodePanelWidth = 400
let mockWorkflowCanvasWidth: number | undefined = 1200
let 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 false
expect(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 true
expect(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) = 200
expect(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) = 400
expect(result.current.floatingRightWidth).toBeLessThanOrEqual(600)
})
})
@@ -127,7 +118,6 @@ describe('useFloatingRight', () => {
const { result } = renderHook(() => useFloatingRight(400))
- // Should not throw and should maintain initial state
expect(result.current.floatingRight).toBe(false)
})
@@ -145,7 +135,6 @@ describe('useFloatingRight', () => {
const { result } = renderHook(() => useFloatingRight(10000))
- // Should be floating due to limited space
expect(result.current.floatingRight).toBe(true)
})
@@ -159,7 +148,6 @@ describe('useFloatingRight', () => {
const { result } = renderHook(() => useFloatingRight(400))
- // Should have selected node so node panel is considered
expect(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.tsx
similarity index 78%
rename from web/app/components/rag-pipeline/components/panel/input-field/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/input-field/__tests__/index.spec.tsx
index 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 updates
let mockNodesData: Node<DataSourceNodeType>[] = []
vi.mock('reactflow', () => ({
useNodes: () => mockNodesData,
}))
-// Mock useInputFieldPanel hook
const 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 hook
const 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', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.title'),
).toBeInTheDocument()
})
it('should render panel title correctly', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.title'),
).toBeInTheDocument()
})
it('should render panel description', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.description'),
).toBeInTheDocument()
})
it('should render preview button', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
screen.getByText('datasetPipeline.operations.preview'),
).toBeInTheDocument()
})
it('should render close button', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
const closeButton = screen.getByRole('button', { name: '' })
expect(closeButton).toBeInTheDocument()
})
it('should render footer tip component', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('footer-tip')).toBeInTheDocument()
})
it('should render unique inputs section title', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.uniqueInputs.title'),
).toBeInTheDocument()
})
it('should render global inputs field list', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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', () => {
- // Arrange
const nodes = [
createDataSourceNode('node-1', 'DataSource 1'),
createDataSourceNode('node-2', 'DataSource 2'),
]
setupMocks({ nodes })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('field-list-node-1')).toBeInTheDocument()
expect(screen.getByTestId('field-list-node-2')).toBeInTheDocument()
})
it('should render datasource label for each node', () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'My DataSource')]
setupMocks({ nodes })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
screen.getByTestId('datasource-label-My DataSource'),
).toBeInTheDocument()
})
it('should not render any datasource field lists when no nodes exist', () => {
- // Arrange
setupMocks({ nodes: [] })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.queryByTestId('field-list-node-1')).not.toBeInTheDocument()
- // Global inputs should still render
expect(screen.getByTestId('field-list-shared')).toBeInTheDocument()
})
it('should filter only DataSource type nodes', () => {
- // Arrange
const dataSourceNode = createDataSourceNode('ds-node', 'DataSource Node')
- // Create a non-datasource node to verify filtering
const otherNode = {
id: 'other-node',
type: 'custom',
@@ -359,10 +301,8 @@ describe('InputFieldPanel', () => {
} as Node<DataSourceNodeType>
mockNodesData = [dataSourceNode, otherNode]
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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', () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
const variables = [
createRAGPipelineVariable('node-1', { variable: 'var1' }),
@@ -384,28 +320,22 @@ describe('InputFieldPanel', () => {
]
setupMocks({ nodes, ragPipelineVariables: variables })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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', () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
setupMocks({ nodes, ragPipelineVariables: [] })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('field-list-fields-count-node-1')).toHaveTextContent('0')
})
it('should pass all variable names to field lists', () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
const variables = [
createRAGPipelineVariable('node-1', { variable: 'var1' }),
@@ -413,10 +343,8 @@ describe('InputFieldPanel', () => {
]
setupMocks({ nodes, ragPipelineVariables: variables })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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 class
const 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', () => {
- // Arrange
render(<InputFieldPanel />)
const buttons = screen.getAllByRole('button')
const closeButton = buttons.find(isCloseButton)
- // Act
fireEvent.click(closeButton!)
- // Assert
expect(mockCloseAllInputFieldPanels).toHaveBeenCalledTimes(1)
})
it('should call toggleInputFieldPreviewPanel when preview button is clicked', () => {
- // Arrange
render(<InputFieldPanel />)
const previewButton = screen.getByText('datasetPipeline.operations.preview')
- // Act
fireEvent.click(previewButton)
- // Assert
expect(mockToggleInputFieldPreviewPanel).toHaveBeenCalledTimes(1)
})
it('should disable preview button when editing', () => {
- // Arrange
setupMocks({ isEditing: true })
- // Act
render(<InputFieldPanel />)
- // Assert
const previewButton = screen
.getByText('datasetPipeline.operations.preview')
.closest('button')
@@ -475,13 +390,10 @@ describe('InputFieldPanel', () => {
})
it('should not disable preview button when not editing', () => {
- // Arrange
setupMocks({ isEditing: false })
- // Act
render(<InputFieldPanel />)
- // Assert
const 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', () => {
- // Arrange
setupMocks({ isPreviewing: true })
- // Act
render(<InputFieldPanel />)
- // Assert
const previewButton = screen
.getByText('datasetPipeline.operations.preview')
.closest('button')
@@ -509,81 +415,62 @@ describe('InputFieldPanel', () => {
})
it('should set readonly to true when previewing', () => {
- // Arrange
setupMocks({ isPreviewing: true })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('field-list-readonly-shared')).toHaveTextContent(
'true',
)
})
it('should set readonly to true when editing', () => {
- // Arrange
setupMocks({ isEditing: true })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('field-list-readonly-shared')).toHaveTextContent(
'true',
)
})
it('should set readonly to false when not previewing or editing', () => {
- // Arrange
setupMocks({ isPreviewing: false, isEditing: false })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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 () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
setupMocks({ nodes })
render(<InputFieldPanel />)
- // Act
fireEvent.click(screen.getByTestId('trigger-change-node-1'))
- // Assert
await waitFor(() => {
expect(mockSetRagPipelineVariables).toHaveBeenCalled()
})
})
it('should call handleSyncWorkflowDraft when fields change', async () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
setupMocks({ nodes })
render(<InputFieldPanel />)
- // Act
fireEvent.click(screen.getByTestId('trigger-change-node-1'))
- // Assert
await waitFor(() => {
expect(mockHandleSyncWorkflowDraft).toHaveBeenCalled()
})
})
it('should place datasource node fields before global fields', async () => {
- // Arrange
const 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 />)
- // Act
fireEvent.click(screen.getByTestId('trigger-change-node-1'))
- // Assert
await waitFor(() => {
expect(mockSetRagPipelineVariables).toHaveBeenCalled()
})
- // Verify datasource fields come before shared fields
const setVarsCall = mockSetRagPipelineVariables.mock.calls[0][0] as RAGPipelineVariables
const 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 () => {
- // Arrange
const 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 />)
- // Act
fireEvent.click(screen.getByTestId('trigger-remove-node-1'))
- // Assert
await waitFor(() => {
expect(mockSetRagPipelineVariables).toHaveBeenCalled()
})
})
it('should update global input fields correctly', async () => {
- // Arrange
setupMocks()
render(<InputFieldPanel />)
- // Act
fireEvent.click(screen.getByTestId('trigger-change-shared'))
- // Assert
await 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', () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
setupMocks({ nodes })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
screen.getByTestId('field-list-classname-node-1'),
).toHaveTextContent('pt-1 pb-1')
})
it('should pass correct className to global inputs field list', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('field-list-classname-shared')).toHaveTextContent(
'pt-2 pb-1',
)
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should memoize datasourceNodeDataMap based on nodes', () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
setupMocks({ nodes })
const { rerender } = render(<InputFieldPanel />)
- // Act - rerender with same nodes reference
rerender(<InputFieldPanel />)
- // Assert - component should not break and should render correctly
expect(screen.getByTestId('field-list-node-1')).toBeInTheDocument()
})
it('should compute allVariableNames correctly', () => {
- // Arrange
const variables = [
createRAGPipelineVariable('node-1', { variable: 'alpha' }),
createRAGPipelineVariable('node-1', { variable: 'beta' }),
@@ -707,21 +570,15 @@ describe('InputFieldPanel', () => {
]
setupMocks({ ragPipelineVariables: variables })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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 nesting
const findCloseButton = (buttons: HTMLElement[]) => {
const isCloseButton = (btn: HTMLElement) =>
btn.classList.contains('size-6')
@@ -730,10 +587,8 @@ describe('InputFieldPanel', () => {
}
it('should maintain closePanel callback reference', () => {
- // Arrange
const { rerender } = render(<InputFieldPanel />)
- // Act
const 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)!)
- // Assert
expect(mockCloseAllInputFieldPanels.mock.calls.length).toBe(callCount1 + 1)
})
it('should maintain togglePreviewPanel callback reference', () => {
- // Arrange
const { rerender } = render(<InputFieldPanel />)
- // Act
fireEvent.click(screen.getByText('datasetPipeline.operations.preview'))
const callCount1 = mockToggleInputFieldPreviewPanel.mock.calls.length
rerender(<InputFieldPanel />)
fireEvent.click(screen.getByText('datasetPipeline.operations.preview'))
- // Assert
expect(mockToggleInputFieldPreviewPanel.mock.calls.length).toBe(
callCount1 + 1,
)
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle empty ragPipelineVariables', () => {
- // Arrange
setupMocks({ ragPipelineVariables: [] })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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 value
mockRagPipelineVariables = undefined
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('field-list-shared')).toBeInTheDocument()
})
it('should handle null variable names in allVariableNames', () => {
- // Arrange - intentionally testing edge case with empty variable name
const variables = [
createRAGPipelineVariable('node-1', { variable: 'valid_var' }),
createRAGPipelineVariable('node-1', { variable: '' }),
]
setupMocks({ ragPipelineVariables: variables })
- // Act
render(<InputFieldPanel />)
- // Assert - should not crash
expect(screen.getByTestId('field-list-shared')).toBeInTheDocument()
})
it('should handle large number of datasource nodes', () => {
- // Arrange
const nodes = Array.from({ length: 10 }, (_, i) =>
createDataSourceNode(`node-${i}`, `DataSource ${i}`))
setupMocks({ nodes })
- // Act
render(<InputFieldPanel />)
- // Assert
nodes.forEach((_, i) => {
expect(screen.getByTestId(`field-list-node-${i}`)).toBeInTheDocument()
})
})
it('should handle large number of variables', () => {
- // Arrange
const variables = Array.from({ length: 100 }, (_, i) =>
createRAGPipelineVariable('shared', { variable: `var_${i}` }))
setupMocks({ ragPipelineVariables: variables })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('field-list-fields-count-shared')).toHaveTextContent(
'100',
)
})
it('should handle special characters in variable names', () => {
- // Arrange
const variables = [
createRAGPipelineVariable('shared', { variable: 'var_with_underscore' }),
createRAGPipelineVariable('shared', { variable: 'varWithCamelCase' }),
]
setupMocks({ ragPipelineVariables: variables })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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 () => {
- // Arrange
const nodes = [
createDataSourceNode('node-1', 'DataSource 1'),
createDataSourceNode('node-2', 'DataSource 2'),
@@ -869,18 +695,15 @@ describe('InputFieldPanel', () => {
setupMocks({ nodes })
render(<InputFieldPanel />)
- // Act
fireEvent.click(screen.getByTestId('trigger-change-node-1'))
fireEvent.click(screen.getByTestId('trigger-change-node-2'))
- // Assert
await waitFor(() => {
expect(mockSetRagPipelineVariables).toHaveBeenCalledTimes(2)
})
})
it('should maintain separate field lists for different nodes', () => {
- // Arrange
const nodes = [
createDataSourceNode('node-1', 'DataSource 1'),
createDataSourceNode('node-2', 'DataSource 2'),
@@ -892,42 +715,31 @@ describe('InputFieldPanel', () => {
]
setupMocks({ nodes, ragPipelineVariables: variables })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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', () => {
- // Act
const { container } = render(<InputFieldPanel />)
- // Assert
const panel = container.firstChild as HTMLElement
expect(panel).toHaveClass('w-[400px]')
})
it('should have overflow scroll on content area', () => {
- // Act
const { container } = render(<InputFieldPanel />)
- // Assert
const scrollContainer = container.querySelector('.overflow-y-auto')
expect(scrollContainer).toBeInTheDocument()
})
it('should render header section with proper spacing', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
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', () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
const variables = [
createRAGPipelineVariable('node-1', { variable: 'test_var' }),
@@ -953,38 +761,29 @@ describe('InputFieldPanel', () => {
isPreviewing: true,
})
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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', () => {
- // Arrange
const variables = [
createRAGPipelineVariable('shared', { variable: 'shared_var' }),
]
setupMocks({ ragPipelineVariables: variables, isEditing: true })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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', () => {
- // Arrange
const variables = [
createRAGPipelineVariable('node-1', { variable: 'first' }),
createRAGPipelineVariable('node-1', { variable: 'second' }),
@@ -992,10 +791,8 @@ describe('InputFieldPanel', () => {
]
setupMocks({ ragPipelineVariables: variables })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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 behavior
render(<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', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(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', () => {
- // Act
render(<InputFieldPanel />)
- // Assert
expect(screen.getByTestId('global-inputs-label')).toBeInTheDocument()
})
it('should render Datasource label for each datasource node', () => {
- // Arrange
const nodes = [
createDataSourceNode('node-1', 'First DataSource'),
createDataSourceNode('node-2', 'Second DataSource'),
]
setupMocks({ nodes })
- // Act
render(<InputFieldPanel />)
- // Assert
expect(
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 memoization
const { rerender } = render(<InputFieldPanel />)
- // Act - rerender without prop changes
rerender(<InputFieldPanel />)
- // Assert - component should still render correctly
expect(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 () => {
- // Arrange
const nodes = [createDataSourceNode('node-1', 'DataSource 1')]
setupMocks({ nodes })
render(<InputFieldPanel />)
- // Act - trigger a state change
fireEvent.click(screen.getByTestId('trigger-change-node-1'))
- // Assert
await 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.tsx
similarity index 82%
rename from web/app/components/rag-pipeline/components/panel/input-field/editor/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/input-field/editor/__tests__/index.spec.tsx
index 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 hook
const 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 service
vi.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', () => {
- // Arrange
const props = createInputFieldEditorProps()
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(screen.getByTestId('input-field-form')).toBeInTheDocument()
})
it('should render close button', () => {
- // Arrange
const props = createInputFieldEditorProps()
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
const closeButton = screen.getByRole('button', { name: '' })
expect(closeButton).toBeInTheDocument()
})
it('should render "Add Input Field" title when no initialData', () => {
- // Arrange
const props = createInputFieldEditorProps({ initialData: undefined })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.addInputField'),
).toBeInTheDocument()
})
it('should render "Edit Input Field" title when initialData is provided', () => {
- // Arrange
const props = createInputFieldEditorProps({
initialData: createInputVar(),
})
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.editInputField'),
).toBeInTheDocument()
})
it('should pass supportFile=true to form', () => {
- // Arrange
const props = createInputFieldEditorProps()
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(screen.getByTestId('form-support-file').textContent).toBe('true')
})
it('should pass isEditMode=false when no initialData', () => {
- // Arrange
const props = createInputFieldEditorProps({ initialData: undefined })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(screen.getByTestId('form-is-edit-mode').textContent).toBe('false')
})
it('should pass isEditMode=true when initialData is provided', () => {
- // Arrange
const props = createInputFieldEditorProps({
initialData: createInputVar(),
})
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(screen.getByTestId('form-is-edit-mode').textContent).toBe('true')
})
})
- // -------------------------------------------------------------------------
- // Props Variations Tests
- // -------------------------------------------------------------------------
describe('Props Variations', () => {
it('should handle different input types in initialData', () => {
- // Arrange
const typesToTest = [
PipelineInputVarType.textInput,
PipelineInputVarType.paragraph,
@@ -269,19 +222,16 @@ describe('InputFieldEditorPanel', () => {
const initialData = createInputVar({ type })
const props = createInputFieldEditorProps({ initialData })
- // Act
const { unmount } = renderWithProviders(
<InputFieldEditorPanel {...props} />,
)
- // Assert
expect(screen.getByTestId('input-field-form')).toBeInTheDocument()
unmount()
})
})
it('should handle initialData with all optional fields populated', () => {
- // Arrange
const initialData = createInputVar({
default_value: 'default',
tooltips: 'tooltip text',
@@ -294,15 +244,12 @@ describe('InputFieldEditorPanel', () => {
})
const props = createInputFieldEditorProps({ initialData })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(screen.getByTestId('input-field-form')).toBeInTheDocument()
})
it('should handle initialData with minimal fields', () => {
- // Arrange
const initialData: InputVar = {
type: PipelineInputVarType.textInput,
label: 'Min',
@@ -311,54 +258,40 @@ describe('InputFieldEditorPanel', () => {
}
const props = createInputFieldEditorProps({ initialData })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(screen.getByTestId('input-field-form')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // User Interaction Tests
- // -------------------------------------------------------------------------
describe('User Interactions', () => {
it('should call onClose when close button is clicked', () => {
- // Arrange
const onClose = vi.fn()
const props = createInputFieldEditorProps({ onClose })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
fireEvent.click(screen.getByTestId('input-field-editor-close-btn'))
- // Assert
expect(onClose).toHaveBeenCalledTimes(1)
})
it('should call onClose when form cancel is triggered', () => {
- // Arrange
const onClose = vi.fn()
const props = createInputFieldEditorProps({ onClose })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
fireEvent.click(screen.getByTestId('form-cancel-btn'))
- // Assert
expect(onClose).toHaveBeenCalledTimes(1)
})
it('should call onSubmit with converted data when form submits', () => {
- // Arrange
const onSubmit = vi.fn()
const props = createInputFieldEditorProps({ onSubmit })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
fireEvent.click(screen.getByTestId('form-submit-btn'))
- // Assert
expect(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', () => {
- // Arrange
const props = createInputFieldEditorProps()
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(mockUseFloatingRight).toHaveBeenCalled()
})
it('should apply floating right styles when floatingRight is true', () => {
- // Arrange
mockUseFloatingRight.mockReturnValue({
floatingRight: true,
floatingRightWidth: 300,
})
const props = createInputFieldEditorProps()
- // Act
const { container } = renderWithProviders(
<InputFieldEditorPanel {...props} />,
)
- // Assert
const panel = container.firstChild as HTMLElement
expect(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', () => {
- // Arrange
mockUseFloatingRight.mockReturnValue({
floatingRight: false,
floatingRightWidth: 400,
})
const props = createInputFieldEditorProps()
- // Act
const { container } = renderWithProviders(
<InputFieldEditorPanel {...props} />,
)
- // Assert
const panel = container.firstChild as HTMLElement
expect(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', () => {
- // Arrange
const onClose = vi.fn()
const props = createInputFieldEditorProps({ onClose })
- // Act
const { rerender } = renderWithProviders(
<InputFieldEditorPanel {...props} />,
)
@@ -447,16 +363,13 @@ describe('InputFieldEditorPanel', () => {
)
fireEvent.click(screen.getByTestId('form-cancel-btn'))
- // Assert
expect(onClose).toHaveBeenCalledTimes(2)
})
it('should maintain stable onSubmit callback reference', () => {
- // Arrange
const onSubmit = vi.fn()
const props = createInputFieldEditorProps({ onSubmit })
- // Act
const { rerender } = renderWithProviders(
<InputFieldEditorPanel {...props} />,
)
@@ -469,21 +382,15 @@ describe('InputFieldEditorPanel', () => {
)
fireEvent.click(screen.getByTestId('form-submit-btn'))
- // Assert
expect(onSubmit).toHaveBeenCalledTimes(2)
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should memoize formData when initialData does not change', () => {
- // Arrange
const initialData = createInputVar()
const props = createInputFieldEditorProps({ initialData })
- // Act
const { rerender } = renderWithProviders(
<InputFieldEditorPanel {...props} />,
)
@@ -496,18 +403,15 @@ describe('InputFieldEditorPanel', () => {
)
const secondFormData = screen.getByTestId('form-initial-data').textContent
- // Assert
expect(firstFormData).toBe(secondFormData)
})
it('should recompute formData when initialData changes', () => {
- // Arrange
const initialData1 = createInputVar({ variable: 'var1' })
const initialData2 = createInputVar({ variable: 'var2' })
const props1 = createInputFieldEditorProps({ initialData: initialData1 })
const props2 = createInputFieldEditorProps({ initialData: initialData2 })
- // Act
const { rerender } = renderWithProviders(
<InputFieldEditorPanel {...props1} />,
)
@@ -520,33 +424,25 @@ describe('InputFieldEditorPanel', () => {
)
const secondFormData = screen.getByTestId('form-initial-data').textContent
- // Assert
expect(firstFormData).not.toBe(secondFormData)
expect(firstFormData).toContain('var1')
expect(secondFormData).toContain('var2')
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle undefined initialData gracefully', () => {
- // Arrange
const props = createInputFieldEditorProps({ initialData: undefined })
- // Act & Assert
expect(() =>
renderWithProviders(<InputFieldEditorPanel {...props} />),
).not.toThrow()
})
it('should handle rapid close button clicks', () => {
- // Arrange
const onClose = vi.fn()
const props = createInputFieldEditorProps({ onClose })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
const closeButtons = screen.getAllByRole('button')
const closeButton = closeButtons.find(btn => btn.querySelector('svg'))
@@ -557,12 +453,10 @@ describe('InputFieldEditorPanel', () => {
fireEvent.click(closeButton)
}
- // Assert
expect(onClose).toHaveBeenCalledTimes(3)
})
it('should handle special characters in initialData', () => {
- // Arrange
const initialData = createInputVar({
label: 'Test <script>alert("xss")</script>',
variable: 'test_var',
@@ -570,15 +464,12 @@ describe('InputFieldEditorPanel', () => {
})
const props = createInputFieldEditorProps({ initialData })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(screen.getByTestId('input-field-form')).toBeInTheDocument()
})
it('should handle empty string values in initialData', () => {
- // Arrange
const initialData = createInputVar({
label: '',
variable: '',
@@ -588,26 +479,16 @@ describe('InputFieldEditorPanel', () => {
})
const props = createInputFieldEditorProps({ initialData })
- // Act
renderWithProviders(<InputFieldEditorPanel {...props} />)
- // Assert
expect(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', () => {
- // Arrange
const inputVar = createInputVar({
type: PipelineInputVarType.textInput,
label: 'Test',
@@ -621,10 +502,8 @@ describe('convertToInputFieldFormData', () => {
unit: 'kg',
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(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', () => {
- // Arrange
const 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'],
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.allowedFileUploadMethods).toEqual([
'local_file',
'remote_url',
@@ -661,10 +537,8 @@ describe('convertToInputFieldFormData', () => {
})
it('should return default template when data is undefined', () => {
- // Act
const result = convertToInputFieldFormData(undefined)
- // Assert
expect(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', () => {
- // Arrange
const inputVar = createInputVar({
default_value: undefined,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.default).toBeUndefined()
})
it('should not include default when default_value is null', () => {
- // Arrange
const inputVar: InputVar = {
...createInputVar(),
default_value: null as unknown as string,
}
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.default).toBeUndefined()
})
it('should include default when default_value is empty string', () => {
- // Arrange
const inputVar = createInputVar({
default_value: '',
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.default).toBe('')
})
it('should not include tooltips when undefined', () => {
- // Arrange
const inputVar = createInputVar({
tooltips: undefined,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.tooltips).toBeUndefined()
})
it('should not include placeholder when undefined', () => {
- // Arrange
const inputVar = createInputVar({
placeholder: undefined,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.placeholder).toBeUndefined()
})
it('should not include unit when undefined', () => {
- // Arrange
const inputVar = createInputVar({
unit: undefined,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.unit).toBeUndefined()
})
it('should not include file settings when allowed_file_upload_methods is undefined', () => {
- // Arrange
const inputVar = createInputVar({
allowed_file_upload_methods: undefined,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.allowedFileUploadMethods).toBeUndefined()
})
it('should not include allowedTypesAndExtensions details when file types/extensions are missing', () => {
- // Arrange
const inputVar = createInputVar({
allowed_file_types: undefined,
allowed_file_extensions: undefined,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.allowedTypesAndExtensions).toEqual({})
})
})
- // -------------------------------------------------------------------------
- // Type-Specific Tests
- // -------------------------------------------------------------------------
describe('Type-Specific Handling', () => {
it('should handle textInput type', () => {
- // Arrange
const inputVar = createInputVar({
type: PipelineInputVarType.textInput,
max_length: 256,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.type).toBe(PipelineInputVarType.textInput)
expect(result.maxLength).toBe(256)
})
it('should handle paragraph type', () => {
- // Arrange
const inputVar = createInputVar({
type: PipelineInputVarType.paragraph,
max_length: 1000,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.type).toBe(PipelineInputVarType.paragraph)
expect(result.maxLength).toBe(1000)
})
it('should handle number type with unit', () => {
- // Arrange
const inputVar = createInputVar({
type: PipelineInputVarType.number,
unit: 'meters',
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.type).toBe(PipelineInputVarType.number)
expect(result.unit).toBe('meters')
})
it('should handle select type with options', () => {
- // Arrange
const inputVar = createInputVar({
type: PipelineInputVarType.select,
options: ['Option A', 'Option B', 'Option C'],
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.type).toBe(PipelineInputVarType.select)
expect(result.options).toEqual(['Option A', 'Option B', 'Option C'])
})
it('should handle singleFile type', () => {
- // Arrange
const inputVar = createInputVar({
type: PipelineInputVarType.singleFile,
allowed_file_upload_methods: ['local_file'] as TransferMethod[],
@@ -856,16 +687,13 @@ describe('convertToInputFieldFormData', () => {
allowed_file_extensions: ['.jpg'],
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.type).toBe(PipelineInputVarType.singleFile)
expect(result.allowedFileUploadMethods).toEqual(['local_file'])
})
it('should handle multiFiles type', () => {
- // Arrange
const inputVar = createInputVar({
type: PipelineInputVarType.multiFiles,
max_length: 5,
@@ -874,42 +702,29 @@ describe('convertToInputFieldFormData', () => {
allowed_file_extensions: ['.pdf', '.doc'],
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.type).toBe(PipelineInputVarType.multiFiles)
expect(result.maxLength).toBe(5)
})
it('should handle checkbox type', () => {
- // Arrange
const inputVar = createInputVar({
type: PipelineInputVarType.checkbox,
default_value: 'true',
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(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', () => {
- // Arrange
const formData = createFormData({
type: PipelineInputVarType.textInput,
label: 'Test',
@@ -928,10 +743,8 @@ describe('convertFormDataToINputField', () => {
},
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(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', () => {
- // Arrange
const formData = createFormData({
default: undefined,
tooltips: undefined,
@@ -961,10 +773,8 @@ describe('convertFormDataToINputField', () => {
},
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(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', () => {
- // Arrange
const formData = createFormData({ maxLength: 256 })
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.max_length).toBe(256)
})
it('should map default to default_value', () => {
- // Arrange
const formData = createFormData({ default: 'my default' })
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.default_value).toBe('my default')
})
it('should map allowedFileUploadMethods to allowed_file_upload_methods', () => {
- // Arrange
const formData = createFormData({
allowedFileUploadMethods: ['local_file', 'remote_url'] as TransferMethod[],
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.allowed_file_upload_methods).toEqual([
'local_file',
'remote_url',
@@ -1018,7 +816,6 @@ describe('convertFormDataToINputField', () => {
})
it('should map allowedTypesAndExtensions to separate fields', () => {
- // Arrange
const formData = createFormData({
allowedTypesAndExtensions: {
allowedFileTypes: ['image', 'document'] as SupportUploadFileTypes[],
@@ -1026,119 +823,88 @@ describe('convertFormDataToINputField', () => {
},
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(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', () => {
- // Arrange
const formData = createFormData({ type: PipelineInputVarType.textInput })
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.type).toBe(PipelineInputVarType.textInput)
})
it('should preserve paragraph type', () => {
- // Arrange
const formData = createFormData({ type: PipelineInputVarType.paragraph })
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.type).toBe(PipelineInputVarType.paragraph)
})
it('should preserve select type with options', () => {
- // Arrange
const formData = createFormData({
type: PipelineInputVarType.select,
options: ['A', 'B', 'C'],
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.type).toBe(PipelineInputVarType.select)
expect(result.options).toEqual(['A', 'B', 'C'])
})
it('should preserve number type with unit', () => {
- // Arrange
const formData = createFormData({
type: PipelineInputVarType.number,
unit: 'kg',
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.type).toBe(PipelineInputVarType.number)
expect(result.unit).toBe('kg')
})
it('should preserve singleFile type', () => {
- // Arrange
const formData = createFormData({
type: PipelineInputVarType.singleFile,
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.type).toBe(PipelineInputVarType.singleFile)
})
it('should preserve multiFiles type with maxLength', () => {
- // Arrange
const formData = createFormData({
type: PipelineInputVarType.multiFiles,
maxLength: 10,
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.type).toBe(PipelineInputVarType.multiFiles)
expect(result.max_length).toBe(10)
})
it('should preserve checkbox type', () => {
- // Arrange
const formData = createFormData({ type: PipelineInputVarType.checkbox })
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.type).toBe(PipelineInputVarType.checkbox)
})
})
})
-// ============================================================================
-// Round-Trip Conversion Tests
-// ============================================================================
-
describe('Round-Trip Conversion', () => {
it('should preserve data through round-trip conversion for textInput', () => {
- // Arrange
const original = createInputVar({
type: PipelineInputVarType.textInput,
label: 'Test Label',
@@ -1150,11 +916,9 @@ describe('Round-Trip Conversion', () => {
placeholder: 'placeholder',
})
- // Act
const formData = convertToInputFieldFormData(original)
const result = convertFormDataToINputField(formData)
- // Assert
expect(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', () => {
- // Arrange
const original = createInputVar({
type: PipelineInputVarType.select,
options: ['Option A', 'Option B', 'Option C'],
default_value: 'Option A',
})
- // Act
const formData = convertToInputFieldFormData(original)
const result = convertFormDataToINputField(formData)
- // Assert
expect(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', () => {
- // Arrange
const original = createInputVar({
type: PipelineInputVarType.multiFiles,
max_length: 5,
@@ -1193,11 +953,9 @@ describe('Round-Trip Conversion', () => {
allowed_file_extensions: ['.jpg', '.pdf'],
})
- // Act
const formData = convertToInputFieldFormData(original)
const result = convertFormDataToINputField(formData)
- // Assert
expect(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', () => {
- // Arrange
const typesToTest = [
PipelineInputVarType.textInput,
PipelineInputVarType.paragraph,
@@ -1224,54 +981,39 @@ describe('Round-Trip Conversion', () => {
typesToTest.forEach((type) => {
const original = createInputVar({ type })
- // Act
const formData = convertToInputFieldFormData(original)
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.type).toBe(original.type)
})
})
})
-// ============================================================================
-// Edge Cases Tests
-// ============================================================================
-
describe('Edge Cases', () => {
describe('convertToInputFieldFormData edge cases', () => {
it('should handle zero maxLength', () => {
- // Arrange
const inputVar = createInputVar({ max_length: 0 })
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.maxLength).toBe(0)
})
it('should handle empty options array', () => {
- // Arrange
const inputVar = createInputVar({ options: [] })
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.options).toEqual([])
})
it('should handle options with special characters', () => {
- // Arrange
const inputVar = createInputVar({
options: ['<script>', '"quoted"', '\'apostrophe\'', '&amp;'],
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.options).toEqual([
'<script>',
'"quoted"',
@@ -1281,33 +1023,27 @@ describe('Edge Cases', () => {
})
it('should handle very long strings', () => {
- // Arrange
const longString = 'a'.repeat(10000)
const inputVar = createInputVar({
label: longString,
tooltips: longString,
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(result.label).toBe(longString)
expect(result.tooltips).toBe(longString)
})
it('should handle unicode characters', () => {
- // Arrange
const inputVar = createInputVar({
label: '测试标签 🎉',
tooltips: 'ツールチップ 😀',
placeholder: 'Platzhalter ñ é',
})
- // Act
const result = convertToInputFieldFormData(inputVar)
- // Assert
expect(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', () => {
- // Arrange
const formData = createFormData({ maxLength: 0 })
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.max_length).toBe(0)
})
it('should handle empty allowedTypesAndExtensions', () => {
- // Arrange
const formData = createFormData({
allowedTypesAndExtensions: {
allowedFileTypes: [],
@@ -1335,51 +1067,38 @@ describe('Edge Cases', () => {
},
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.allowed_file_types).toEqual([])
expect(result.allowed_file_extensions).toEqual([])
})
it('should handle boolean default value (checkbox)', () => {
- // Arrange
const formData = createFormData({
type: PipelineInputVarType.checkbox,
default: 'true',
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.default_value).toBe('true')
})
it('should handle numeric default value (number type)', () => {
- // Arrange
const formData = createFormData({
type: PipelineInputVarType.number,
default: '42',
})
- // Act
const result = convertFormDataToINputField(formData)
- // Assert
expect(result.default_value).toBe('42')
})
})
})
-// ============================================================================
-// Hook Memoization Tests
-// ============================================================================
-
describe('Hook Memoization', () => {
it('should return stable callback reference for handleSubmit', () => {
- // Arrange
const onSubmit = vi.fn()
let handleSubmitRef1: ((value: FormData) => void) | undefined
let handleSubmitRef2: ((value: FormData) => void) | undefined
@@ -1402,7 +1121,6 @@ describe('Hook Memoization', () => {
return null
}
- // Act
const { 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 useCallback
expect(handleSubmitRef1).toBe(handleSubmitRef2)
})
it('should return stable formData when initialData is unchanged', () => {
- // Arrange
const initialData = createInputVar()
let formData1: FormData | undefined
let formData2: FormData | undefined
@@ -1435,7 +1151,6 @@ describe('Hook Memoization', () => {
return null
}
- // Act
const { rerender } = render(
<TestComponent
data={initialData}
@@ -1449,7 +1164,6 @@ describe('Hook Memoization', () => {
/>,
)
- // Assert - formData should be same reference due to useMemo
expect(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.ts
new file mode 100644
index 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.tsx
similarity index 77%
rename from web/app/components/rag-pipeline/components/panel/input-field/editor/form/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/index.spec.tsx
index 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 objects
const 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 service
const mockFileUploadConfig = {
image_file_size_limit: 10,
file_size_limit: 15,
@@ -32,17 +25,12 @@ vi.mock('@/service/use-common', () => ({
}),
}))
-// Mock Toast static method
vi.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', () => {
- // Arrange
const props = createInputFieldFormProps()
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should render cancel button', () => {
- // Arrange
const props = createInputFieldFormProps()
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument()
})
it('should render form with initial values', () => {
- // Arrange
const initialData = createFormData({
variable: 'custom_var',
label: 'Custom Label',
})
const props = createInputFieldFormProps({ initialData })
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Props Variations Tests
- // -------------------------------------------------------------------------
describe('Props Variations', () => {
it('should handle supportFile=true prop', () => {
- // Arrange
const props = createInputFieldFormProps({ supportFile: true })
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should handle supportFile=false (default) prop', () => {
- // Arrange
const props = createInputFieldFormProps({ supportFile: false })
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should handle isEditMode=true prop', () => {
- // Arrange
const props = createInputFieldFormProps({ isEditMode: true })
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should handle isEditMode=false prop', () => {
- // Arrange
const props = createInputFieldFormProps({ isEditMode: false })
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should handle different initial data types', () => {
- // Arrange
const typesToTest = [
PipelineInputVarType.textInput,
PipelineInputVarType.paragraph,
@@ -214,49 +166,37 @@ describe('InputFieldForm', () => {
const initialData = createFormData({ type })
const props = createInputFieldFormProps({ initialData })
- // Act
const { container, unmount } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
unmount()
})
})
})
- // -------------------------------------------------------------------------
- // User Interaction Tests
- // -------------------------------------------------------------------------
describe('User Interactions', () => {
it('should call onCancel when cancel button is clicked', async () => {
- // Arrange
const onCancel = vi.fn()
const props = createInputFieldFormProps({ onCancel })
- // Act
renderWithProviders(<InputFieldForm {...props} />)
fireEvent.click(screen.getByRole('button', { name: /cancel/i }))
- // Assert
expect(onCancel).toHaveBeenCalledTimes(1)
})
it('should prevent default on form submit', async () => {
- // Arrange
const props = createInputFieldFormProps()
const { container } = renderWithProviders(<InputFieldForm {...props} />)
const form = container.querySelector('form')!
const submitEvent = new Event('submit', { bubbles: true, cancelable: true })
- // Act
form.dispatchEvent(submitEvent)
- // Assert
expect(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 })
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
const form = container.querySelector('form')!
fireEvent.submit(form)
- // Assert - Toast should be called with error message when validation fails
await waitFor(() => {
expect(Toast.default.notify).toHaveBeenCalledWith(
expect.objectContaining({
@@ -279,12 +217,10 @@ describe('InputFieldForm', () => {
}),
)
})
- // onSubmit should not be called when validation fails
expect(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,
})
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Find and change the variable input by label
const variableInput = screen.getByLabelText('appDebug.variableConfig.varName')
fireEvent.change(variableInput, { target: { value: 'new_var' } })
- // Submit the form
const form = document.querySelector('form')!
fireEvent.submit(form)
- // Assert - onSubmit should be called with moreInfo containing variable name change info
await 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 same
const initialData = createFormData({
variable: 'same_var',
label: 'Test Label',
@@ -337,14 +268,11 @@ describe('InputFieldForm', () => {
isEditMode: true,
})
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Submit without changing variable name
const 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 () => {
- // Arrange
const initialData = createFormData({
variable: 'test_var',
label: 'Test Label',
@@ -368,14 +295,11 @@ describe('InputFieldForm', () => {
isEditMode: false,
})
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Submit the form
const form = document.querySelector('form')!
fireEvent.submit(form)
- // Assert - onSubmit should be called without moreInfo since not in edit mode
await 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', () => {
- // Arrange
const props = createInputFieldFormProps()
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Assert - ShowAllSettings component should be visible when showAllSettings is false
expect(screen.queryByText(/appDebug.variableConfig.showAllSettings/i)).toBeInTheDocument()
})
it('should toggle showAllSettings state when clicking show all settings', async () => {
- // Arrange
const props = createInputFieldFormProps()
renderWithProviders(<InputFieldForm {...props} />)
- // Act - Find and click the show all settings element
const 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 visible
await waitFor(() => {
expect(screen.queryByText(/appDebug.variableConfig.showAllSettings/i)).not.toBeInTheDocument()
})
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should maintain stable onCancel callback reference', () => {
- // Arrange
const onCancel = vi.fn()
const props = createInputFieldFormProps({ onCancel })
- // Act
renderWithProviders(<InputFieldForm {...props} />)
const cancelButton = screen.getByRole('button', { name: /cancel/i })
fireEvent.click(cancelButton)
fireEvent.click(cancelButton)
- // Assert
expect(onCancel).toHaveBeenCalledTimes(2)
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle empty initial data gracefully', () => {
- // Arrange
const props = createInputFieldFormProps({
initialData: {} as Record<string, unknown>,
})
- // Act & Assert - should not crash
expect(() => renderWithProviders(<InputFieldForm {...props} />)).not.toThrow()
})
it('should handle undefined optional fields', () => {
- // Arrange
const initialData = {
type: PipelineInputVarType.textInput,
label: 'Test',
@@ -464,75 +367,57 @@ describe('InputFieldForm', () => {
allowedFileTypes: [],
allowedFileExtensions: [],
},
- // Other fields are undefined
}
const props = createInputFieldFormProps({ initialData })
- // Act & Assert
expect(() => renderWithProviders(<InputFieldForm {...props} />)).not.toThrow()
})
it('should handle special characters in variable name', () => {
- // Arrange
const initialData = createFormData({
variable: 'test_var_123',
label: 'Test Label <script>',
})
const props = createInputFieldFormProps({ initialData })
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenFieldNames(PipelineInputVarType.textInput),
)
- // Assert - should include default value, placeholder, tooltips
expect(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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenFieldNames(PipelineInputVarType.paragraph),
)
- // Assert
expect(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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenFieldNames(PipelineInputVarType.number),
)
- // Assert - should include unit field
expect(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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenFieldNames(PipelineInputVarType.select),
)
- // Assert
expect(result.current).toContain('appDebug.variableConfig.defaultValue'.toLowerCase())
expect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())
})
it('should return correct field names for singleFile type', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenFieldNames(PipelineInputVarType.singleFile),
)
- // Assert
expect(result.current).toContain('appDebug.variableConfig.uploadMethod'.toLowerCase())
expect(result.current).toContain('appDebug.variableConfig.tooltips'.toLowerCase())
})
it('should return correct field names for multiFiles type', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenFieldNames(PipelineInputVarType.multiFiles),
)
- // Assert
expect(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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenFieldNames(PipelineInputVarType.checkbox),
)
- // Assert
expect(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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenFieldNames('unknown_type' as PipelineInputVarType),
)
- // Assert - should only contain tooltips for unknown types
expect(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', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
- // Act
const { result } = renderHookWithProviders(() =>
useConfigurations({
getFieldValue: mockGetFieldValue,
@@ -628,17 +491,14 @@ describe('useConfigurations', () => {
}),
)
- // Assert
expect(Array.isArray(result.current)).toBe(true)
expect(result.current.length).toBeGreaterThan(0)
})
it('should include type field configuration', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
- // Act
const { result } = renderHookWithProviders(() =>
useConfigurations({
getFieldValue: mockGetFieldValue,
@@ -647,18 +507,15 @@ describe('useConfigurations', () => {
}),
)
- // Assert
const typeConfig = result.current.find(config => config.variable === 'type')
expect(typeConfig).toBeDefined()
expect(typeConfig?.required).toBe(true)
})
it('should include variable field configuration', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
- // Act
const { result } = renderHookWithProviders(() =>
useConfigurations({
getFieldValue: mockGetFieldValue,
@@ -667,18 +524,15 @@ describe('useConfigurations', () => {
}),
)
- // Assert
const variableConfig = result.current.find(config => config.variable === 'variable')
expect(variableConfig).toBeDefined()
expect(variableConfig?.required).toBe(true)
})
it('should include label field configuration', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
- // Act
const { result } = renderHookWithProviders(() =>
useConfigurations({
getFieldValue: mockGetFieldValue,
@@ -687,18 +541,15 @@ describe('useConfigurations', () => {
}),
)
- // Assert
const labelConfig = result.current.find(config => config.variable === 'label')
expect(labelConfig).toBeDefined()
expect(labelConfig?.required).toBe(false)
})
it('should include required field configuration', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
- // Act
const { result } = renderHookWithProviders(() =>
useConfigurations({
getFieldValue: mockGetFieldValue,
@@ -707,17 +558,14 @@ describe('useConfigurations', () => {
}),
)
- // Assert
const requiredConfig = result.current.find(config => config.variable === 'required')
expect(requiredConfig).toBeDefined()
})
it('should pass supportFile prop to type configuration', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
- // Act
const { result } = renderHookWithProviders(() =>
useConfigurations({
getFieldValue: mockGetFieldValue,
@@ -726,18 +574,13 @@ describe('useConfigurations', () => {
}),
)
- // Assert
const 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', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
@@ -749,17 +592,14 @@ describe('useConfigurations', () => {
}),
)
- // Act
const typeConfig = result.current.find(config => config.variable === 'type')
typeConfig?.listeners?.onChange?.(createMockEvent(PipelineInputVarType.singleFile))
- // Assert
expect(mockSetFieldValue).toHaveBeenCalledWith('allowedFileUploadMethods', expect.any(Array))
expect(mockSetFieldValue).toHaveBeenCalledWith('allowedTypesAndExtensions', expect.any(Object))
})
it('should call setFieldValue when type changes to multiFiles', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
@@ -771,16 +611,13 @@ describe('useConfigurations', () => {
}),
)
- // Act
const typeConfig = result.current.find(config => config.variable === 'type')
typeConfig?.listeners?.onChange?.(createMockEvent(PipelineInputVarType.multiFiles))
- // Assert
expect(mockSetFieldValue).toHaveBeenCalledWith('maxLength', expect.any(Number))
})
it('should set label from variable name on blur when label is empty', () => {
- // Arrange
const mockGetFieldValue = vi.fn().mockReturnValue('')
const mockSetFieldValue = vi.fn()
@@ -792,16 +629,13 @@ describe('useConfigurations', () => {
}),
)
- // Act
const variableConfig = result.current.find(config => config.variable === 'variable')
variableConfig?.listeners?.onBlur?.(createMockEvent('test_variable'))
- // Assert
expect(mockSetFieldValue).toHaveBeenCalledWith('label', 'test_variable')
})
it('should not set label from variable name on blur when label is not empty', () => {
- // Arrange
const mockGetFieldValue = vi.fn().mockReturnValue('Existing Label')
const mockSetFieldValue = vi.fn()
@@ -813,16 +647,13 @@ describe('useConfigurations', () => {
}),
)
- // Act
const variableConfig = result.current.find(config => config.variable === 'variable')
variableConfig?.listeners?.onBlur?.(createMockEvent('test_variable'))
- // Assert
expect(mockSetFieldValue).not.toHaveBeenCalled()
})
it('should reset label to variable name when display name is cleared', () => {
- // Arrange
const mockGetFieldValue = vi.fn().mockReturnValue('original_var')
const mockSetFieldValue = vi.fn()
@@ -834,25 +665,18 @@ describe('useConfigurations', () => {
}),
)
- // Act
const labelConfig = result.current.find(config => config.variable === 'label')
labelConfig?.listeners?.onBlur?.(createMockEvent(''))
- // Assert
expect(mockSetFieldValue).toHaveBeenCalledWith('label', 'original_var')
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should return configurations array with correct length', () => {
- // Arrange
const mockGetFieldValue = vi.fn()
const mockSetFieldValue = vi.fn()
- // Act
const { result } = renderHookWithProviders(() =>
useConfigurations({
getFieldValue: mockGetFieldValue,
@@ -861,77 +685,59 @@ describe('useConfigurations', () => {
}),
)
- // Assert - should have all expected field configurations
expect(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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
expect(Array.isArray(result.current)).toBe(true)
expect(result.current.length).toBeGreaterThan(0)
})
it('should include default value configurations for different types', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
const defaultConfigs = result.current.filter(config => config.variable === 'default')
expect(defaultConfigs.length).toBeGreaterThan(0)
})
it('should include tooltips configuration', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
const tooltipsConfig = result.current.find(config => config.variable === 'tooltips')
expect(tooltipsConfig).toBeDefined()
expect(tooltipsConfig?.showConditions).toEqual([])
})
it('should include placeholder configurations', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
const placeholderConfigs = result.current.filter(config => config.variable === 'placeholder')
expect(placeholderConfigs.length).toBeGreaterThan(0)
})
it('should include unit configuration for number type', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
const 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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
const uploadMethodConfigs = result.current.filter(
config => config.variable === 'allowedFileUploadMethods',
)
@@ -954,12 +758,10 @@ describe('useHiddenConfigurations', () => {
})
it('should include maxLength configuration for multiFiles', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
const 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', () => {
- // Arrange
const options = ['Option A', 'Option B', 'Option C']
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options }),
)
- // Assert
const 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', () => {
- // Arrange
const options = ['Option A']
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options }),
)
- // Assert
const 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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
const 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', () => {
- // Act
const { result } = renderHookWithProviders(() =>
useHiddenConfigurations({ options: undefined }),
)
- // Assert
const 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 requirements
const 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', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const invalidData = { variable: '', label: 'Test', required: true, type: 'text-input' }
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
it('should validate variable max length', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const invalidData = {
variable: 'a'.repeat(100),
@@ -1082,15 +856,12 @@ describe('createInputFieldSchema', () => {
maxLength: 48,
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
it('should validate variable does not start with number', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const invalidData = {
variable: '123var',
@@ -1100,15 +871,12 @@ describe('createInputFieldSchema', () => {
maxLength: 48,
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
it('should validate variable format (alphanumeric and underscore)', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const invalidData = {
variable: 'var-name',
@@ -1118,15 +886,12 @@ describe('createInputFieldSchema', () => {
maxLength: 48,
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
it('should accept valid variable name', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'valid_var_123',
@@ -1136,15 +901,12 @@ describe('createInputFieldSchema', () => {
maxLength: 48,
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
it('should validate required label field', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const invalidData = {
variable: 'test_var',
@@ -1154,20 +916,14 @@ describe('createInputFieldSchema', () => {
maxLength: 48,
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
})
- // -------------------------------------------------------------------------
- // Text Input Schema Tests
- // -------------------------------------------------------------------------
describe('Text Input Schema', () => {
it('should validate maxLength within bounds', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1177,15 +933,12 @@ describe('createInputFieldSchema', () => {
maxLength: 100,
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
it('should reject maxLength exceeding TEXT_MAX_LENGTH', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const invalidData = {
variable: 'test_var',
@@ -1195,15 +948,12 @@ describe('createInputFieldSchema', () => {
maxLength: TEXT_MAX_LENGTH + 1,
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
it('should reject maxLength less than 1', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const invalidData = {
variable: 'test_var',
@@ -1213,15 +963,12 @@ describe('createInputFieldSchema', () => {
maxLength: 0,
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
it('should allow optional default value', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.textInput, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1232,20 +979,14 @@ describe('createInputFieldSchema', () => {
default: 'default value',
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
})
- // -------------------------------------------------------------------------
- // Paragraph Schema Tests
- // -------------------------------------------------------------------------
describe('Paragraph Schema', () => {
it('should validate paragraph type similar to textInput', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.paragraph, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1255,20 +996,14 @@ describe('createInputFieldSchema', () => {
maxLength: 100,
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
})
- // -------------------------------------------------------------------------
- // Number Schema Tests
- // -------------------------------------------------------------------------
describe('Number Schema', () => {
it('should allow optional default number', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.number, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1278,15 +1013,12 @@ describe('createInputFieldSchema', () => {
default: 42,
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
it('should allow optional unit', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.number, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1296,20 +1028,14 @@ describe('createInputFieldSchema', () => {
unit: 'kg',
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
})
- // -------------------------------------------------------------------------
- // Select Schema Tests
- // -------------------------------------------------------------------------
describe('Select Schema', () => {
it('should require non-empty options array', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.select, mockT, { maxFileUploadLimit: 10 })
const invalidData = {
variable: 'test_var',
@@ -1319,15 +1045,12 @@ describe('createInputFieldSchema', () => {
options: [],
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
it('should accept valid options array', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.select, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1337,15 +1060,12 @@ describe('createInputFieldSchema', () => {
options: ['Option 1', 'Option 2'],
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
it('should reject duplicate options', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.select, mockT, { maxFileUploadLimit: 10 })
const invalidData = {
variable: 'test_var',
@@ -1355,20 +1075,14 @@ describe('createInputFieldSchema', () => {
options: ['Option 1', 'Option 1'],
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
})
- // -------------------------------------------------------------------------
- // Single File Schema Tests
- // -------------------------------------------------------------------------
describe('Single File Schema', () => {
it('should validate allowedFileUploadMethods', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.singleFile, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1381,15 +1095,12 @@ describe('createInputFieldSchema', () => {
},
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
it('should validate allowedTypesAndExtensions', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.singleFile, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1403,20 +1114,14 @@ describe('createInputFieldSchema', () => {
},
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
})
- // -------------------------------------------------------------------------
- // Multi Files Schema Tests
- // -------------------------------------------------------------------------
describe('Multi Files Schema', () => {
it('should validate maxLength within file upload limit', () => {
- // Arrange
const maxFileUploadLimit = 10
const schema = createInputFieldSchema(PipelineInputVarType.multiFiles, mockT, { maxFileUploadLimit })
const validData = {
@@ -1431,15 +1136,12 @@ describe('createInputFieldSchema', () => {
maxLength: 5,
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
it('should reject maxLength exceeding file upload limit', () => {
- // Arrange
const maxFileUploadLimit = 10
const schema = createInputFieldSchema(PipelineInputVarType.multiFiles, mockT, { maxFileUploadLimit })
const invalidData = {
@@ -1454,20 +1156,14 @@ describe('createInputFieldSchema', () => {
maxLength: 15,
}
- // Act
const result = schema.safeParse(invalidData)
- // Assert
expect(result.success).toBe(false)
})
})
- // -------------------------------------------------------------------------
- // Default Schema Tests (for checkbox and other types)
- // -------------------------------------------------------------------------
describe('Default Schema', () => {
it('should validate checkbox type with common schema', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.checkbox, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1476,15 +1172,12 @@ describe('createInputFieldSchema', () => {
type: 'checkbox',
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(result.success).toBe(true)
})
it('should allow passthrough of additional fields', () => {
- // Arrange
const schema = createInputFieldSchema(PipelineInputVarType.checkbox, mockT, { maxFileUploadLimit: 10 })
const validData = {
variable: 'test_var',
@@ -1494,10 +1187,8 @@ describe('createInputFieldSchema', () => {
extraField: 'extra value',
}
- // Act
const result = schema.safeParse(validData)
- // Assert
expect(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 too
const 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', () => {
- // Arrange
const initialData = createFormData()
const props = createInputFieldFormProps({ initialData })
- // Act
const { container } = renderWithProviders(<InputFieldForm {...props} />)
- // Assert
expect(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 label
const initialData = createFormData({
variable: '',
label: '', // Empty label to trigger the condition
})
const props = createInputFieldFormProps({ initialData })
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Find the variable input and trigger blur with a value
const 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 empty
await waitFor(() => {
const labelInput = screen.getByLabelText('appDebug.variableConfig.displayName')
- // Label should be set to the variable value when it was empty
expect(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 label
const initialData = createFormData({
variable: '',
label: 'Existing Label', // Label already has value
})
const props = createInputFieldFormProps({ initialData })
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Find the variable input and trigger blur with a value
const 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 value
await 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 label
const initialData = createFormData({
variable: 'original_var',
label: 'Some Label',
})
const props = createInputFieldFormProps({ initialData })
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Find the label input, clear it, and trigger blur
const 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 name
await waitFor(() => {
expect(labelInput).toHaveValue('original_var')
})
})
it('should keep label value when display name blur event fires with non-empty value', async () => {
- // Arrange
const initialData = createFormData({
variable: 'test_var',
label: 'Original Label',
})
const props = createInputFieldFormProps({ initialData })
- // Act
renderWithProviders(<InputFieldForm {...props} />)
- // Find the label input, change it to a new value, and trigger blur
const labelInput = screen.getByLabelText('appDebug.variableConfig.displayName')
fireEvent.change(labelInput, { target: { value: 'New Label' } })
fireEvent.blur(labelInput)
- // Assert - Label should keep the new non-empty value
await 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.tsx
similarity index 80%
rename from web/app/components/rag-pipeline/components/panel/input-field/field-list/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/input-field/field-list/__tests__/index.spec.tsx
index 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 useHover
let mockIsHovering = false
const getMockIsHovering = () => mockIsHovering
@@ -23,7 +18,6 @@ vi.mock('ahooks', async (importOriginal) => {
}
})
-// Mock react-sortablejs
vi.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 items
const newList = [...list]
const temp = newList[0]
newList[0] = newList[1]
@@ -56,7 +49,6 @@ vi.mock('react-sortablejs', () => ({
<button
data-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 hook
const 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 hook
const mockToggleInputFieldEditPanel = vi.fn()
vi.mock('@/app/components/rag-pipeline/hooks', () => ({
@@ -88,14 +78,12 @@ vi.mock('@/app/components/rag-pipeline/hooks', () => ({
}),
}))
-// Mock Toast
vi.mock('@/app/components/base/toast', () => ({
default: {
notify: vi.fn(),
},
}))
-// Mock RemoveEffectVarConfirm
vi.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', () => {
- // Arrange
const payload = createInputVar({ variable: 'my_field' })
- // Act
render(
<FieldItem
payload={payload}
@@ -183,15 +158,12 @@ describe('FieldItem', () => {
/>,
)
- // Assert
expect(screen.getByText('my_field')).toBeInTheDocument()
})
it('should render field item with label when provided', () => {
- // Arrange
const payload = createInputVar({ variable: 'field', label: 'Field Label' })
- // Act
render(
<FieldItem
payload={payload}
@@ -201,15 +173,12 @@ describe('FieldItem', () => {
/>,
)
- // Assert
expect(screen.getByText('Field Label')).toBeInTheDocument()
})
it('should not render label when empty', () => {
- // Arrange
const payload = createInputVar({ variable: 'field', label: '' })
- // Act
render(
<FieldItem
payload={payload}
@@ -219,16 +188,13 @@ describe('FieldItem', () => {
/>,
)
- // Assert
expect(screen.queryByText('·')).not.toBeInTheDocument()
})
it('should render required badge when not hovering and required is true', () => {
- // Arrange
mockIsHovering = false
const payload = createInputVar({ required: true })
- // Act
render(
<FieldItem
payload={payload}
@@ -238,16 +204,13 @@ describe('FieldItem', () => {
/>,
)
- // Assert
expect(screen.getByText(/required/i)).toBeInTheDocument()
})
it('should not render required badge when required is false', () => {
- // Arrange
mockIsHovering = false
const payload = createInputVar({ required: false })
- // Act
render(
<FieldItem
payload={payload}
@@ -257,16 +220,13 @@ describe('FieldItem', () => {
/>,
)
- // Assert
expect(screen.queryByText(/required/i)).not.toBeInTheDocument()
})
it('should render InputField icon when not hovering', () => {
- // Arrange
mockIsHovering = false
const payload = createInputVar()
- // Act
const { container } = render(
<FieldItem
payload={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', () => {
- // Arrange
mockIsHovering = true
const payload = createInputVar()
- // Act
const { container } = render(
<FieldItem
payload={payload}
@@ -297,17 +254,14 @@ describe('FieldItem', () => {
/>,
)
- // Assert - RiDraggable icon should be present
const icons = container.querySelectorAll('svg')
expect(icons.length).toBeGreaterThan(0)
})
it('should render edit and delete buttons when hovering and not readonly', () => {
- // Arrange
mockIsHovering = true
const payload = createInputVar()
- // Act
render(
<FieldItem
payload={payload}
@@ -318,17 +272,14 @@ describe('FieldItem', () => {
/>,
)
- // Assert
const buttons = screen.getAllByRole('button')
expect(buttons.length).toBe(2) // Edit and Delete buttons
})
it('should not render edit and delete buttons when readonly', () => {
- // Arrange
mockIsHovering = true
const payload = createInputVar()
- // Act
render(
<FieldItem
payload={payload}
@@ -339,23 +290,17 @@ describe('FieldItem', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
mockIsHovering = true
const onClickEdit = vi.fn()
const payload = createInputVar({ variable: 'test_var' })
- // Act
render(
<FieldItem
payload={payload}
@@ -367,17 +312,14 @@ describe('FieldItem', () => {
const buttons = screen.getAllByRole('button')
fireEvent.click(buttons[0]) // Edit button
- // Assert
expect(onClickEdit).toHaveBeenCalledWith('test_var')
})
it('should call onRemove with index when delete button is clicked', () => {
- // Arrange
mockIsHovering = true
const onRemove = vi.fn()
const payload = createInputVar()
- // Act
render(
<FieldItem
payload={payload}
@@ -389,17 +331,14 @@ describe('FieldItem', () => {
const buttons = screen.getAllByRole('button')
fireEvent.click(buttons[1]) // Delete button
- // Assert
expect(onRemove).toHaveBeenCalledWith(5)
})
it('should not call onClickEdit when readonly', () => {
- // Arrange
mockIsHovering = true
const onClickEdit = vi.fn()
const payload = createInputVar()
- // Render without readonly to get buttons, then check behavior
const { rerender } = render(
<FieldItem
payload={payload}
@@ -410,7 +349,6 @@ describe('FieldItem', () => {
/>,
)
- // Re-render with readonly but buttons still exist from previous state check
rerender(
<FieldItem
payload={payload}
@@ -421,18 +359,15 @@ describe('FieldItem', () => {
/>,
)
- // Assert - no buttons should be rendered when readonly
expect(screen.queryAllByRole('button').length).toBe(0)
})
it('should stop event propagation when edit button is clicked', () => {
- // Arrange
mockIsHovering = true
const onClickEdit = vi.fn()
const parentClick = vi.fn()
const payload = createInputVar()
- // Act
render(
<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 stopPropagation
expect(onClickEdit).toHaveBeenCalled()
expect(parentClick).not.toHaveBeenCalled()
})
it('should stop event propagation when delete button is clicked', () => {
- // Arrange
mockIsHovering = true
const onRemove = vi.fn()
const parentClick = vi.fn()
const payload = createInputVar()
- // Act
render(
<div onClick={parentClick}>
<FieldItem
@@ -472,23 +404,17 @@ describe('FieldItem', () => {
const buttons = screen.getAllByRole('button')
fireEvent.click(buttons[1])
- // Assert
expect(onRemove).toHaveBeenCalled()
expect(parentClick).not.toHaveBeenCalled()
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should maintain stable handleOnClickEdit when props dont change', () => {
- // Arrange
mockIsHovering = true
const onClickEdit = vi.fn()
const payload = createInputVar()
- // Act
const { rerender } = render(
<FieldItem
payload={payload}
@@ -511,21 +437,15 @@ describe('FieldItem', () => {
const buttonsAfterRerender = screen.getAllByRole('button')
fireEvent.click(buttonsAfterRerender[0])
- // Assert
expect(onClickEdit).toHaveBeenCalledTimes(2)
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle very long variable names with truncation', () => {
- // Arrange
const longVariable = 'a'.repeat(200)
const payload = createInputVar({ variable: longVariable })
- // Act
render(
<FieldItem
payload={payload}
@@ -535,17 +455,14 @@ describe('FieldItem', () => {
/>,
)
- // Assert
const varElement = screen.getByTitle(longVariable)
expect(varElement).toHaveClass('truncate')
})
it('should handle very long label names with truncation', () => {
- // Arrange
const longLabel = 'b'.repeat(200)
const payload = createInputVar({ label: longLabel })
- // Act
render(
<FieldItem
payload={payload}
@@ -555,19 +472,16 @@ describe('FieldItem', () => {
/>,
)
- // Assert
const labelElement = screen.getByTitle(longLabel)
expect(labelElement).toHaveClass('truncate')
})
it('should handle special characters in variable and label', () => {
- // Arrange
const payload = createInputVar({
variable: '<test>&"var\'',
label: '<label>&"test\'',
})
- // Act
render(
<FieldItem
payload={payload}
@@ -577,19 +491,16 @@ describe('FieldItem', () => {
/>,
)
- // Assert
expect(screen.getByText('<test>&"var\'')).toBeInTheDocument()
expect(screen.getByText('<label>&"test\'')).toBeInTheDocument()
})
it('should handle unicode characters', () => {
- // Arrange
const payload = createInputVar({
variable: '变量_🎉',
label: '标签_😀',
})
- // Act
render(
<FieldItem
payload={payload}
@@ -599,13 +510,11 @@ describe('FieldItem', () => {
/>,
)
- // Assert
expect(screen.getByText('变量_🎉')).toBeInTheDocument()
expect(screen.getByText('标签_😀')).toBeInTheDocument()
})
it('should render different input types correctly', () => {
- // Arrange
const types = [
PipelineInputVarType.textInput,
PipelineInputVarType.paragraph,
@@ -619,7 +528,6 @@ describe('FieldItem', () => {
types.forEach((type) => {
const payload = createInputVar({ type })
- // Act
const { unmount } = render(
<FieldItem
payload={payload}
@@ -629,24 +537,18 @@ describe('FieldItem', () => {
/>,
)
- // Assert
expect(screen.getByText('test_variable')).toBeInTheDocument()
unmount()
})
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should be memoized with React.memo', () => {
- // Arrange
const payload = createInputVar()
const onClickEdit = vi.fn()
const onRemove = vi.fn()
- // Act
const { rerender } = render(
<FieldItem
payload={payload}
@@ -656,7 +558,6 @@ describe('FieldItem', () => {
/>,
)
- // Rerender with same props
rerender(
<FieldItem
payload={payload}
@@ -666,21 +567,15 @@ describe('FieldItem', () => {
/>,
)
- // Assert - component should still render correctly
expect(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', () => {
- // Arrange
mockIsHovering = true
const payload = createInputVar()
- // Act
render(
<FieldItem
payload={payload}
@@ -691,16 +586,13 @@ describe('FieldItem', () => {
/>,
)
- // Assert - no action buttons should be rendered
expect(screen.queryAllByRole('button')).toHaveLength(0)
})
it('should render type icon and required badge in readonly mode when hovering', () => {
- // Arrange
mockIsHovering = true
const payload = createInputVar({ required: true })
- // Act
render(
<FieldItem
payload={payload}
@@ -711,15 +603,12 @@ describe('FieldItem', () => {
/>,
)
- // Assert - required badge should be visible instead of action buttons
expect(screen.getByText(/required/i)).toBeInTheDocument()
})
it('should apply cursor-default class when readonly', () => {
- // Arrange
const payload = createInputVar()
- // Act
const { container } = render(
<FieldItem
payload={payload}
@@ -730,17 +619,14 @@ describe('FieldItem', () => {
/>,
)
- // Assert
const fieldItem = container.firstChild as HTMLElement
expect(fieldItem.className).toContain('cursor-default')
})
it('should apply cursor-all-scroll class when hovering and not readonly', () => {
- // Arrange
mockIsHovering = true
const payload = createInputVar()
- // Act
const { container } = render(
<FieldItem
payload={payload}
@@ -751,32 +637,22 @@ describe('FieldItem', () => {
/>,
)
- // Assert
const fieldItem = container.firstChild as HTMLElement
expect(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', () => {
- // Arrange
const inputFields = createInputVarList(2)
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -786,15 +662,12 @@ describe('FieldListContainer', () => {
/>,
)
- // Assert
expect(screen.getByTestId('sortable-container')).toBeInTheDocument()
})
it('should render all field items', () => {
- // Arrange
const inputFields = createInputVarList(3)
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -804,14 +677,12 @@ describe('FieldListContainer', () => {
/>,
)
- // Assert
expect(screen.getByText('var_0')).toBeInTheDocument()
expect(screen.getByText('var_1')).toBeInTheDocument()
expect(screen.getByText('var_2')).toBeInTheDocument()
})
it('should render empty list without errors', () => {
- // Act
render(
<FieldListContainer
inputFields={[]}
@@ -821,15 +692,12 @@ describe('FieldListContainer', () => {
/>,
)
- // Assert
expect(screen.getByTestId('sortable-container')).toBeInTheDocument()
})
it('should apply custom className', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
render(
<FieldListContainer
className="custom-class"
@@ -840,16 +708,13 @@ describe('FieldListContainer', () => {
/>,
)
- // Assert
const container = screen.getByTestId('sortable-container')
expect(container.className).toContain('custom-class')
})
it('should disable sorting when readonly is true', () => {
- // Arrange
const inputFields = createInputVarList(2)
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -860,22 +725,16 @@ describe('FieldListContainer', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const inputFields = createInputVarList(2)
const onListSortChange = vi.fn()
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -886,16 +745,13 @@ describe('FieldListContainer', () => {
)
fireEvent.click(screen.getByTestId('trigger-sort'))
- // Assert
expect(onListSortChange).toHaveBeenCalled()
})
it('should not call onListSortChange when list hasnt changed', () => {
- // Arrange
const inputFields = [createInputVar()]
const onListSortChange = vi.fn()
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -906,16 +762,13 @@ describe('FieldListContainer', () => {
)
fireEvent.click(screen.getByTestId('trigger-sort'))
- // Assert - with only one item, no reorder happens
expect(onListSortChange).not.toHaveBeenCalled()
})
it('should not call onListSortChange when disabled', () => {
- // Arrange
const inputFields = createInputVarList(2)
const onListSortChange = vi.fn()
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -927,16 +780,13 @@ describe('FieldListContainer', () => {
)
fireEvent.click(screen.getByTestId('trigger-sort'))
- // Assert
expect(onListSortChange).not.toHaveBeenCalled()
})
it('should not call onListSortChange when list order is unchanged (isEqual check)', () => {
- // Arrange - This tests line 42 in field-list-container.tsx
const inputFields = createInputVarList(2)
const onListSortChange = vi.fn()
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -945,20 +795,16 @@ describe('FieldListContainer', () => {
onEditField={vi.fn()}
/>,
)
- // Trigger same sort - passes same list to setList
fireEvent.click(screen.getByTestId('trigger-same-sort'))
- // Assert - onListSortChange should NOT be called due to isEqual check
expect(onListSortChange).not.toHaveBeenCalled()
})
it('should pass onEditField to FieldItem', () => {
- // Arrange
mockIsHovering = true
const inputFields = createInputVarList(1)
const onEditField = vi.fn()
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -970,17 +816,14 @@ describe('FieldListContainer', () => {
const buttons = screen.getAllByRole('button')
fireEvent.click(buttons[0]) // Edit button
- // Assert
expect(onEditField).toHaveBeenCalledWith('var_0')
})
it('should pass onRemoveField to FieldItem', () => {
- // Arrange
mockIsHovering = true
const inputFields = createInputVarList(1)
const onRemoveField = vi.fn()
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -992,24 +835,18 @@ describe('FieldListContainer', () => {
const buttons = screen.getAllByRole('button')
fireEvent.click(buttons[1]) // Delete button
- // Assert
expect(onRemoveField).toHaveBeenCalledWith(0)
})
})
- // -------------------------------------------------------------------------
- // List Conversion Tests
- // -------------------------------------------------------------------------
describe('List Conversion', () => {
it('should convert InputVar[] to SortableItem[]', () => {
- // Arrange
const inputFields = [
createInputVar({ variable: 'var1' }),
createInputVar({ variable: 'var2' }),
]
const onListSortChange = vi.fn()
- // Act
render(
<FieldListContainer
inputFields={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', () => {
- // Arrange
const inputFields = createInputVarList(2)
const onListSortChange = vi.fn()
- // Act
const { rerender } = render(
<FieldListContainer
inputFields={inputFields}
@@ -1057,15 +888,12 @@ describe('FieldListContainer', () => {
/>,
)
- // Assert - component should still render correctly
expect(screen.getByText('var_0')).toBeInTheDocument()
})
it('should be memoized with React.memo', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
const { rerender } = render(
<FieldListContainer
inputFields={inputFields}
@@ -1075,7 +903,6 @@ describe('FieldListContainer', () => {
/>,
)
- // Rerender with same props
rerender(
<FieldListContainer
inputFields={inputFields}
@@ -1085,20 +912,14 @@ describe('FieldListContainer', () => {
/>,
)
- // Assert
expect(screen.getByText('var_0')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle large list of items', () => {
- // Arrange
const inputFields = createInputVarList(100)
- // Act
render(
<FieldListContainer
inputFields={inputFields}
@@ -1108,14 +929,11 @@ describe('FieldListContainer', () => {
/>,
)
- // Assert
expect(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 TypeScript
expect(() =>
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', () => {
- // Arrange
const inputFields = createInputVarList(2)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1160,16 +969,13 @@ describe('FieldList', () => {
/>,
)
- // Assert
expect(screen.getByText('Label Content')).toBeInTheDocument()
expect(screen.getByText('var_0')).toBeInTheDocument()
})
it('should render add button', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1180,7 +986,6 @@ describe('FieldList', () => {
/>,
)
- // Assert
const addButton = screen.getAllByRole('button').find(btn =>
btn.querySelector('svg'),
)
@@ -1188,10 +993,8 @@ describe('FieldList', () => {
})
it('should disable add button when readonly', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1203,7 +1006,6 @@ describe('FieldList', () => {
/>,
)
- // Assert
const addButton = screen.getAllByRole('button').find(btn =>
btn.querySelector('svg'),
)
@@ -1211,10 +1013,8 @@ describe('FieldList', () => {
})
it('should apply custom labelClassName', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
const { container } = render(
<FieldList
nodeId="node-1"
@@ -1226,21 +1026,15 @@ describe('FieldList', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1256,15 +1050,12 @@ describe('FieldList', () => {
if (addButton)
fireEvent.click(addButton)
- // Assert
expect(mockToggleInputFieldEditPanel).toHaveBeenCalled()
})
it('should not open editor when readonly and add button clicked', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1281,21 +1072,15 @@ describe('FieldList', () => {
if (addButton)
fireEvent.click(addButton)
- // Assert - button is disabled so click shouldnt work
expect(mockToggleInputFieldEditPanel).not.toHaveBeenCalled()
})
})
- // -------------------------------------------------------------------------
- // Callback Tests
- // -------------------------------------------------------------------------
describe('Callback Handling', () => {
it('should call handleInputFieldsChange with nodeId when fields change', () => {
- // Arrange
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-123"
@@ -1305,10 +1090,8 @@ describe('FieldList', () => {
allVariableNames={[]}
/>,
)
- // Trigger sort to cause fields change
fireEvent.click(screen.getByTestId('trigger-sort'))
- // Assert
expect(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 () => {
- // Arrange
mockIsVarUsedInNodes.mockReturnValue(true)
mockIsHovering = true
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="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 button
if (fieldItemButtons.length >= 2)
fireEvent.click(fieldItemButtons[1])
- // Assert
await waitFor(() => {
expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()
})
})
it('should hide remove confirmation when cancel is clicked', async () => {
- // Arrange
mockIsVarUsedInNodes.mockReturnValue(true)
mockIsHovering = true
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1367,7 +1140,6 @@ describe('FieldList', () => {
/>,
)
- // Trigger remove - find delete button in sortable container
const 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 cancel
fireEvent.click(screen.getByTestId('confirm-cancel'))
- // Assert
await waitFor(() => {
expect(screen.queryByTestId('remove-var-confirm')).not.toBeInTheDocument()
})
})
it('should remove field and call removeUsedVarInNodes when confirm is clicked', async () => {
- // Arrange
mockIsVarUsedInNodes.mockReturnValue(true)
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1404,7 +1172,6 @@ describe('FieldList', () => {
/>,
)
- // Trigger remove - find delete button in sortable container
const 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 confirm
fireEvent.click(screen.getByTestId('confirm-ok'))
- // Assert
await 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', () => {
- // Arrange
mockIsVarUsedInNodes.mockReturnValue(false)
mockIsHovering = true
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1442,24 +1205,18 @@ describe('FieldList', () => {
/>,
)
- // Find delete button in sortable container
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 2)
fireEvent.click(fieldItemButtons[1])
- // Assert - should not show confirmation
expect(screen.queryByTestId('remove-var-confirm')).not.toBeInTheDocument()
expect(handleInputFieldsChange).toHaveBeenCalled()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle empty inputFields', () => {
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1470,12 +1227,10 @@ describe('FieldList', () => {
/>,
)
- // Assert
expect(screen.getByTestId('sortable-container')).toBeInTheDocument()
})
it('should handle null LabelRightContent', () => {
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1486,12 +1241,10 @@ describe('FieldList', () => {
/>,
)
- // Assert - should render without errors
expect(screen.getByText('var_0')).toBeInTheDocument()
})
it('should handle complex LabelRightContent', () => {
- // Arrange
const complexContent = (
<div data-testid="complex-content">
<span>Part 1</span>
@@ -1499,7 +1252,6 @@ describe('FieldList', () => {
</div>
)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1510,22 +1262,16 @@ describe('FieldList', () => {
/>,
)
- // Assert
expect(screen.getByTestId('complex-content')).toBeInTheDocument()
expect(screen.getByText('Part 1')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should be wrapped with React.memo', () => {
- // Arrange
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
const { rerender } = render(
<FieldList
nodeId="node-1"
@@ -1546,16 +1292,13 @@ describe('FieldList', () => {
/>,
)
- // Assert
expect(screen.getByText('var_0')).toBeInTheDocument()
})
it('should maintain stable onInputFieldsChange callback', () => {
- // Arrange
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
const { rerender } = render(
<FieldList
nodeId="node-1"
@@ -1580,31 +1323,21 @@ describe('FieldList', () => {
fireEvent.click(screen.getByTestId('trigger-sort'))
- // Assert
expect(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', () => {
- // Arrange
const inputFields = createInputVarList(2)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1615,13 +1348,11 @@ describe('useFieldList Hook', () => {
/>,
)
- // Assert
expect(screen.getByText('var_0')).toBeInTheDocument()
expect(screen.getByText('var_1')).toBeInTheDocument()
})
it('should initialize with empty inputFields', () => {
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1632,21 +1363,15 @@ describe('useFieldList Hook', () => {
/>,
)
- // Assert
expect(screen.getByTestId('sortable-container')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // handleListSortChange Tests
- // -------------------------------------------------------------------------
describe('handleListSortChange', () => {
it('should update inputFields and call onInputFieldsChange', () => {
- // Arrange
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1658,7 +1383,6 @@ describe('useFieldList Hook', () => {
)
fireEvent.click(screen.getByTestId('trigger-sort'))
- // Assert
expect(handleInputFieldsChange).toHaveBeenCalledWith(
'node-1',
expect.arrayContaining([
@@ -1669,11 +1393,9 @@ describe('useFieldList Hook', () => {
})
it('should strip sortable properties from list items', () => {
- // Arrange
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1685,7 +1407,6 @@ describe('useFieldList Hook', () => {
)
fireEvent.click(screen.getByTestId('trigger-sort'))
- // Assert
const 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 () => {
- // Arrange
mockIsVarUsedInNodes.mockReturnValue(true)
mockIsHovering = true
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1714,26 +1430,22 @@ describe('useFieldList Hook', () => {
/>,
)
- // Find delete button in sortable container
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 2)
fireEvent.click(fieldItemButtons[1])
- // Assert
await waitFor(() => {
expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()
})
})
it('should remove directly when variable is not used', () => {
- // Arrange
mockIsVarUsedInNodes.mockReturnValue(false)
mockIsHovering = true
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1744,25 +1456,21 @@ describe('useFieldList Hook', () => {
/>,
)
- // Find delete button in sortable container
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 2)
fireEvent.click(fieldItemButtons[1])
- // Assert
expect(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 directly
mockIsVarUsedInNodes.mockReturnValue(true)
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1773,13 +1481,11 @@ describe('useFieldList Hook', () => {
/>,
)
- // Find delete button and click it
const 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 () => {
- // Arrange
mockIsVarUsedInNodes.mockReturnValue(true)
mockIsHovering = true
const inputFields = [createInputVar({ variable: 'my_test_var' })]
- // Act
render(
<FieldList
nodeId="test-node-123"
@@ -1808,18 +1512,15 @@ describe('useFieldList Hook', () => {
if (fieldItemButtons.length >= 2)
fireEvent.click(fieldItemButtons[1])
- // Assert
expect(mockIsVarUsedInNodes).toHaveBeenCalledWith(['rag', 'test-node-123', 'my_test_var'])
})
it('should handle empty variable name gracefully', async () => {
- // Arrange - Tests line 70 with empty variable
mockIsVarUsedInNodes.mockReturnValue(false)
mockIsHovering = true
const inputFields = [createInputVar({ variable: '' })]
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1835,18 +1536,15 @@ describe('useFieldList Hook', () => {
if (fieldItemButtons.length >= 2)
fireEvent.click(fieldItemButtons[1])
- // Assert - should still work with empty variable
expect(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-73
mockIsVarUsedInNodes.mockReturnValue(true)
mockIsHovering = true
const inputFields = createInputVarList(3)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="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 item
if (allFieldItemButtons.length >= 4)
fireEvent.click(allFieldItemButtons[3])
- // Show confirmation
await waitFor(() => {
expect(screen.getByTestId('remove-var-confirm')).toBeInTheDocument()
})
- // Click confirm
fireEvent.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', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1906,7 +1594,6 @@ describe('useFieldList Hook', () => {
if (addButton)
fireEvent.click(addButton)
- // Assert
expect(mockToggleInputFieldEditPanel).toHaveBeenCalledWith(
expect.objectContaining({
onClose: expect.any(Function),
@@ -1916,11 +1603,9 @@ describe('useFieldList Hook', () => {
})
it('should pass initialData when editing existing field', () => {
- // Arrange
mockIsHovering = true
const inputFields = [createInputVar({ variable: 'my_var', label: 'My Label' })]
- // Act
render(
<FieldList
nodeId="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])
- // Assert
expect(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 () => {
- // Arrange
mockIsVarUsedInNodes.mockReturnValue(true)
mockIsHovering = true
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -1970,7 +1648,6 @@ describe('useFieldList Hook', () => {
/>,
)
- // Find delete button in sortable container
const 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'))
- // Assert
await 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', () => {
- // Arrange
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2018,19 +1688,15 @@ describe('handleSubmitField', () => {
/>,
)
- // Click add button to open editor
fireEvent.click(screen.getByTestId('field-list-add-btn'))
- // Get the onSubmit callback that was passed to toggleInputFieldEditPanel
expect(mockToggleInputFieldEditPanel).toHaveBeenCalled()
const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]
expect(editorProps).toHaveProperty('onSubmit')
- // Simulate form submission with new field data
const newFieldData = createInputVar({ variable: 'new_var', label: 'New Label' })
editorProps.onSubmit(newFieldData)
- // Assert
expect(handleInputFieldsChange).toHaveBeenCalledWith(
'node-1',
expect.arrayContaining([
@@ -2041,12 +1707,10 @@ describe('handleSubmitField', () => {
})
it('should update existing field when editingFieldIndex is valid', () => {
- // Arrange
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2057,20 +1721,16 @@ describe('handleSubmitField', () => {
/>,
)
- // Click edit button on existing field
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 1)
fireEvent.click(fieldItemButtons[0])
- // Get the onSubmit callback
const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]
- // Simulate form submission with updated data
const updatedFieldData = createInputVar({ variable: 'var_0', label: 'Updated Label' })
editorProps.onSubmit(updatedFieldData)
- // Assert - field should be updated, not added
expect(handleInputFieldsChange).toHaveBeenCalledWith(
'node-1',
expect.arrayContaining([
@@ -2082,12 +1742,10 @@ describe('handleSubmitField', () => {
})
it('should call handleInputVarRename when variable name changes', () => {
- // Arrange
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2098,23 +1756,19 @@ describe('handleSubmitField', () => {
/>,
)
- // Click edit button
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 1)
fireEvent.click(fieldItemButtons[0])
- // Get the onSubmit callback
const 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' },
})
- // Assert
expect(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.ts
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2139,31 +1791,25 @@ describe('handleSubmitField', () => {
/>,
)
- // Click edit button
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 1)
fireEvent.click(fieldItemButtons[0])
- // Get the onSubmit callback
const 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 called
expect(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 type
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2174,31 +1820,25 @@ describe('handleSubmitField', () => {
/>,
)
- // Click edit button
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 1)
fireEvent.click(fieldItemButtons[0])
- // Get the onSubmit callback
const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]
- // Simulate form submission with moreInfo but different type
const 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 called
expect(mockHandleInputVarRename).not.toHaveBeenCalled()
expect(handleInputFieldsChange).toHaveBeenCalled()
})
it('should handle empty beforeKey and afterKey in moreInfo payload', () => {
- // Arrange - This tests line 108 with empty keys
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2209,23 +1849,19 @@ describe('handleSubmitField', () => {
/>,
)
- // Click edit button
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 1)
fireEvent.click(fieldItemButtons[0])
- // Get the onSubmit callback
const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]
- // Simulate form submission with changeVarName but empty keys
const updatedFieldData = createInputVar({ variable: 'new_var' })
editorProps.onSubmit(updatedFieldData, {
type: 'changeVarName',
payload: { beforeKey: '', afterKey: '' },
})
- // Assert - handleInputVarRename should be called with empty strings
expect(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 payload
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2250,23 +1884,19 @@ describe('handleSubmitField', () => {
/>,
)
- // Click edit button
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 1)
fireEvent.click(fieldItemButtons[0])
- // Get the onSubmit callback
const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]
- // Simulate form submission with changeVarName but undefined payload
const 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', () => {
- // Arrange
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2290,26 +1918,20 @@ describe('handleSubmitField', () => {
/>,
)
- // Click add button
fireEvent.click(screen.getByTestId('field-list-add-btn'))
- // Get the onSubmit callback
const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]
- // Simulate form submission
const newFieldData = createInputVar({ variable: 'new_var' })
editorProps.onSubmit(newFieldData)
- // Assert - toggleInputFieldEditPanel should be called with null to close
expect(mockToggleInputFieldEditPanel).toHaveBeenCalledTimes(2)
expect(mockToggleInputFieldEditPanel).toHaveBeenLastCalledWith(null)
})
it('should call onClose when editor is closed manually', () => {
- // Arrange
const inputFields = createInputVarList(1)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2320,25 +1942,17 @@ describe('handleSubmitField', () => {
/>,
)
- // Click add button
fireEvent.click(screen.getByTestId('field-list-add-btn'))
- // Get the onClose callback
const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]
expect(editorProps).toHaveProperty('onClose')
- // Simulate close
editorProps.onClose()
- // Assert - toggleInputFieldEditPanel should be called with null
expect(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 () => {
- // Arrange
const Toast = await import('@/app/components/base/toast')
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2363,31 +1975,24 @@ describe('Duplicate Variable Name Handling', () => {
/>,
)
- // Click add button
fireEvent.click(screen.getByTestId('field-list-add-btn'))
- // Get the onSubmit callback
const editorProps = mockToggleInputFieldEditPanel.mock.calls[0][0]
- // Try to submit with a duplicate variable name
const duplicateFieldData = createInputVar({ variable: 'existing_var' })
editorProps.onSubmit(duplicateFieldData)
- // Assert - handleInputFieldsChange should NOT be called
expect(handleInputFieldsChange).not.toHaveBeenCalled()
- // Toast should be shown
expect(Toast.default.notify).toHaveBeenCalledWith(
expect.objectContaining({ type: 'error' }),
)
})
it('should allow updating field to same variable name', () => {
- // Arrange
mockIsHovering = true
const inputFields = createInputVarList(2)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2398,35 +2003,25 @@ describe('Duplicate Variable Name Handling', () => {
/>,
)
- // Click edit button on first field
const sortableContainer = screen.getByTestId('sortable-container')
const fieldItemButtons = sortableContainer.querySelectorAll('button.action-btn')
if (fieldItemButtons.length >= 1)
fireEvent.click(fieldItemButtons[0])
- // Get the onSubmit callback
const 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 name
expect(handleInputFieldsChange).toHaveBeenCalled()
})
})
-// ============================================================================
-// SortableItem Type Tests
-// ============================================================================
-
describe('SortableItem Type', () => {
it('should have correct structure', () => {
- // Arrange
const inputVar = createInputVar()
const sortableItem = createSortableItem(inputVar)
- // Assert
expect(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', () => {
- // Arrange
const inputVar = createInputVar()
const sortableItem = createSortableItem(inputVar, {
chosen: true,
selected: true,
})
- // Assert
expect(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 () => {
- // Arrange
mockIsHovering = true
const inputFields = createInputVarList(1)
const handleInputFieldsChange = vi.fn()
- // Act - Render
render(
<FieldList
nodeId="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 field
const 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 field
if (fieldItemButtons.length >= 2)
fireEvent.click(fieldItemButtons[1])
@@ -2498,11 +2082,9 @@ describe('Integration Tests', () => {
})
it('should handle sort operation correctly', () => {
- // Arrange
const inputFields = createInputVarList(3)
const handleInputFieldsChange = vi.fn()
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2515,13 +2097,11 @@ describe('Integration Tests', () => {
fireEvent.click(screen.getByTestId('trigger-sort'))
- // Assert
expect(handleInputFieldsChange).toHaveBeenCalledWith(
'node-1',
expect.any(Array),
)
const newOrder = handleInputFieldsChange.mock.calls[0][1]
- // First two should be swapped
expect(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', () => {
- // Arrange
const inputFields = createInputVarList(2)
- // Act
render(
<FieldList
nodeId="node-1"
@@ -2544,7 +2122,6 @@ describe('Integration Tests', () => {
/>,
)
- // Assert
const 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.tsx
similarity index 90%
rename from web/app/components/rag-pipeline/components/panel/input-field/label-right-content/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/input-field/label-right-content/__tests__/index.spec.tsx
index 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-so
import { 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 BlockIcon
vi.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 useToolIcon
vi.mock('@/app/components/workflow/hooks', () => ({
useToolIcon: (nodeData: DataSourceNodeType) => nodeData.provider_name || 'default-icon',
}))
-// Mock Tooltip
vi.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 text
expect(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.tsx
similarity index 75%
rename from web/app/components/rag-pipeline/components/panel/input-field/preview/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/index.spec.tsx
index 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 hook
const mockUseFloatingRight = vi.fn(() => ({
floatingRight: false,
floatingRightWidth: 480,
}))
-vi.mock('../hooks', () => ({
+vi.mock('../../hooks', () => ({
useFloatingRight: () => mockUseFloatingRight(),
}))
-// Mock useInputFieldPanel hook
const 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 store
let mockPipelineId: string | null = 'test-pipeline-id'
vi.mock('@/app/components/workflow/store', () => ({
@@ -56,17 +49,14 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-// Mock reactflow store
vi.mock('reactflow', () => ({
useStore: () => undefined,
}))
-// Mock zustand shallow
vi.mock('zustand/react/shallow', () => ({
useShallow: (fn: unknown) => fn,
}))
-// Track mock data for API hooks
let mockPreProcessingParamsData: { variables: RAGPipelineVariables } | undefined
let mockProcessingParamsData: { variables: RAGPipelineVariables } | undefined
@@ -83,10 +73,9 @@ vi.mock('@/service/use-pipeline', () => ({
}),
}))
-// Track mock datasource options
let 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 object
const mapOptionToObject = (option: string) => ({
label: option,
value: option,
})
-// Mock form-related hooks
vi.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 hook
vi.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 component
vi.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', () => {
- // Act
renderWithProviders(<PreviewPanel />)
- // Assert
expect(
screen.getByText('datasetPipeline.operations.preview'),
).toBeInTheDocument()
})
it('should render preview badge', () => {
- // Act
renderWithProviders(<PreviewPanel />)
- // Assert
const badge = screen.getByText('datasetPipeline.operations.preview')
expect(badge).toBeInTheDocument()
})
it('should render close button', () => {
- // Act
renderWithProviders(<PreviewPanel />)
- // Assert
const closeButton = screen.getByRole('button')
expect(closeButton).toBeInTheDocument()
})
it('should render DataSource component', () => {
- // Act
renderWithProviders(<PreviewPanel />)
- // Assert
expect(screen.getByTestId('data-source-options')).toBeInTheDocument()
})
it('should render ProcessDocuments component', () => {
- // Act
renderWithProviders(<PreviewPanel />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),
).toBeInTheDocument()
})
it('should render divider between sections', () => {
- // Act
const { container } = renderWithProviders(<PreviewPanel />)
- // Assert
const divider = container.querySelector('.bg-divider-subtle')
expect(divider).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // State Management Tests
- // -------------------------------------------------------------------------
describe('State Management', () => {
it('should initialize with empty datasource state', () => {
- // Act
renderWithProviders(<PreviewPanel />)
- // Assert
expect(screen.getByTestId('current-node-id').textContent).toBe('')
})
it('should update datasource state when DataSource selects', () => {
- // Arrange
mockDatasourceOptions = [
createDatasourceOption({ value: 'node-1', label: 'Node 1' }),
]
- // Act
renderWithProviders(<PreviewPanel />)
fireEvent.click(screen.getByTestId('option-node-1'))
- // Assert
expect(screen.getByTestId('current-node-id').textContent).toBe('node-1')
})
it('should pass datasource nodeId to ProcessDocuments', () => {
- // Arrange
mockDatasourceOptions = [
createDatasourceOption({ value: 'test-node', label: 'Test Node' }),
]
- // Act
renderWithProviders(<PreviewPanel />)
fireEvent.click(screen.getByTestId('option-test-node'))
- // Assert - ProcessDocuments receives the nodeId
expect(screen.getByTestId('current-node-id').textContent).toBe('test-node')
})
})
- // -------------------------------------------------------------------------
- // User Interaction Tests
- // -------------------------------------------------------------------------
describe('User Interactions', () => {
it('should call toggleInputFieldPreviewPanel when close button clicked', () => {
- // Act
renderWithProviders(<PreviewPanel />)
const closeButton = screen.getByRole('button')
fireEvent.click(closeButton)
- // Assert
expect(mockToggleInputFieldPreviewPanel).toHaveBeenCalledTimes(1)
})
it('should handle multiple close button clicks', () => {
- // Act
renderWithProviders(<PreviewPanel />)
const closeButton = screen.getByRole('button')
fireEvent.click(closeButton)
fireEvent.click(closeButton)
fireEvent.click(closeButton)
- // Assert
expect(mockToggleInputFieldPreviewPanel).toHaveBeenCalledTimes(3)
})
it('should handle datasource selection changes', () => {
- // Arrange
mockDatasourceOptions = [
createDatasourceOption({ value: 'node-1', label: 'Node 1' }),
createDatasourceOption({ value: 'node-2', label: 'Node 2' }),
]
- // Act
renderWithProviders(<PreviewPanel />)
fireEvent.click(screen.getByTestId('option-node-1'))
- // Assert
expect(screen.getByTestId('current-node-id').textContent).toBe('node-1')
- // Act - Change selection
fireEvent.click(screen.getByTestId('option-node-2'))
- // Assert
expect(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', () => {
- // Arrange
mockUseFloatingRight.mockReturnValue({
floatingRight: true,
floatingRightWidth: 400,
})
- // Act
const { container } = renderWithProviders(<PreviewPanel />)
- // Assert
const panel = container.firstChild as HTMLElement
expect(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', () => {
- // Arrange
mockUseFloatingRight.mockReturnValue({
floatingRight: false,
floatingRightWidth: 480,
})
- // Act
const { container } = renderWithProviders(<PreviewPanel />)
- // Assert
const panel = container.firstChild as HTMLElement
expect(panel.className).not.toContain('absolute')
expect(panel.style.width).toBe('480px')
})
it('should update width when floatingRightWidth changes', () => {
- // Arrange
mockUseFloatingRight.mockReturnValue({
floatingRight: false,
floatingRightWidth: 600,
})
- // Act
const { container } = renderWithProviders(<PreviewPanel />)
- // Assert
const panel = container.firstChild as HTMLElement
expect(panel.style.width).toBe('600px')
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should maintain stable handleClosePreviewPanel callback', () => {
- // Act
const { rerender } = renderWithProviders(<PreviewPanel />)
fireEvent.click(screen.getByRole('button'))
@@ -469,51 +388,37 @@ describe('PreviewPanel', () => {
)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(mockToggleInputFieldPreviewPanel).toHaveBeenCalledTimes(2)
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle empty datasource options', () => {
- // Arrange
mockDatasourceOptions = []
- // Act
renderWithProviders(<PreviewPanel />)
- // Assert
expect(screen.getByTestId('data-source-options')).toBeInTheDocument()
expect(screen.getByTestId('current-node-id').textContent).toBe('')
})
it('should handle rapid datasource selections', () => {
- // Arrange
mockDatasourceOptions = [
createDatasourceOption({ value: 'node-1', label: 'Node 1' }),
createDatasourceOption({ value: 'node-2', label: 'Node 2' }),
createDatasourceOption({ value: 'node-3', label: 'Node 3' }),
]
- // Act
renderWithProviders(<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-3
expect(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', () => {
- // Arrange
const onSelect = vi.fn()
- // Act
renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="" />,
)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepOneTitle'),
).toBeInTheDocument()
})
it('should render DataSourceOptions component', () => {
- // Arrange
const onSelect = vi.fn()
- // Act
renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="" />,
)
- // Assert
expect(screen.getByTestId('data-source-options')).toBeInTheDocument()
})
it('should pass dataSourceNodeId to DataSourceOptions', () => {
- // Arrange
const onSelect = vi.fn()
- // Act
renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="test-node-id" />,
)
- // Assert
expect(screen.getByTestId('current-node-id').textContent).toBe(
'test-node-id',
)
})
})
- // -------------------------------------------------------------------------
- // Props Variations Tests
- // -------------------------------------------------------------------------
describe('Props Variations', () => {
it('should handle empty dataSourceNodeId', () => {
- // Arrange
const onSelect = vi.fn()
- // Act
renderWithProviders(<DataSource onSelect={onSelect} dataSourceNodeId="" />)
- // Assert
expect(screen.getByTestId('current-node-id').textContent).toBe('')
})
it('should handle different dataSourceNodeId values', () => {
- // Arrange
const onSelect = vi.fn()
- // Act
const { rerender } = renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="node-1" />,
)
- // Assert
expect(screen.getByTestId('current-node-id').textContent).toBe('node-1')
- // Act - Change nodeId
rerender(
<TestWrapper>
<DataSource onSelect={onSelect} dataSourceNodeId="node-2" />
</TestWrapper>,
)
- // Assert
expect(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 () => {
- // Arrange
const onSelect = vi.fn()
mockPreProcessingParamsData = {
variables: [createRAGPipelineVariable()],
}
- // Act
renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="test-node" />,
)
- // Assert - Form should render with fetched variables
await waitFor(() => {
expect(screen.getByTestId('field-test_variable')).toBeInTheDocument()
})
})
it('should not render form fields when params data is empty', () => {
- // Arrange
const onSelect = vi.fn()
mockPreProcessingParamsData = { variables: [] }
- // Act
renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="test-node" />,
)
- // Assert
expect(screen.queryByTestId('field-test_variable')).not.toBeInTheDocument()
})
it('should handle undefined params data', () => {
- // Arrange
const onSelect = vi.fn()
mockPreProcessingParamsData = undefined
- // Act
renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="" />,
)
- // Assert - Should render without errors
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepOneTitle'),
).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // User Interaction Tests
- // -------------------------------------------------------------------------
describe('User Interactions', () => {
it('should call onSelect when datasource option is clicked', () => {
- // Arrange
const onSelect = vi.fn()
mockDatasourceOptions = [
createDatasourceOption({ value: 'selected-node', label: 'Selected' }),
]
- // Act
renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="" />,
)
fireEvent.click(screen.getByTestId('option-selected-node'))
- // Assert
expect(onSelect).toHaveBeenCalledTimes(1)
expect(onSelect).toHaveBeenCalledWith(
expect.objectContaining({
@@ -689,58 +553,43 @@ describe('DataSource', () => {
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should be memoized (React.memo)', () => {
- // Arrange
const onSelect = vi.fn()
- // Act
const { rerender } = renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="node-1" />,
)
- // Rerender with same props
rerender(
<TestWrapper>
<DataSource onSelect={onSelect} dataSourceNodeId="node-1" />
</TestWrapper>,
)
- // Assert - Component should not cause additional renders
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepOneTitle'),
).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle null pipelineId', () => {
- // Arrange
const onSelect = vi.fn()
mockPipelineId = null
- // Act
renderWithProviders(
<DataSource onSelect={onSelect} dataSourceNodeId="test-node" />,
)
- // Assert - Should render without errors
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepOneTitle'),
).toBeInTheDocument()
})
it('should handle special characters in dataSourceNodeId', () => {
- // Arrange
const onSelect = vi.fn()
- // Act
renderWithProviders(
<DataSource
onSelect={onSelect}
@@ -748,7 +597,6 @@ describe('DataSource', () => {
/>,
)
- // Assert
expect(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', () => {
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId="" />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),
).toBeInTheDocument()
})
it('should render Form component', () => {
- // Arrange
mockProcessingParamsData = {
variables: [createRAGPipelineVariable({ variable: 'process_var' })],
}
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)
- // Assert - Form should be rendered
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),
).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Props Variations Tests
- // -------------------------------------------------------------------------
describe('Props Variations', () => {
it('should handle empty dataSourceNodeId', () => {
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId="" />)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),
).toBeInTheDocument()
})
it('should handle different dataSourceNodeId values', () => {
- // Act
const { rerender } = renderWithProviders(
<ProcessDocuments dataSourceNodeId="node-1" />,
)
- // Assert
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),
).toBeInTheDocument()
- // Act - Change nodeId
rerender(
<TestWrapper>
<ProcessDocuments dataSourceNodeId="node-2" />
</TestWrapper>,
)
- // Assert
expect(
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 () => {
- // Arrange
mockProcessingParamsData = {
variables: [
createRAGPipelineVariable({
@@ -851,41 +674,32 @@ describe('ProcessDocuments', () => {
],
}
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('field-chunk_size')).toBeInTheDocument()
})
})
it('should not render form fields when params data is empty', () => {
- // Arrange
mockProcessingParamsData = { variables: [] }
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)
- // Assert
expect(screen.queryByTestId('field-chunk_size')).not.toBeInTheDocument()
})
it('should handle undefined params data', () => {
- // Arrange
mockProcessingParamsData = undefined
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId="" />)
- // Assert - Should render without errors
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),
).toBeInTheDocument()
})
it('should render multiple form fields from params', async () => {
- // Arrange
mockProcessingParamsData = {
variables: [
createRAGPipelineVariable({
@@ -899,10 +713,8 @@ describe('ProcessDocuments', () => {
],
}
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)
- // Assert
await 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)', () => {
- // Act
const { rerender } = renderWithProviders(
<ProcessDocuments dataSourceNodeId="node-1" />,
)
- // Rerender with same props
rerender(
<TestWrapper>
<ProcessDocuments dataSourceNodeId="node-1" />
</TestWrapper>,
)
- // Assert - Component should render without issues
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),
).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle null pipelineId', () => {
- // Arrange
mockPipelineId = null
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId="test-node" />)
- // Assert - Should render without errors
expect(
screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),
).toBeInTheDocument()
})
it('should handle very long dataSourceNodeId', () => {
- // Arrange
const longNodeId = 'a'.repeat(100)
- // Act
renderWithProviders(<ProcessDocuments dataSourceNodeId={longNodeId} />)
- // Assert
expect(
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', () => {
- // Act
const { container } = renderWithProviders(<Form variables={[]} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should render form fields for each variable', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({ variable: 'field1', label: 'Field 1' }),
createRAGPipelineVariable({ variable: 'field2', label: 'Field 2' }),
]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('field-field1')).toBeInTheDocument()
expect(screen.getByTestId('field-field2')).toBeInTheDocument()
})
it('should render no fields when variables is empty', () => {
- // Act
renderWithProviders(<Form variables={[]} />)
- // Assert
expect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Props Variations Tests
- // -------------------------------------------------------------------------
describe('Props Variations', () => {
it('should handle different variable types', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({
variable: 'text_var',
@@ -1033,17 +812,14 @@ describe('Form', () => {
}),
]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(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', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({
variable: 'with_default',
@@ -1051,15 +827,12 @@ describe('Form', () => {
}),
]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('field-with_default')).toBeInTheDocument()
})
it('should handle variables with all optional fields', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({
variable: 'full_var',
@@ -1073,59 +846,42 @@ describe('Form', () => {
}),
]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('field-full_var')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Form Behavior Tests
- // -------------------------------------------------------------------------
describe('Form Behavior', () => {
it('should prevent default form submission', () => {
- // Arrange
const variables = [createRAGPipelineVariable()]
const preventDefaultMock = vi.fn()
- // Act
const { container } = renderWithProviders(<Form variables={variables} />)
const form = container.querySelector('form')!
- // Create and dispatch submit event
const submitEvent = new Event('submit', { bubbles: true, cancelable: true })
Object.defineProperty(submitEvent, 'preventDefault', {
value: preventDefaultMock,
})
form.dispatchEvent(submitEvent)
- // Assert - Form should prevent default submission
expect(preventDefaultMock).toHaveBeenCalled()
})
it('should pass form to each field component', () => {
- // Arrange
const variables = [createRAGPipelineVariable({ variable: 'test_var' })]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('form-ref').textContent).toBe('has-form')
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should memoize initialData when variables do not change', () => {
- // Arrange
const variables = [createRAGPipelineVariable()]
- // Act
const { rerender } = renderWithProviders(<Form variables={variables} />)
rerender(
<TestWrapper>
@@ -1133,72 +889,55 @@ describe('Form', () => {
</TestWrapper>,
)
- // Assert - Component should render without issues
expect(screen.getByTestId('field-test_variable')).toBeInTheDocument()
})
it('should memoize configurations when variables do not change', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({ variable: 'var1' }),
createRAGPipelineVariable({ variable: 'var2' }),
]
- // Act
const { rerender } = renderWithProviders(<Form variables={variables} />)
- // Rerender with same variables reference
rerender(
<TestWrapper>
<Form variables={variables} />
</TestWrapper>,
)
- // Assert
expect(screen.getByTestId('field-var1')).toBeInTheDocument()
expect(screen.getByTestId('field-var2')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle empty variables array', () => {
- // Act
const { container } = renderWithProviders(<Form variables={[]} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
expect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()
})
it('should handle single variable', () => {
- // Arrange
const variables = [createRAGPipelineVariable({ variable: 'single' })]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('field-single')).toBeInTheDocument()
})
it('should handle many variables', () => {
- // Arrange
const variables = Array.from({ length: 20 }, (_, i) =>
createRAGPipelineVariable({ variable: `var_${i}`, label: `Var ${i}` }))
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('field-var_0')).toBeInTheDocument()
expect(screen.getByTestId('field-var_19')).toBeInTheDocument()
})
it('should handle variables with special characters in names', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({
variable: 'var_with_underscore',
@@ -1206,15 +945,12 @@ describe('Form', () => {
}),
]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('field-var_with_underscore')).toBeInTheDocument()
})
it('should handle variables with unicode labels', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({
variable: 'unicode_var',
@@ -1223,16 +959,13 @@ describe('Form', () => {
}),
]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('field-unicode_var')).toBeInTheDocument()
expect(screen.getByText('中文标签 🎉')).toBeInTheDocument()
})
it('should handle variables with empty string default values', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({
variable: 'empty_default',
@@ -1240,15 +973,12 @@ describe('Form', () => {
}),
]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(screen.getByTestId('field-empty_default')).toBeInTheDocument()
})
it('should handle variables with zero max_length', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({
variable: 'zero_length',
@@ -1256,19 +986,13 @@ describe('Form', () => {
}),
]
- // Act
renderWithProviders(<Form variables={variables} />)
- // Assert
expect(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 () => {
- // Arrange
mockDatasourceOptions = [
createDatasourceOption({ value: 'node-1', label: 'Local File' }),
]
@@ -1308,13 +1028,10 @@ describe('Preview Panel Integration', () => {
],
}
- // Act
renderWithProviders(<PreviewPanel />)
- // Select datasource
fireEvent.click(screen.getByTestId('option-node-1'))
- // Assert - Both forms should show their fields
await 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 () => {
- // Arrange
mockDatasourceOptions = [
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' })],
}
- // Act
renderWithProviders(<PreviewPanel />)
- // Select first datasource
fireEvent.click(screen.getByTestId('option-node-1'))
- // Assert initial selection
await waitFor(() => {
expect(screen.getByTestId('current-node-id').textContent).toBe('node-1')
})
- // Select second datasource
fireEvent.click(screen.getByTestId('option-node-2'))
- // Assert updated selection
await 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', () => {
- // Arrange
mockDatasourceOptions = [
createDatasourceOption({ value: 'communicated-node', label: 'Node' }),
]
- // Act
renderWithProviders(<PreviewPanel />)
fireEvent.click(screen.getByTestId('option-communicated-node'))
- // Assert
expect(screen.getByTestId('current-node-id').textContent).toBe(
'communicated-node',
)
})
})
- // -------------------------------------------------------------------------
- // State Persistence Tests
- // -------------------------------------------------------------------------
describe('State Persistence', () => {
it('should maintain datasource selection within same render cycle', () => {
- // Arrange
mockDatasourceOptions = [
createDatasourceOption({ value: 'persistent-node', label: 'Persistent' }),
createDatasourceOption({ value: 'other-node', label: 'Other' }),
]
- // Act
renderWithProviders(<PreviewPanel />)
fireEvent.click(screen.getByTestId('option-persistent-node'))
- // Assert - Selection should be maintained
expect(screen.getByTestId('current-node-id').textContent).toBe(
'persistent-node',
)
- // Change selection and verify state updates correctly
fireEvent.click(screen.getByTestId('option-other-node'))
expect(screen.getByTestId('current-node-id').textContent).toBe(
'other-node',
)
- // Go back to original and verify
fireEvent.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.tsx
similarity index 85%
rename from web/app/components/rag-pipeline/components/panel/test-run/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/test-run/__tests__/index.spec.tsx
index 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 store
const 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 interactions
const 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 provider
vi.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 workflow
vi.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 workflow
vi.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 component
vi.mock('@/app/components/base/loading', () => ({
default: () => <div data-testid="loading">Loading...</div>,
}))
-// Mock config
vi.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 tests
describe('Rendering', () => {
it('should render with correct container styles', () => {
const { container } = render(<TestRunPanel />)
@@ -168,7 +145,6 @@ describe('TestRunPanel', () => {
})
})
- // Conditional rendering based on isPreparingDataSource
describe('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 tests
describe('Rendering', () => {
it('should render title with correct translation key', () => {
render(<Header />)
@@ -225,7 +196,6 @@ describe('Header', () => {
})
})
- // Close button interactions
describe('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').default
beforeAll(async () => {
- const resultModule = await import('./result')
+ const resultModule = await import('../result')
Result = resultModule.default
})
@@ -274,7 +238,6 @@ describe('Result', () => {
mockWorkflowRunningData.mockReturnValue(undefined)
})
- // Rendering tests
describe('Rendering', () => {
it('should render with RESULT tab active by default', async () => {
render(<Result />)
@@ -294,7 +257,6 @@ describe('Result', () => {
})
})
- // Tab switching tests
describe('Tab Switching', () => {
it('should switch to DETAIL tab when clicked', async () => {
mockWorkflowRunningData.mockReturnValue(createMockWorkflowRunningData())
@@ -321,7 +283,6 @@ describe('Result', () => {
})
})
- // Loading states
describe('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').default
beforeAll(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 state
describe('Loading State', () => {
it('should show loading spinner when isRunning is true and no outputs', () => {
render(
@@ -402,7 +357,6 @@ describe('ResultPreview', () => {
})
})
- // Error state
describe('Error State', () => {
it('should show error message when not running and has error', () => {
render(
@@ -448,7 +402,6 @@ describe('ResultPreview', () => {
})
})
- // Success state with outputs
describe('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 cases
describe('Edge Cases', () => {
it('should handle empty outputs gracefully', () => {
render(
@@ -504,7 +455,6 @@ describe('ResultPreview', () => {
/>,
)
- // Should not crash and should not show chunk card list
expect(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').default
beforeAll(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 tests
describe('Rendering', () => {
it('should render all three tabs', () => {
render(
@@ -560,7 +505,6 @@ describe('Tabs', () => {
})
})
- // Active tab styling
describe('Active Tab Styling', () => {
it('should highlight RESULT tab when currentTab is RESULT', () => {
render(
@@ -589,7 +533,6 @@ describe('Tabs', () => {
})
})
- // Tab click handling
describe('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 data
describe('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').default
beforeAll(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 tests
describe('Rendering', () => {
it('should render tab with label', () => {
render(
@@ -688,7 +625,6 @@ describe('Tab', () => {
})
})
- // Active state styling
describe('Active State', () => {
it('should have active styles when isActive is true', () => {
render(
@@ -721,7 +657,6 @@ describe('Tab', () => {
})
})
- // Click handling
describe('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 disabled
expect(tab).toBeDisabled()
})
})
- // Disabled state
describe('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').formatPreviewChunks
beforeAll(async () => {
- const utilsModule = await import('./result/result-preview/utils')
+ const utilsModule = await import('../result/result-preview/utils')
formatPreviewChunks = utilsModule.formatPreviewChunks
})
- // Edge cases
describe('Edge Cases', () => {
it('should return undefined for null outputs', () => {
expect(formatPreviewChunks(null)).toBeUndefined()
@@ -824,7 +752,6 @@ describe('formatPreviewChunks', () => {
})
})
- // General (text) chunks
describe('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 5
expect(result).toHaveLength(5)
expect(result).toEqual([
{ content: 'chunk0', summary: undefined },
@@ -861,7 +787,6 @@ describe('formatPreviewChunks', () => {
})
})
- // Parent-child chunks
describe('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 chunks
describe('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.ts
new file mode 100644
index 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.tsx
similarity index 76%
rename from web/app/components/rag-pipeline/components/panel/test-run/preparation/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/test-run/preparation/__tests__/index.spec.tsx
index 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.mock
let mockNodes: Array<{ id: string, data: DataSourceNodeType }> = []
-// Test Data Factory - must be declared before vi.mock that uses it
const 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 reactflow
vi.mock('reactflow', () => ({
useNodes: () => mockNodes,
}))
-// Mock zustand/react/shallow
vi.mock('zustand/react/shallow', () => ({
useShallow: <T,>(fn: (state: unknown) => T) => fn,
}))
-// Mock amplitude tracking
vi.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/st
useDataSourceStoreWithSelector: <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 & Act
render(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Assert
expect(screen.getByText('Step 1')).toBeInTheDocument()
expect(screen.getByText('Step 2')).toBeInTheDocument()
expect(screen.getByText('Step 3')).toBeInTheDocument()
})
it('should render all step labels', () => {
- // Arrange
const steps = [
{ label: 'Data Source', value: 'dataSource' },
{ label: 'Processing', value: 'processing' },
]
- // Act
render(<StepIndicator steps={steps} currentStep={1} />)
- // Assert
expect(screen.getByText('Data Source')).toBeInTheDocument()
expect(screen.getByText('Processing')).toBeInTheDocument()
})
it('should render container with correct classes', () => {
- // Arrange & Act
const { container } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Assert
const wrapper = container.firstChild as HTMLElement
expect(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 & Act
const { container } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Assert - Should have 2 dividers for 3 steps
const dividers = container.querySelectorAll('.h-px.w-3')
expect(dividers.length).toBe(2)
})
it('should not render divider when there is only one step', () => {
- // Arrange
const singleStep = [{ label: 'Only Step', value: 'only' }]
- // Act
const { container } = render(<StepIndicator steps={singleStep} currentStep={1} />)
- // Assert
const 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 & Act
const { container } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Assert - Check for accent indicator on first step
const 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 & Act
render(<StepIndicator steps={defaultSteps} currentStep={2} />)
- // Assert
const step2Container = screen.getByText('Step 2').parentElement
expect(step2Container?.className).toContain('text-state-accent-solid')
})
it('should highlight third step when currentStep is 3', () => {
- // Arrange & Act
render(<StepIndicator steps={defaultSteps} currentStep={3} />)
- // Assert
const step3Container = screen.getByText('Step 3').parentElement
expect(step3Container?.className).toContain('text-state-accent-solid')
})
it('should apply tertiary color to non-current steps', () => {
- // Arrange & Act
render(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Assert
const step2Container = screen.getByText('Step 2').parentElement
expect(step2Container?.className).toContain('text-text-tertiary')
})
it('should show dot indicator only for current step', () => {
- // Arrange & Act
const { container } = render(<StepIndicator steps={defaultSteps} currentStep={2} />)
- // Assert - Only one dot should exist
const dots = container.querySelectorAll('.size-1.rounded-full')
expect(dots.length).toBe(1)
})
it('should handle empty steps array', () => {
- // Arrange & Act
const { container } = render(<StepIndicator steps={[]} currentStep={1} />)
- // Assert
expect(container.firstChild).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should be wrapped with React.memo', () => {
- // Arrange & Act
const { rerender } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Rerender with same props
rerender(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Assert - Component should render correctly
expect(screen.getByText('Step 1')).toBeInTheDocument()
})
it('should update when currentStep changes', () => {
- // Arrange
const { rerender } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Assert initial state
let step1Container = screen.getByText('Step 1').parentElement
expect(step1Container?.className).toContain('text-state-accent-solid')
- // Act - Change step
rerender(<StepIndicator steps={defaultSteps} currentStep={2} />)
- // Assert
step1Container = screen.getByText('Step 1').parentElement
expect(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', () => {
- // Arrange
const { rerender } = render(<StepIndicator steps={defaultSteps} currentStep={1} />)
- // Act
const newSteps = [
{ label: 'New Step 1', value: 'new1' },
{ label: 'New Step 2', value: 'new2' },
]
rerender(<StepIndicator steps={newSteps} currentStep={1} />)
- // Assert
expect(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 & Act
const { 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 & Act
const { container } = render(<StepIndicator steps={defaultSteps} currentStep={10} />)
- // Assert - No step should be highlighted
const dots = container.querySelectorAll('.size-1.rounded-full')
expect(dots.length).toBe(0)
})
it('should handle steps with empty labels', () => {
- // Arrange
const stepsWithEmpty = [
{ label: '', value: 'empty' },
{ label: 'Valid', value: 'valid' },
]
- // Act
render(<StepIndicator steps={stepsWithEmpty} currentStep={1} />)
- // Assert
expect(screen.getByText('Valid')).toBeInTheDocument()
})
it('should handle steps with very long labels', () => {
- // Arrange
const longLabel = 'A'.repeat(100)
const stepsWithLong = [{ label: longLabel, value: 'long' }]
- // Act
render(<StepIndicator steps={stepsWithLong} currentStep={1} />)
- // Assert
expect(screen.getByText(longLabel)).toBeInTheDocument()
})
it('should handle special characters in labels', () => {
- // Arrange
const specialSteps = [{ label: '<Test> & "Label"', value: 'special' }]
- // Act
render(<StepIndicator steps={specialSteps} currentStep={1} />)
- // Assert
expect(screen.getByText('<Test> & "Label"')).toBeInTheDocument()
})
it('should handle unicode characters in labels', () => {
- // Arrange
const unicodeSteps = [{ label: '数据源 🎉', value: 'unicode' }]
- // Act
render(<StepIndicator steps={unicodeSteps} currentStep={1} />)
- // Assert
expect(screen.getByText('数据源 🎉')).toBeInTheDocument()
})
it('should handle negative currentStep', () => {
- // Arrange & Act
const { container } = render(<StepIndicator steps={defaultSteps} currentStep={-1} />)
- // Assert - No step should be highlighted
const 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 & Act
render(<FooterTips />)
- // Assert - Check for translated text
expect(screen.getByText('datasetPipeline.testRun.tooltip')).toBeInTheDocument()
})
it('should render with correct container classes', () => {
- // Arrange & Act
const { container } = render(<FooterTips />)
- // Assert
const wrapper = container.firstChild as HTMLElement
expect(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 & Act
const { rerender } = render(<FooterTips />)
- // Rerender
rerender(<FooterTips />)
- // Assert
expect(screen.getByText('datasetPipeline.testRun.tooltip')).toBeInTheDocument()
})
it('should render consistently across multiple rerenders', () => {
- // Arrange
const { rerender } = render(<FooterTips />)
- // Act - Multiple rerenders
for (let i = 0; i < 5; i++)
rerender(<FooterTips />)
- // Assert
expect(screen.getByText('datasetPipeline.testRun.tooltip')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle unmount cleanly', () => {
- // Arrange
const { unmount } = render(<FooterTips />)
- // Assert
expect(() => 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 & Act
const { result } = renderHook(() => useTestRunSteps())
- // Assert
expect(result.current.currentStep).toBe(1)
})
it('should provide steps array with data source and document processing steps', () => {
- // Arrange & Act
const { result } = renderHook(() => useTestRunSteps())
- // Assert
expect(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 & Act
const { result } = renderHook(() => useTestRunSteps())
- // Assert
expect(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', () => {
- // Arrange
const { result } = renderHook(() => useTestRunSteps())
- // Act
act(() => {
result.current.handleNextStep()
})
- // Assert
expect(result.current.currentStep).toBe(2)
})
it('should continue incrementing on multiple calls', () => {
- // Arrange
const { result } = renderHook(() => useTestRunSteps())
- // Act
act(() => {
result.current.handleNextStep()
result.current.handleNextStep()
result.current.handleNextStep()
})
- // Assert
expect(result.current.currentStep).toBe(4)
})
})
- // -------------------------------------------------------------------------
- // handleBackStep Tests
- // -------------------------------------------------------------------------
describe('handleBackStep', () => {
it('should decrement currentStep by 1', () => {
- // Arrange
const { result } = renderHook(() => useTestRunSteps())
- // First go to step 2
act(() => {
result.current.handleNextStep()
})
expect(result.current.currentStep).toBe(2)
- // Act
act(() => {
result.current.handleBackStep()
})
- // Assert
expect(result.current.currentStep).toBe(1)
})
it('should allow going to negative steps (no validation)', () => {
- // Arrange
const { result } = renderHook(() => useTestRunSteps())
- // Act
act(() => {
result.current.handleBackStep()
})
- // Assert
expect(result.current.currentStep).toBe(0)
})
it('should continue decrementing on multiple calls', () => {
- // Arrange
const { result } = renderHook(() => useTestRunSteps())
- // Go to step 5
act(() => {
for (let i = 0; i < 4; i++)
result.current.handleNextStep()
})
expect(result.current.currentStep).toBe(5)
- // Act - Go back 3 steps
act(() => {
result.current.handleBackStep()
result.current.handleBackStep()
result.current.handleBackStep()
})
- // Assert
expect(result.current.currentStep).toBe(2)
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should return stable handleNextStep callback', () => {
- // Arrange
const { result, rerender } = renderHook(() => useTestRunSteps())
const initialCallback = result.current.handleNextStep
- // Act
rerender()
- // Assert
expect(result.current.handleNextStep).toBe(initialCallback)
})
it('should return stable handleBackStep callback', () => {
- // Arrange
const { result, rerender } = renderHook(() => useTestRunSteps())
const initialCallback = result.current.handleBackStep
- // Act
rerender()
- // Assert
expect(result.current.handleBackStep).toBe(initialCallback)
})
})
- // -------------------------------------------------------------------------
- // Integration Tests
- // -------------------------------------------------------------------------
describe('Integration', () => {
it('should handle forward and backward navigation', () => {
- // Arrange
const { result } = renderHook(() => useTestRunSteps())
- // Act & Assert - Navigate forward
act(() => result.current.handleNextStep())
expect(result.current.currentStep).toBe(2)
act(() => result.current.handleNextStep())
expect(result.current.currentStep).toBe(3)
- // Act & Assert - Navigate backward
act(() => 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', () => {
- // Arrange
mockNodes = []
- // Act
const { result } = renderHook(() => useDatasourceOptions())
- // Assert
expect(result.current).toEqual([])
})
it('should return empty array when no DataSource nodes exist', () => {
- // Arrange
mockNodes = [
{
id: 'node-1',
@@ -854,15 +656,12 @@ describe('useDatasourceOptions', () => {
},
]
- // Act
const { result } = renderHook(() => useDatasourceOptions())
- // Assert
expect(result.current).toEqual([])
})
it('should return options for DataSource nodes only', () => {
- // Arrange
mockNodes = [
{
id: 'datasource-1',
@@ -887,10 +686,8 @@ describe('useDatasourceOptions', () => {
},
]
- // Act
const { result } = renderHook(() => useDatasourceOptions())
- // Assert
expect(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', () => {
- // Arrange
mockNodes = [
{
id: 'unique-node-id-123',
@@ -916,15 +712,12 @@ describe('useDatasourceOptions', () => {
},
]
- // Act
const { result } = renderHook(() => useDatasourceOptions())
- // Assert
expect(result.current[0].value).toBe('unique-node-id-123')
})
it('should map node title to option label', () => {
- // Arrange
mockNodes = [
{
id: 'node-1',
@@ -935,15 +728,12 @@ describe('useDatasourceOptions', () => {
},
]
- // Act
const { result } = renderHook(() => useDatasourceOptions())
- // Assert
expect(result.current[0].label).toBe('Custom Data Source Title')
})
it('should include full node data in option', () => {
- // Arrange
const nodeData = {
...createNodeData({
title: 'Full Data Test',
@@ -960,20 +750,14 @@ describe('useDatasourceOptions', () => {
},
]
- // Act
const { result } = renderHook(() => useDatasourceOptions())
- // Assert
expect(result.current[0].data).toEqual(nodeData)
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should return same options reference when nodes do not change', () => {
- // Arrange
mockNodes = [
{
id: 'node-1',
@@ -984,18 +768,15 @@ describe('useDatasourceOptions', () => {
},
]
- // Act
const { result, rerender } = renderHook(() => useDatasourceOptions())
rerender()
- // Assert - Options should be memoized and still work correctly after rerender
expect(result.current).toHaveLength(1)
expect(result.current[0].label).toBe('Test')
})
it('should update options when nodes change', () => {
- // Arrange
mockNodes = [
{
id: 'node-1',
@@ -1010,7 +791,6 @@ describe('useDatasourceOptions', () => {
expect(result.current).toHaveLength(1)
expect(result.current[0].label).toBe('First')
- // Act - Change nodes
mockNodes = [
{
id: 'node-2',
@@ -1029,19 +809,14 @@ describe('useDatasourceOptions', () => {
]
rerender()
- // Assert
expect(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', () => {
- // Arrange
mockNodes = [
{
id: 'node-1',
@@ -1052,15 +827,12 @@ describe('useDatasourceOptions', () => {
},
]
- // Act
const { result } = renderHook(() => useDatasourceOptions())
- // Assert
expect(result.current[0].label).toBe('')
})
it('should handle multiple DataSource nodes', () => {
- // Arrange
mockNodes = Array.from({ length: 10 }, (_, i) => ({
id: `node-${i}`,
data: {
@@ -1069,10 +841,8 @@ describe('useDatasourceOptions', () => {
} as DataSourceNodeType,
}))
- // Act
const { result } = renderHook(() => useDatasourceOptions())
- // Assert
expect(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', () => {
- // Arrange
const { result } = renderHook(() => useOnlineDocument())
- // Act
act(() => {
result.current.clearOnlineDocumentData()
})
- // Assert
expect(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', () => {
- // Arrange
const { 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'))
- // Act
act(() => {
result.current.clearOnlineDocumentData()
})
- // Assert
expect(callOrder).toEqual([
'setDocumentsData',
'setSearchValue',
@@ -1139,58 +896,40 @@ describe('useOnlineDocument', () => {
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should maintain functional callback after rerender', () => {
- // Arrange
const { result, rerender } = renderHook(() => useOnlineDocument())
- // Act - First call
act(() => {
result.current.clearOnlineDocumentData()
})
const firstCallCount = mockDataSourceStoreState.setDocumentsData.mock.calls.length
- // Rerender
rerender()
- // Act - Second call after rerender
act(() => {
result.current.clearOnlineDocumentData()
})
- // Assert - Callback should still work after rerender
expect(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', () => {
- // Arrange
const { result } = renderHook(() => useWebsiteCrawl())
- // Act
act(() => {
result.current.clearWebsiteCrawlData()
})
- // Assert
expect(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', () => {
- // Arrange
const { 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'))
- // Act
act(() => {
result.current.clearWebsiteCrawlData()
})
- // Assert
expect(callOrder).toEqual([
'setStep',
'setCrawlResult',
@@ -1224,58 +960,40 @@ describe('useWebsiteCrawl', () => {
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should maintain functional callback after rerender', () => {
- // Arrange
const { result, rerender } = renderHook(() => useWebsiteCrawl())
- // Act - First call
act(() => {
result.current.clearWebsiteCrawlData()
})
const firstCallCount = mockDataSourceStoreState.setStep.mock.calls.length
- // Rerender
rerender()
- // Act - Second call after rerender
act(() => {
result.current.clearWebsiteCrawlData()
})
- // Assert - Callback should still work after rerender
expect(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', () => {
- // Arrange
const { result } = renderHook(() => useOnlineDrive())
- // Act
act(() => {
result.current.clearOnlineDriveData()
})
- // Assert
expect(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', () => {
- // Arrange
const { 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'))
- // Act
act(() => {
result.current.clearOnlineDriveData()
})
- // Assert
expect(callOrder).toEqual([
'setOnlineDriveFileList',
'setBucket',
@@ -1309,398 +1024,291 @@ describe('useOnlineDrive', () => {
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should maintain functional callback after rerender', () => {
- // Arrange
const { result, rerender } = renderHook(() => useOnlineDrive())
- // Act - First call
act(() => {
result.current.clearOnlineDriveData()
})
const firstCallCount = mockDataSourceStoreState.setOnlineDriveFileList.mock.calls.length
- // Rerender
rerender()
- // Act - Second call after rerender
act(() => {
result.current.clearOnlineDriveData()
})
- // Assert - Callback should still work after rerender
expect(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 & Act
render(<Preparation />)
- // Assert
expect(screen.getByTestId('data-source-options')).toBeInTheDocument()
})
it('should render StepIndicator', () => {
- // Arrange & Act
render(<Preparation />)
- // Assert - Check for step text
expect(screen.getByText('datasetPipeline.testRun.steps.dataSource')).toBeInTheDocument()
expect(screen.getByText('datasetPipeline.testRun.steps.documentProcessing')).toBeInTheDocument()
})
it('should render DataSourceOptions on step 1', () => {
- // Arrange & Act
render(<Preparation />)
- // Assert
expect(screen.getByTestId('data-source-options')).toBeInTheDocument()
})
it('should render Actions on step 1', () => {
- // Arrange & Act
render(<Preparation />)
- // Assert
expect(screen.getByText('datasetCreation.stepOne.button')).toBeInTheDocument()
})
it('should render FooterTips on step 1', () => {
- // Arrange & Act
render(<Preparation />)
- // Assert
expect(screen.getByText('datasetPipeline.testRun.tooltip')).toBeInTheDocument()
})
it('should not render DocumentProcessing on step 1', () => {
- // Arrange & Act
render(<Preparation />)
- // Assert
expect(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', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(screen.getByTestId('local-file')).toBeInTheDocument()
})
it('should render OnlineDocuments component when online document datasource is selected', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert
expect(screen.getByTestId('online-documents')).toBeInTheDocument()
})
it('should render WebsiteCrawl component when website crawl datasource is selected', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-website-crawl'))
- // Assert
expect(screen.getByTestId('website-crawl')).toBeInTheDocument()
})
it('should render OnlineDrive component when online drive datasource is selected', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-drive'))
- // Assert
expect(screen.getByTestId('online-drive')).toBeInTheDocument()
})
it('should pass correct props to LocalFile component', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
const 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', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert
const onlineDocs = screen.getByTestId('online-documents')
expect(onlineDocs).toHaveAttribute('data-in-pipeline', 'true')
})
it('should pass supportBatchUpload=false to all data source components', () => {
- // Arrange
render(<Preparation />)
- // Act - Select online document
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert
expect(screen.getByTestId('online-documents')).toHaveAttribute('data-batch', 'false')
})
it('should update dataSourceNodeId when selecting different datasources', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(screen.getByTestId('data-source-options')).toHaveAttribute('data-selected', 'local-file-node')
- // Act - Select another
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert
expect(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 & Act
render(<Preparation />)
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
})
it('should disable next button for local file when file list is empty', () => {
- // Arrange
mockDataSourceStoreState.localFileList = []
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
})
it('should disable next button for local file when file has no id', () => {
- // Arrange
mockDataSourceStoreState.localFileList = [
{ file: { id: '', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },
]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
})
it('should enable next button for local file when file has valid id', () => {
- // Arrange
mockDataSourceStoreState.localFileList = [
{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },
]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()
})
it('should disable next button for online document when documents list is empty', () => {
- // Arrange
mockDataSourceStoreState.onlineDocuments = []
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
})
it('should enable next button for online document when documents exist', () => {
- // Arrange
mockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1', page_id: 'page-1' }]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()
})
it('should disable next button for website crawl when pages list is empty', () => {
- // Arrange
mockDataSourceStoreState.websitePages = []
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-website-crawl'))
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
})
it('should enable next button for website crawl when pages exist', () => {
- // Arrange
mockDataSourceStoreState.websitePages = [{ url: 'https://example.com' }]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-website-crawl'))
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()
})
it('should disable next button for online drive when no files selected', () => {
- // Arrange
mockDataSourceStoreState.selectedFileIds = []
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-drive'))
- // Assert
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
})
it('should enable next button for online drive when files are selected', () => {
- // Arrange
mockDataSourceStoreState.selectedFileIds = ['file-1']
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-drive'))
- // Assert
expect(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', () => {
- // Arrange
mockDataSourceStoreState.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 next
fireEvent.click(screen.getByTestId('select-local-file'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
- // Assert
expect(screen.getByTestId('document-processing')).toBeInTheDocument()
expect(screen.queryByTestId('data-source-options')).not.toBeInTheDocument()
})
it('should pass correct dataSourceNodeId to DocumentProcessing', () => {
- // Arrange
mockDataSourceStoreState.localFileList = [
{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },
]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
- // Assert
expect(screen.getByTestId('document-processing')).toHaveAttribute('data-node-id', 'local-file-node')
})
it('should navigate back to step 1 when back button is clicked', () => {
- // Arrange
mockDataSourceStoreState.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 2
fireEvent.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
fireEvent.click(screen.getByTestId('back-btn'))
- // Assert
expect(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 () => {
- // Arrange
mockDataSourceStoreState.localFileList = [
{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },
]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
fireEvent.click(screen.getByTestId('process-btn'))
- // Assert
await 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 () => {
- // Arrange
mockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1', page_id: 'page-1', title: 'Test Doc' }]
mockDataSourceStoreState.currentCredentialId = 'cred-123'
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-document'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
fireEvent.click(screen.getByTestId('process-btn'))
- // Assert
await 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 () => {
- // Arrange
mockDataSourceStoreState.websitePages = [{ url: 'https://example.com', title: 'Example' }]
mockDataSourceStoreState.currentCredentialId = 'cred-456'
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-website-crawl'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
fireEvent.click(screen.getByTestId('process-btn'))
- // Assert
await 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 () => {
- // Arrange
mockDataSourceStoreState.selectedFileIds = ['file-1']
mockDataSourceStoreState.onlineDriveFileList = [{ id: 'file-1', name: 'data.csv', type: 'file' }]
mockDataSourceStoreState.bucket = 'my-bucket'
mockDataSourceStoreState.currentCredentialId = 'cred-789'
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-drive'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
fireEvent.click(screen.getByTestId('process-btn'))
- // Assert
await waitFor(() => {
expect(mockHandleRun).toHaveBeenCalledWith(expect.objectContaining({
inputs: { field1: 'value1' },
@@ -1776,211 +1375,151 @@ describe('Preparation', () => {
})
it('should call setIsPreparingDataSource(false) after processing', async () => {
- // Arrange
mockDataSourceStoreState.localFileList = [
{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },
]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
fireEvent.click(screen.getByTestId('process-btn'))
- // Assert
await waitFor(() => {
expect(mockWorkflowStoreState.setIsPreparingDataSource).toHaveBeenCalledWith(false)
})
})
})
- // -------------------------------------------------------------------------
- // clearDataSourceData Tests
- // -------------------------------------------------------------------------
describe('clearDataSourceData', () => {
it('should clear online document data when switching from online document', () => {
- // Arrange
render(<Preparation />)
- // Act - Select online document first
fireEvent.click(screen.getByTestId('select-online-document'))
- // Then switch to local file
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(mockDataSourceStoreState.setDocumentsData).toHaveBeenCalled()
expect(mockDataSourceStoreState.setOnlineDocuments).toHaveBeenCalled()
})
it('should clear website crawl data when switching from website crawl', () => {
- // Arrange
render(<Preparation />)
- // Act - Select website crawl first
fireEvent.click(screen.getByTestId('select-website-crawl'))
- // Then switch to local file
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(mockDataSourceStoreState.setWebsitePages).toHaveBeenCalled()
expect(mockDataSourceStoreState.setCrawlResult).toHaveBeenCalled()
})
it('should clear online drive data when switching from online drive', () => {
- // Arrange
render(<Preparation />)
- // Act - Select online drive first
fireEvent.click(screen.getByTestId('select-online-drive'))
- // Then switch to local file
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(mockDataSourceStoreState.setOnlineDriveFileList).toHaveBeenCalled()
expect(mockDataSourceStoreState.setBucket).toHaveBeenCalled()
})
})
- // -------------------------------------------------------------------------
- // handleCredentialChange Tests
- // -------------------------------------------------------------------------
describe('handleCredentialChange', () => {
it('should update credential and clear data when credential changes for online document', () => {
- // Arrange
mockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1' }]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-document'))
fireEvent.click(screen.getByText('Change Credential'))
- // Assert
expect(mockDataSourceStoreState.setCurrentCredentialId).toHaveBeenCalledWith('new-credential-id')
})
it('should clear data when credential changes for website crawl', () => {
- // Arrange
mockDataSourceStoreState.websitePages = [{ url: 'https://example.com' }]
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-website-crawl'))
fireEvent.click(screen.getByText('Change Credential'))
- // Assert
expect(mockDataSourceStoreState.setCurrentCredentialId).toHaveBeenCalledWith('new-credential-id')
expect(mockDataSourceStoreState.setWebsitePages).toHaveBeenCalled()
})
it('should clear data when credential changes for online drive', () => {
- // Arrange
mockDataSourceStoreState.selectedFileIds = ['file-1']
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-online-drive'))
fireEvent.click(screen.getByText('Change Credential'))
- // Assert
expect(mockDataSourceStoreState.setCurrentCredentialId).toHaveBeenCalledWith('new-credential-id')
expect(mockDataSourceStoreState.setOnlineDriveFileList).toHaveBeenCalled()
})
})
- // -------------------------------------------------------------------------
- // handleSwitchDataSource Tests
- // -------------------------------------------------------------------------
describe('handleSwitchDataSource', () => {
it('should clear credential when switching datasource', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(mockDataSourceStoreState.setCurrentCredentialId).toHaveBeenCalledWith('')
})
it('should update currentNodeIdRef when switching datasource', () => {
- // Arrange
render(<Preparation />)
- // Act
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert
expect(mockDataSourceStoreState.currentNodeIdRef.current).toBe('local-file-node')
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should be wrapped with React.memo', () => {
- // Arrange & Act
const { rerender } = render(<Preparation />)
rerender(<Preparation />)
- // Assert
expect(screen.getByTestId('data-source-options')).toBeInTheDocument()
})
it('should maintain state across rerenders', () => {
- // Arrange
mockDataSourceStoreState.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 2
fireEvent.click(screen.getByTestId('select-local-file'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
- // Rerender
rerender(<Preparation />)
- // Assert - Should still be on step 2
expect(screen.getByTestId('document-processing')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle unmount cleanly', () => {
- // Arrange
const { unmount } = render(<Preparation />)
- // Assert
expect(() => 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 types
render(<Preparation />)
- // Act - Select unknown type datasource
fireEvent.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 branch
render(<Preparation />)
- // Act - Select unknown type and go to step 2
fireEvent.click(screen.getByTestId('select-unknown-type'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
- // Process with unknown type
fireEvent.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', () => {
- // Arrange
render(<Preparation />)
- // Act - Rapidly switch between datasources
fireEvent.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 selected
expect(screen.getByTestId('local-file')).toBeInTheDocument()
})
it('should handle rapid step navigation', () => {
- // Arrange
mockDataSourceStoreState.localFileList = [
{ file: { id: 'file-123', name: 'test.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },
]
render(<Preparation />)
- // Act - Select and navigate
fireEvent.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 1
expect(screen.getByTestId('data-source-options')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Integration Tests
- // -------------------------------------------------------------------------
describe('Integration', () => {
it('should complete full flow: select datasource -> next -> process', async () => {
- // Arrange
mockDataSourceStoreState.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 datasource
fireEvent.click(screen.getByTestId('select-local-file'))
expect(screen.getByTestId('local-file')).toBeInTheDocument()
- // Act - Step 1: Click next
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
expect(screen.getByTestId('document-processing')).toBeInTheDocument()
- // Act - Step 2: Process
fireEvent.click(screen.getByTestId('process-btn'))
- // Assert
await waitFor(() => {
expect(mockHandleRun).toHaveBeenCalled()
})
})
it('should complete full flow with back navigation', async () => {
- // Arrange
mockDataSourceStoreState.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 2
fireEvent.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 document
fireEvent.click(screen.getByTestId('back-btn'))
fireEvent.click(screen.getByTestId('select-online-document'))
expect(screen.getByTestId('online-documents')).toBeInTheDocument()
- // Act - Go to step 2 again
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
- // Assert - Should be on step 2 with online document
expect(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', () => {
- // Arrange
const { rerender } = render(<Preparation />)
fireEvent.click(screen.getByTestId('select-local-file'))
- // Assert - Initially disabled
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
- // Act - Update localFileList
mockDataSourceStoreState.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 enabled
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()
})
it('should update when onlineDocuments changes', () => {
- // Arrange
const { rerender } = render(<Preparation />)
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert - Initially disabled
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
- // Act - Update onlineDocuments
mockDataSourceStoreState.onlineDocuments = [{ workspace_id: 'ws-1' }]
rerender(<Preparation />)
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert - Now enabled
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()
})
it('should update when websitePages changes', () => {
- // Arrange
const { rerender } = render(<Preparation />)
fireEvent.click(screen.getByTestId('select-website-crawl'))
- // Assert - Initially disabled
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
- // Act - Update websitePages
mockDataSourceStoreState.websitePages = [{ url: 'https://example.com' }]
rerender(<Preparation />)
fireEvent.click(screen.getByTestId('select-website-crawl'))
- // Assert - Now enabled
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).not.toBeDisabled()
})
it('should update when selectedFileIds changes', () => {
- // Arrange
const { rerender } = render(<Preparation />)
fireEvent.click(screen.getByTestId('select-online-drive'))
- // Assert - Initially disabled
expect(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i })).toBeDisabled()
- // Act - Update selectedFileIds
mockDataSourceStoreState.selectedFileIds = ['file-1']
rerender(<Preparation />)
fireEvent.click(screen.getByTestId('select-online-drive'))
- // Assert - Now enabled
expect(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 () => {
- // Arrange
mockDataSourceStoreState.localFileList = [
{ file: { id: 'initial-file', name: 'initial.txt', type: 'text/plain', size: 100, extension: 'txt', mime_type: 'text/plain' } },
]
render(<Preparation />)
- // Act - Select and navigate
fireEvent.click(screen.getByTestId('select-local-file'))
fireEvent.click(screen.getByRole('button', { name: /datasetCreation.stepOne.button/i }))
- // Update store before processing
mockDataSourceStoreState.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 file
await 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', () => {
- // Arrange
render(<Preparation />)
- // Act - Select online document
fireEvent.click(screen.getByTestId('select-online-document'))
- // Assert
expect(mockDataSourceStoreState.setOnlineDocuments).toHaveBeenCalled()
- // Act - Switch to website crawl
fireEvent.click(screen.getByTestId('select-website-crawl'))
- // Assert
expect(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.tsx
similarity index 74%
rename from web/app/components/rag-pipeline/components/panel/test-run/preparation/actions/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/test-run/preparation/actions/__tests__/index.spec.tsx
index 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', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions handleNextStep={handleNextStep} />)
- // Assert
expect(screen.getByRole('button')).toBeInTheDocument()
})
it('should render button with translated text', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions handleNextStep={handleNextStep} />)
- // Assert - Translation mock returns key with namespace prefix
expect(screen.getByText('datasetCreation.stepOne.button')).toBeInTheDocument()
})
it('should render with correct container structure', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { container } = render(<Actions handleNextStep={handleNextStep} />)
- // Assert
const wrapper = container.firstChild as HTMLElement
expect(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', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { container } = render(<Actions handleNextStep={handleNextStep} />)
- // Assert
const 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', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions disabled={true} handleNextStep={handleNextStep} />)
- // Assert
expect(screen.getByRole('button')).toBeDisabled()
})
it('should pass disabled=false to button when disabled prop is false', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions disabled={false} handleNextStep={handleNextStep} />)
- // Assert
expect(screen.getByRole('button')).not.toBeDisabled()
})
it('should not disable button when disabled prop is undefined', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions handleNextStep={handleNextStep} />)
- // Assert
expect(screen.getByRole('button')).not.toBeDisabled()
})
it('should handle disabled switching from true to false', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { rerender } = render(
<Actions disabled={true} handleNextStep={handleNextStep} />,
)
- // Assert - Initially disabled
expect(screen.getByRole('button')).toBeDisabled()
- // Act - Rerender with disabled=false
rerender(<Actions disabled={false} handleNextStep={handleNextStep} />)
- // Assert - Now enabled
expect(screen.getByRole('button')).not.toBeDisabled()
})
it('should handle disabled switching from false to true', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { rerender } = render(
<Actions disabled={false} handleNextStep={handleNextStep} />,
)
- // Assert - Initially enabled
expect(screen.getByRole('button')).not.toBeDisabled()
- // Act - Rerender with disabled=true
rerender(<Actions disabled={true} handleNextStep={handleNextStep} />)
- // Assert - Now disabled
expect(screen.getByRole('button')).toBeDisabled()
})
it('should handle undefined disabled becoming true', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { rerender } = render(
<Actions handleNextStep={handleNextStep} />,
)
- // Assert - Initially not disabled (undefined)
expect(screen.getByRole('button')).not.toBeDisabled()
- // Act - Rerender with disabled=true
rerender(<Actions disabled={true} handleNextStep={handleNextStep} />)
- // Assert - Now disabled
expect(screen.getByRole('button')).toBeDisabled()
})
})
- // -------------------------------------------------------------------------
- // User Interaction Tests
- // -------------------------------------------------------------------------
describe('User Interactions', () => {
it('should call handleNextStep when button is clicked', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions handleNextStep={handleNextStep} />)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(handleNextStep).toHaveBeenCalledTimes(1)
})
it('should call handleNextStep exactly once per click', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions handleNextStep={handleNextStep} />)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(handleNextStep).toHaveBeenCalled()
expect(handleNextStep.mock.calls).toHaveLength(1)
})
it('should call handleNextStep multiple times on multiple clicks', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions handleNextStep={handleNextStep} />)
const button = screen.getByRole('button')
fireEvent.click(button)
fireEvent.click(button)
fireEvent.click(button)
- // Assert
expect(handleNextStep).toHaveBeenCalledTimes(3)
})
it('should not call handleNextStep when button is disabled and clicked', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions disabled={true} handleNextStep={handleNextStep} />)
fireEvent.click(screen.getByRole('button'))
- // Assert - Disabled button should not trigger onClick
expect(handleNextStep).not.toHaveBeenCalled()
})
it('should handle rapid clicks when not disabled', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions handleNextStep={handleNextStep} />)
const button = screen.getByRole('button')
- // Simulate rapid clicks
for (let i = 0; i < 10; i++)
fireEvent.click(button)
- // Assert
expect(handleNextStep).toHaveBeenCalledTimes(10)
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should use the new handleNextStep when prop changes', () => {
- // Arrange
const handleNextStep1 = vi.fn()
const handleNextStep2 = vi.fn()
- // Act
const { rerender } = render(
<Actions handleNextStep={handleNextStep1} />,
)
@@ -251,16 +181,13 @@ describe('Actions', () => {
rerender(<Actions handleNextStep={handleNextStep2} />)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(handleNextStep1).toHaveBeenCalledTimes(1)
expect(handleNextStep2).toHaveBeenCalledTimes(1)
})
it('should maintain functionality after rerender with same props', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { rerender } = render(
<Actions handleNextStep={handleNextStep} />,
)
@@ -269,17 +196,14 @@ describe('Actions', () => {
rerender(<Actions handleNextStep={handleNextStep} />)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(handleNextStep).toHaveBeenCalledTimes(2)
})
it('should work correctly when handleNextStep changes multiple times', () => {
- // Arrange
const handleNextStep1 = vi.fn()
const handleNextStep2 = vi.fn()
const handleNextStep3 = vi.fn()
- // Act
const { rerender } = render(
<Actions handleNextStep={handleNextStep1} />,
)
@@ -291,77 +215,58 @@ describe('Actions', () => {
rerender(<Actions handleNextStep={handleNextStep3} />)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(handleNextStep1).toHaveBeenCalledTimes(1)
expect(handleNextStep2).toHaveBeenCalledTimes(1)
expect(handleNextStep3).toHaveBeenCalledTimes(1)
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should be wrapped with React.memo', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act - Verify component is memoized by checking display name pattern
const { rerender } = render(
<Actions handleNextStep={handleNextStep} />,
)
- // Rerender with same props should work without issues
rerender(<Actions handleNextStep={handleNextStep} />)
- // Assert - Component should render correctly after rerender
expect(screen.getByRole('button')).toBeInTheDocument()
})
it('should not break when props remain the same across rerenders', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { rerender } = render(
<Actions disabled={false} handleNextStep={handleNextStep} />,
)
- // Multiple rerenders with same props
for (let i = 0; i < 5; i++) {
rerender(<Actions disabled={false} handleNextStep={handleNextStep} />)
}
- // Assert - Should still function correctly
fireEvent.click(screen.getByRole('button'))
expect(handleNextStep).toHaveBeenCalledTimes(1)
})
it('should update correctly when only disabled prop changes', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { rerender } = render(
<Actions disabled={false} handleNextStep={handleNextStep} />,
)
- // Assert - Initially not disabled
expect(screen.getByRole('button')).not.toBeDisabled()
- // Act - Change only disabled prop
rerender(<Actions disabled={true} handleNextStep={handleNextStep} />)
- // Assert - Should reflect the new disabled state
expect(screen.getByRole('button')).toBeDisabled()
})
it('should update correctly when only handleNextStep prop changes', () => {
- // Arrange
const handleNextStep1 = vi.fn()
const handleNextStep2 = vi.fn()
- // Act
const { 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 prop
rerender(<Actions disabled={false} handleNextStep={handleNextStep2} />)
fireEvent.click(screen.getByRole('button'))
- // Assert - New callback should be used
expect(handleNextStep1).toHaveBeenCalledTimes(1)
expect(handleNextStep2).toHaveBeenCalledTimes(1)
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should call handleNextStep even if it has side effects', () => {
- // Arrange
let sideEffectValue = 0
const handleNextStep = vi.fn(() => {
sideEffectValue = 42
})
- // Act
render(<Actions handleNextStep={handleNextStep} />)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(handleNextStep).toHaveBeenCalledTimes(1)
expect(sideEffectValue).toBe(42)
})
it('should handle handleNextStep that returns a value', () => {
- // Arrange
const handleNextStep = vi.fn(() => 'return value')
- // Act
render(<Actions handleNextStep={handleNextStep} />)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(handleNextStep).toHaveBeenCalledTimes(1)
expect(handleNextStep).toHaveReturnedWith('return value')
})
it('should handle handleNextStep that is async', async () => {
- // Arrange
const handleNextStep = vi.fn().mockResolvedValue(undefined)
- // Act
render(<Actions handleNextStep={handleNextStep} />)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(handleNextStep).toHaveBeenCalledTimes(1)
})
it('should render correctly with both disabled=true and handleNextStep', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions disabled={true} handleNextStep={handleNextStep} />)
- // Assert
const button = screen.getByRole('button')
expect(button).toBeDisabled()
})
it('should handle component unmount gracefully', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { unmount } = render(<Actions handleNextStep={handleNextStep} />)
- // Assert - Unmount should not throw
expect(() => unmount()).not.toThrow()
})
it('should handle disabled as boolean-like falsy value', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act - Test with explicit false
render(<Actions disabled={false} handleNextStep={handleNextStep} />)
- // Assert
expect(screen.getByRole('button')).not.toBeDisabled()
})
})
- // -------------------------------------------------------------------------
- // Accessibility Tests
- // -------------------------------------------------------------------------
describe('Accessibility', () => {
it('should have button element that can receive focus', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<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', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
render(<Actions disabled={true} handleNextStep={handleNextStep} />)
- // Assert
expect(screen.getByRole('button')).toHaveAttribute('disabled')
})
})
- // -------------------------------------------------------------------------
- // Integration Tests
- // -------------------------------------------------------------------------
describe('Integration', () => {
it('should work in a typical workflow: enable -> click -> disable', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act - Start enabled
const { rerender } = render(
<Actions disabled={false} handleNextStep={handleNextStep} />,
)
- // Assert - Can click when enabled
expect(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 disabled
expect(screen.getByRole('button')).toBeDisabled()
fireEvent.click(screen.getByRole('button'))
expect(handleNextStep).toHaveBeenCalledTimes(1) // Still 1, not 2
- // Act - Re-enable
rerender(<Actions disabled={false} handleNextStep={handleNextStep} />)
- // Assert - Can click again
expect(screen.getByRole('button')).not.toBeDisabled()
fireEvent.click(screen.getByRole('button'))
expect(handleNextStep).toHaveBeenCalledTimes(2)
})
it('should maintain consistent rendering across multiple state changes', () => {
- // Arrange
const handleNextStep = vi.fn()
- // Act
const { rerender } = render(
<Actions disabled={false} handleNextStep={handleNextStep} />,
)
- // Toggle disabled state multiple times
const 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 correctly
expect(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.tsx
similarity index 80%
rename from web/app/components/rag-pipeline/components/panel/test-run/preparation/data-source-options/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/test-run/preparation/data-source-options/__tests__/index.spec.tsx
index 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 hook
let mockDatasourceOptions: DataSourceOption[] = []
-vi.mock('../hooks', () => ({
+vi.mock('../../hooks', () => ({
useDatasourceOptions: () => mockDatasourceOptions,
}))
-// Mock useToolIcon hook
const mockToolIcon = { type: 'icon', icon: 'test-icon' }
vi.mock('@/app/components/workflow/hooks', () => ({
useToolIcon: () => mockToolIcon,
}))
-// Mock BlockIcon component
vi.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', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label="Test Label"
@@ -82,15 +62,12 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByText('Test Label')).toBeInTheDocument()
})
it('should render label text', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label="My Data Source"
@@ -100,15 +77,12 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByText('My Data Source')).toBeInTheDocument()
})
it('should render BlockIcon component', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label="Test"
@@ -118,15 +92,12 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByTestId('block-icon')).toBeInTheDocument()
})
it('should pass correct type to BlockIcon', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label="Test"
@@ -136,17 +107,13 @@ describe('OptionCard', () => {
/>,
)
- // Assert
const blockIcon = screen.getByTestId('block-icon')
- // BlockEnum.DataSource value is 'datasource'
expect(blockIcon).toHaveAttribute('data-type', 'datasource')
})
it('should set title attribute on label element', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label="Long Label Text"
@@ -156,20 +123,14 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByTitle('Long Label Text')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Props Variations Tests
- // -------------------------------------------------------------------------
describe('Props Variations', () => {
it('should apply selected styles when selected is true', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -179,17 +140,14 @@ describe('OptionCard', () => {
/>,
)
- // Assert
const card = container.firstChild as HTMLElement
expect(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', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -199,16 +157,13 @@ describe('OptionCard', () => {
/>,
)
- // Assert
const card = container.firstChild as HTMLElement
expect(card.className).not.toContain('border-components-option-card-option-selected-border')
})
it('should apply text-text-primary to label when selected', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label="Test Label"
@@ -218,16 +173,13 @@ describe('OptionCard', () => {
/>,
)
- // Assert
const label = screen.getByText('Test Label')
expect(label.className).toContain('text-text-primary')
})
it('should apply text-text-secondary to label when not selected', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label="Test Label"
@@ -237,16 +189,13 @@ describe('OptionCard', () => {
/>,
)
- // Assert
const label = screen.getByText('Test Label')
expect(label.className).toContain('text-text-secondary')
})
it('should handle undefined onClick prop', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -257,19 +206,16 @@ describe('OptionCard', () => {
/>,
)
- // Assert - should not throw when clicking
const card = container.firstChild as HTMLElement
expect(() => fireEvent.click(card)).not.toThrow()
})
it('should handle different node data types', () => {
- // Arrange
const nodeData = createNodeData({
title: 'Website Crawler',
provider_type: 'website_crawl',
})
- // Act
render(
<OptionCard
label="Website Crawler"
@@ -279,21 +225,15 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByText('Website Crawler')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // User Interaction Tests
- // -------------------------------------------------------------------------
describe('User Interactions', () => {
it('should call onClick with value when card is clicked', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -305,17 +245,14 @@ describe('OptionCard', () => {
)
fireEvent.click(container.firstChild as HTMLElement)
- // Assert
expect(onClick).toHaveBeenCalledTimes(1)
expect(onClick).toHaveBeenCalledWith('test-value')
})
it('should call onClick with correct value for different cards', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
- // Act
const { container: container1 } = render(
<OptionCard
label="Card 1"
@@ -338,18 +275,15 @@ describe('OptionCard', () => {
)
fireEvent.click(container2.firstChild as HTMLElement)
- // Assert
expect(onClick).toHaveBeenCalledTimes(2)
expect(onClick).toHaveBeenNthCalledWith(1, 'value-1')
expect(onClick).toHaveBeenNthCalledWith(2, 'value-2')
})
it('should handle rapid clicks', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -364,16 +298,13 @@ describe('OptionCard', () => {
fireEvent.click(card)
fireEvent.click(card)
- // Assert
expect(onClick).toHaveBeenCalledTimes(3)
})
it('should call onClick with empty string value', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -385,21 +316,15 @@ describe('OptionCard', () => {
)
fireEvent.click(container.firstChild as HTMLElement)
- // Assert
expect(onClick).toHaveBeenCalledWith('')
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should maintain stable handleClickCard callback when props dont change', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
- // Act
const { rerender, container } = render(
<OptionCard
label="Test"
@@ -422,18 +347,15 @@ describe('OptionCard', () => {
)
fireEvent.click(container.firstChild as HTMLElement)
- // Assert
expect(onClick).toHaveBeenCalledTimes(2)
expect(onClick).toHaveBeenNthCalledWith(1, 'test-value')
expect(onClick).toHaveBeenNthCalledWith(2, 'test-value')
})
it('should update handleClickCard when value changes', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
- // Act
const { rerender, container } = render(
<OptionCard
label="Test"
@@ -456,18 +378,15 @@ describe('OptionCard', () => {
)
fireEvent.click(container.firstChild as HTMLElement)
- // Assert
expect(onClick).toHaveBeenNthCalledWith(1, 'old-value')
expect(onClick).toHaveBeenNthCalledWith(2, 'new-value')
})
it('should update handleClickCard when onClick changes', () => {
- // Arrange
const onClick1 = vi.fn()
const onClick2 = vi.fn()
const nodeData = createNodeData()
- // Act
const { rerender, container } = render(
<OptionCard
label="Test"
@@ -490,22 +409,16 @@ describe('OptionCard', () => {
)
fireEvent.click(container.firstChild as HTMLElement)
- // Assert
expect(onClick1).toHaveBeenCalledTimes(1)
expect(onClick2).toHaveBeenCalledTimes(1)
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should be memoized (React.memo)', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
- // Act
const { rerender } = render(
<OptionCard
label="Test"
@@ -516,7 +429,6 @@ describe('OptionCard', () => {
/>,
)
- // Rerender with same props
rerender(
<OptionCard
label="Test"
@@ -527,15 +439,12 @@ describe('OptionCard', () => {
/>,
)
- // Assert - Component should render without issues
expect(screen.getByText('Test')).toBeInTheDocument()
})
it('should re-render when selected prop changes', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
const { rerender, container } = render(
<OptionCard
label="Test"
@@ -557,21 +466,15 @@ describe('OptionCard', () => {
/>,
)
- // Assert - Component should update styles
card = container.firstChild as HTMLElement
expect(card.className).toContain('border-components-option-card-option-selected-border')
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle empty label', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label=""
@@ -581,16 +484,13 @@ describe('OptionCard', () => {
/>,
)
- // Assert - Should render without crashing
expect(screen.getByTestId('block-icon')).toBeInTheDocument()
})
it('should handle very long label', () => {
- // Arrange
const nodeData = createNodeData()
const longLabel = 'A'.repeat(200)
- // Act
render(
<OptionCard
label={longLabel}
@@ -600,17 +500,14 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByText(longLabel)).toBeInTheDocument()
expect(screen.getByTitle(longLabel)).toBeInTheDocument()
})
it('should handle special characters in label', () => {
- // Arrange
const nodeData = createNodeData()
const specialLabel = '<Test> & \'Label\' "Special"'
- // Act
render(
<OptionCard
label={specialLabel}
@@ -620,15 +517,12 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByText(specialLabel)).toBeInTheDocument()
})
it('should handle unicode characters in label', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
render(
<OptionCard
label="数据源 🎉 データソース"
@@ -638,16 +532,13 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByText('数据源 🎉 データソース')).toBeInTheDocument()
})
it('should handle empty value', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -659,17 +550,14 @@ describe('OptionCard', () => {
)
fireEvent.click(container.firstChild as HTMLElement)
- // Assert
expect(onClick).toHaveBeenCalledWith('')
})
it('should handle special characters in value', () => {
- // Arrange
const onClick = vi.fn()
const nodeData = createNodeData()
const specialValue = 'test-value_123/abc:xyz'
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -681,15 +569,12 @@ describe('OptionCard', () => {
)
fireEvent.click(container.firstChild as HTMLElement)
- // Assert
expect(onClick).toHaveBeenCalledWith(specialValue)
})
it('should handle nodeData with minimal properties', () => {
- // Arrange
const minimalNodeData = { title: 'Minimal' } as unknown as DataSourceNodeType
- // Act
render(
<OptionCard
label="Minimal"
@@ -699,20 +584,14 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByText('Minimal')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Accessibility Tests
- // -------------------------------------------------------------------------
describe('Accessibility', () => {
it('should have cursor-pointer class for clickability indication', () => {
- // Arrange
const nodeData = createNodeData()
- // Act
const { container } = render(
<OptionCard
label="Test"
@@ -722,17 +601,14 @@ describe('OptionCard', () => {
/>,
)
- // Assert
const card = container.firstChild as HTMLElement
expect(card.className).toContain('cursor-pointer')
})
it('should provide title attribute for label tooltip', () => {
- // Arrange
const nodeData = createNodeData()
const label = 'This is a very long label that might get truncated'
- // Act
render(
<OptionCard
label={label}
@@ -742,31 +618,21 @@ describe('OptionCard', () => {
/>,
)
- // Assert
expect(screen.getByTitle(label)).toBeInTheDocument()
})
})
})
-// ============================================================================
-// DataSourceOptions Component Tests
-// ============================================================================
-
describe('DataSourceOptions', () => {
beforeEach(() => {
vi.clearAllMocks()
mockDatasourceOptions = []
})
- // -------------------------------------------------------------------------
- // Rendering Tests
- // -------------------------------------------------------------------------
describe('Rendering', () => {
it('should render container without crashing', () => {
- // Arrange
mockDatasourceOptions = []
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -774,19 +640,16 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
expect(container.querySelector('.grid')).toBeInTheDocument()
})
it('should render OptionCard for each option', () => {
- // Arrange
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option 1', value: 'opt-1' }),
createDataSourceOption({ label: 'Option 2', value: 'opt-2' }),
createDataSourceOption({ label: 'Option 3', value: 'opt-3' }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -794,17 +657,14 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
expect(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', () => {
- // Arrange
mockDatasourceOptions = []
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -812,17 +672,14 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
const grid = container.querySelector('.grid')
expect(grid).toBeInTheDocument()
expect(grid?.children.length).toBe(0)
})
it('should apply correct grid layout classes', () => {
- // Arrange
mockDatasourceOptions = [createDataSourceOption()]
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -830,7 +687,6 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
mockDatasourceOptions = [
createDataSourceOption({ label: 'A', value: 'a' }),
createDataSourceOption({ label: 'B', value: 'b' }),
]
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId="a"
@@ -852,24 +706,18 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option 1', value: 'opt-1' }),
createDataSourceOption({ label: 'Option 2', value: 'opt-2' }),
]
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId="opt-1"
@@ -877,20 +725,17 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert - First option should have selected styles
const 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', () => {
- // Arrange
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option 1', value: 'opt-1' }),
createDataSourceOption({ label: 'Option 2', value: 'opt-2' }),
]
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId="opt-2"
@@ -898,20 +743,17 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option 1', value: 'opt-1' }),
createDataSourceOption({ label: 'Option 2', value: 'opt-2' }),
]
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId="non-existent"
@@ -919,7 +761,6 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert - No option should have selected styles
const 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', () => {
- // Arrange
mockDatasourceOptions = [createDataSourceOption()]
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -938,17 +777,12 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
expect(container.querySelector('.grid')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // User Interaction Tests
- // -------------------------------------------------------------------------
describe('User Interactions', () => {
it('should call onSelect with datasource when option is clicked', () => {
- // Arrange
const 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 mount
render(
<DataSourceOptions
dataSourceNodeId="test-id"
@@ -968,7 +801,6 @@ describe('DataSourceOptions', () => {
)
fireEvent.click(screen.getByText('Test Option'))
- // Assert
expect(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', () => {
- // Arrange
const 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 mount
render(
<DataSourceOptions
dataSourceNodeId="id-1"
@@ -996,18 +826,15 @@ describe('DataSourceOptions', () => {
fireEvent.click(screen.getByText('Option 1'))
fireEvent.click(screen.getByText('Option 2'))
- // Assert
expect(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 handleSelect
const onSelect = vi.fn()
mockDatasourceOptions = []
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1015,19 +842,16 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert - Since there are no options, onSelect should not be called
expect(onSelect).not.toHaveBeenCalled()
})
it('should handle clicking same option multiple times', () => {
- // Arrange
const onSelect = vi.fn()
const optionData = createNodeData()
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option', value: 'opt-id', data: optionData }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId="opt-id"
@@ -1038,17 +862,12 @@ describe('DataSourceOptions', () => {
fireEvent.click(screen.getByText('Option'))
fireEvent.click(screen.getByText('Option'))
- // Assert
expect(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 () => {
- // Arrange
const onSelect = vi.fn()
const firstOptionData = createNodeData({ title: 'First' })
mockDatasourceOptions = [
@@ -1056,7 +875,6 @@ describe('DataSourceOptions', () => {
createDataSourceOption({ label: 'Second', value: 'second-id' }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1064,7 +882,6 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert - First option should be auto-selected on mount
await waitFor(() => {
expect(onSelect).toHaveBeenCalledWith({
nodeId: 'first-id',
@@ -1074,14 +891,12 @@ describe('DataSourceOptions', () => {
})
it('should not auto-select when dataSourceNodeId is provided', async () => {
- // Arrange
const onSelect = vi.fn()
mockDatasourceOptions = [
createDataSourceOption({ label: 'First', value: 'first-id' }),
createDataSourceOption({ label: 'Second', value: 'second-id' }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId="second-id"
@@ -1089,18 +904,15 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert - onSelect should not be called since dataSourceNodeId is already set
await waitFor(() => {
expect(onSelect).not.toHaveBeenCalled()
})
})
it('should not auto-select when options array is empty', async () => {
- // Arrange
const onSelect = vi.fn()
mockDatasourceOptions = []
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1108,20 +920,17 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
await waitFor(() => {
expect(onSelect).not.toHaveBeenCalled()
})
})
it('should run effect only once on mount', async () => {
- // Arrange
const onSelect = vi.fn()
mockDatasourceOptions = [
createDataSourceOption({ label: 'First', value: 'first-id' }),
]
- // Act
const { rerender } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1129,7 +938,6 @@ describe('DataSourceOptions', () => {
/>,
)
- // Rerender multiple times
rerender(
<DataSourceOptions
dataSourceNodeId=""
@@ -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 () => {
- // Arrange
const onSelect1 = vi.fn()
const onSelect2 = vi.fn()
mockDatasourceOptions = [
createDataSourceOption({ label: 'First', value: 'first-id' }),
]
- // Act
const { rerender } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1176,18 +981,15 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert - onSelect2 should not be called from effect
expect(onSelect2).not.toHaveBeenCalled()
})
it('should handle unmount cleanly', () => {
- // Arrange
const onSelect = vi.fn()
mockDatasourceOptions = [
createDataSourceOption({ label: 'Test', value: 'test-id' }),
]
- // Act
const { unmount } = render(
<DataSourceOptions
dataSourceNodeId="test-id"
@@ -1195,24 +997,18 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert - Should unmount without errors
expect(() => unmount()).not.toThrow()
})
})
- // -------------------------------------------------------------------------
- // Callback Stability Tests
- // -------------------------------------------------------------------------
describe('Callback Stability', () => {
it('should maintain stable handleSelect callback', () => {
- // Arrange
const onSelect = vi.fn()
const optionData = createNodeData()
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option', value: 'opt-id', data: optionData }),
]
- // Act
const { rerender } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1229,19 +1025,16 @@ describe('DataSourceOptions', () => {
)
fireEvent.click(screen.getByText('Option'))
- // Assert
expect(onSelect).toHaveBeenCalledTimes(3) // 1 auto-select + 2 clicks
})
it('should update handleSelect when onSelect prop changes', () => {
- // Arrange
const onSelect1 = vi.fn()
const onSelect2 = vi.fn()
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option', value: 'opt-id' }),
]
- // Act
const { rerender } = render(
<DataSourceOptions
dataSourceNodeId="opt-id"
@@ -1258,13 +1051,11 @@ describe('DataSourceOptions', () => {
)
fireEvent.click(screen.getByText('Option'))
- // Assert
expect(onSelect1).toHaveBeenCalledTimes(1)
expect(onSelect2).toHaveBeenCalledTimes(1)
})
it('should update handleSelect when options change', () => {
- // Arrange
const 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 }),
]
- // Act
const { rerender } = render(
<DataSourceOptions
dataSourceNodeId="opt-id"
@@ -1281,7 +1071,6 @@ describe('DataSourceOptions', () => {
)
fireEvent.click(screen.getByText('Option'))
- // Update options with different data
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option', value: 'opt-id', data: data2 }),
]
@@ -1293,24 +1082,18 @@ describe('DataSourceOptions', () => {
)
fireEvent.click(screen.getByText('Option'))
- // Assert
expect(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', () => {
- // Arrange
const onSelect = vi.fn()
mockDatasourceOptions = [
createDataSourceOption({ label: 'Only Option', value: 'only-id' }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId="only-id"
@@ -1318,16 +1101,13 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
expect(screen.getByText('Only Option')).toBeInTheDocument()
})
it('should handle many options', () => {
- // Arrange
mockDatasourceOptions = Array.from({ length: 20 }, (_, i) =>
createDataSourceOption({ label: `Option ${i}`, value: `opt-${i}` }))
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1335,13 +1115,11 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
expect(screen.getByText('Option 0')).toBeInTheDocument()
expect(screen.getByText('Option 19')).toBeInTheDocument()
})
it('should handle options with duplicate labels but different values', () => {
- // Arrange
const 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 }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1360,12 +1137,10 @@ describe('DataSourceOptions', () => {
const labels = screen.getAllByText('Same Label')
fireEvent.click(labels[1]) // Click second one
- // Assert
expect(onSelect).toHaveBeenLastCalledWith({ nodeId: 'id-2', nodeData: data2 })
})
it('should handle special characters in option values', () => {
- // Arrange
const onSelect = vi.fn()
const specialData = createNodeData()
mockDatasourceOptions = [
@@ -1376,7 +1151,6 @@ describe('DataSourceOptions', () => {
}),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1385,7 +1159,6 @@ describe('DataSourceOptions', () => {
)
fireEvent.click(screen.getByText('Special'))
- // Assert
expect(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 options
const onSelect = vi.fn()
mockDatasourceOptions = []
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1407,19 +1176,16 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert - No options to click, but component should render
expect(container.querySelector('.grid')).toBeInTheDocument()
})
it('should handle options with empty string values', () => {
- // Arrange
const onSelect = vi.fn()
const emptyValueData = createNodeData()
mockDatasourceOptions = [
createDataSourceOption({ label: 'Empty Value', value: '', data: emptyValueData }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1428,7 +1194,6 @@ describe('DataSourceOptions', () => {
)
fireEvent.click(screen.getByText('Empty Value'))
- // Assert - Should call onSelect with empty string nodeId
expect(onSelect).toHaveBeenCalledWith({
nodeId: '',
nodeData: emptyValueData,
@@ -1436,12 +1201,10 @@ describe('DataSourceOptions', () => {
})
it('should handle options with whitespace-only labels', () => {
- // Arrange
mockDatasourceOptions = [
createDataSourceOption({ label: ' ', value: 'whitespace' }),
]
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId="whitespace"
@@ -1449,25 +1212,19 @@ describe('DataSourceOptions', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const onSelect = vi.fn()
const weirdNodeData = { unexpected: 'data' } as unknown as DataSourceNodeType
mockDatasourceOptions = [
createDataSourceOption({ label: 'Weird', value: 'weird-id', data: weirdNodeData }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId="weird-id"
@@ -1476,7 +1233,6 @@ describe('DataSourceOptions', () => {
)
fireEvent.click(screen.getByText('Weird'))
- // Assert
expect(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 () => {
- // Arrange
const 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 }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1517,20 +1264,16 @@ describe('DataSourceOptions Integration', () => {
/>,
)
- // Assert - Auto-select first option on mount
await waitFor(() => {
expect(onSelect).toHaveBeenCalledWith({ nodeId: 'id-1', nodeData: data1 })
})
- // Act - Manual select second option
fireEvent.click(screen.getByText('Option 2'))
- // Assert
expect(onSelect).toHaveBeenLastCalledWith({ nodeId: 'id-2', nodeData: data2 })
})
it('should update selection state when clicking different options', () => {
- // Arrange
const 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 selected
const { rerender, container } = render(
<DataSourceOptions
dataSourceNodeId="b"
@@ -1546,11 +1288,9 @@ describe('DataSourceOptions Integration', () => {
/>,
)
- // Assert - Option B should be selected
let cards = container.querySelectorAll('.flex.cursor-pointer')
expect(cards[1].className).toContain('border-components-option-card-option-selected-border')
- // Act - Simulate selection change to Option C
rerender(
<DataSourceOptions
dataSourceNodeId="c"
@@ -1558,14 +1298,12 @@ describe('DataSourceOptions Integration', () => {
/>,
)
- // Assert - Option C should now be selected
cards = 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 () => {
- // Arrange
const onSelect = vi.fn()
mockDatasourceOptions = [
createDataSourceOption({ label: 'A', value: 'a' }),
@@ -1573,7 +1311,6 @@ describe('DataSourceOptions Integration', () => {
createDataSourceOption({ label: 'C', value: 'c' }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId="a"
@@ -1586,17 +1323,12 @@ describe('DataSourceOptions Integration', () => {
fireEvent.click(screen.getByText('A'))
fireEvent.click(screen.getByText('B'))
- // Assert
expect(onSelect).toHaveBeenCalledTimes(4)
})
})
- // -------------------------------------------------------------------------
- // Component Communication Tests
- // -------------------------------------------------------------------------
describe('Component Communication', () => {
it('should pass correct props from DataSourceOptions to OptionCard', () => {
- // Arrange
mockDatasourceOptions = [
createDataSourceOption({
label: 'Test Label',
@@ -1605,7 +1337,6 @@ describe('DataSourceOptions Integration', () => {
}),
]
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId="test-value"
@@ -1613,7 +1344,6 @@ describe('DataSourceOptions Integration', () => {
/>,
)
- // Assert - Verify OptionCard receives correct props through rendered output
expect(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', () => {
- // Arrange
const onSelect = vi.fn()
const nodeData = createNodeData()
mockDatasourceOptions = [
createDataSourceOption({ label: 'Click Me', value: 'click-id', data: nodeData }),
]
- // Act
render(
<DataSourceOptions
dataSourceNodeId="click-id"
@@ -1637,7 +1365,6 @@ describe('DataSourceOptions Integration', () => {
)
fireEvent.click(screen.getByText('Click Me'))
- // Assert
expect(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', () => {
- // Arrange
const onSelect = vi.fn()
mockDatasourceOptions = [
createDataSourceOption({ label: 'A', value: 'a' }),
createDataSourceOption({ label: 'B', value: 'b' }),
]
- // Act
const { rerender, container } = render(
<DataSourceOptions
dataSourceNodeId="a"
@@ -1665,7 +1387,6 @@ describe('DataSourceOptions Integration', () => {
/>,
)
- // Multiple rerenders
for (let i = 0; i < 5; i++) {
rerender(
<DataSourceOptions
@@ -1675,14 +1396,12 @@ describe('DataSourceOptions Integration', () => {
)
}
- // Assert - Selection should remain consistent
const 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', () => {
- // Arrange
const onSelect = vi.fn()
const nodeData = createNodeData()
@@ -1690,7 +1409,6 @@ describe('DataSourceOptions Integration', () => {
createDataSourceOption({ label: 'Option', value: 'opt', data: nodeData }),
]
- // Act
const { rerender } = render(
<DataSourceOptions
dataSourceNodeId="opt"
@@ -1698,7 +1416,6 @@ describe('DataSourceOptions Integration', () => {
/>,
)
- // Create new array reference with same content
mockDatasourceOptions = [
createDataSourceOption({ label: 'Option', value: 'opt', data: nodeData }),
]
@@ -1712,7 +1429,6 @@ describe('DataSourceOptions Integration', () => {
fireEvent.click(screen.getByText('Option'))
- // Assert - Should still work correctly
expect(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 component
const { rerender } = render(
<DataSourceOptions
dataSourceNodeId="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 values
const 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 works
fireEvent.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 options
const onSelect = vi.fn()
mockDatasourceOptions = []
- // Act
const { container } = render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1793,13 +1490,11 @@ describe('handleSelect Early Return Coverage', () => {
/>,
)
- // Assert - No options to click, onSelect not called
expect(container.querySelector('.grid')).toBeInTheDocument()
expect(onSelect).not.toHaveBeenCalled()
})
it('should handle auto-select with mismatched first option', async () => {
- // Arrange - Test auto-select behavior
const onSelect = vi.fn()
const firstOptionData = createNodeData({ title: 'First' })
mockDatasourceOptions = [
@@ -1810,7 +1505,6 @@ describe('handleSelect Early Return Coverage', () => {
}),
]
- // Act - Empty dataSourceNodeId triggers auto-select
render(
<DataSourceOptions
dataSourceNodeId=""
@@ -1818,7 +1512,6 @@ describe('handleSelect Early Return Coverage', () => {
/>,
)
- // Assert - First option auto-selected
await 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.tsx
similarity index 85%
rename from web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsx
index 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 store
let mockPipelineId: string | null = 'test-pipeline-id'
let mockWorkflowRunningData: { result: { status: string } } | undefined
@@ -35,7 +30,6 @@ vi.mock('@/app/components/workflow/store', () => ({
},
}))
-// Mock useDraftPipelineProcessingParams
let mockParamsConfig: PipelineProcessingParamsResponse | undefined
let mockIsFetchingParams = false
@@ -46,7 +40,6 @@ vi.mock('@/service/use-pipeline', () => ({
}),
}))
-// Mock use-input-fields hooks
const 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 generateZodSchema
const mockGenerateZodSchema = vi.fn()
vi.mock('@/app/components/base/form/form-scenarios/base/utils', () => ({
generateZodSchema: (configurations: BaseConfiguration[]) => mockGenerateZodSchema(configurations),
}))
-// Mock Toast
const mockToastNotify = vi.fn()
vi.mock('@/app/components/base/toast', () => ({
@@ -71,7 +62,6 @@ vi.mock('@/app/components/base/toast', () => ({
},
}))
-// Mock useAppForm
const mockHandleSubmit = vi.fn()
const mockFormStore = {
isSubmitting: false,
@@ -112,7 +102,6 @@ vi.mock('@/app/components/base/form', () => ({
},
}))
-// Mock BaseField
vi.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 | null
paramsConfig?: 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', () => {
- // Arrange
setupMocks({
configurations: [createBaseConfiguration()],
})
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
it('should render Options component with form elements', () => {
- // Arrange
const configurations = [
createBaseConfiguration({ variable: 'field1', label: 'Field 1' }),
createBaseConfiguration({ variable: 'field2', label: 'Field 2' }),
]
setupMocks({ configurations })
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(screen.getByTestId('field-field1')).toBeInTheDocument()
expect(screen.getByTestId('field-field2')).toBeInTheDocument()
})
it('should render no fields when configurations is empty', () => {
- // Arrange
setupMocks({ configurations: [] })
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()
})
it('should call useInitialData with variables from paramsConfig', () => {
- // Arrange
const variables = [createRAGPipelineVariable({ variable: 'var1' })]
setupMocks({
paramsConfig: { variables },
})
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(mockUseInitialData).toHaveBeenCalledWith(variables)
})
it('should call useConfigurations with variables from paramsConfig', () => {
- // Arrange
const variables = [createRAGPipelineVariable({ variable: 'var1' })]
setupMocks({
paramsConfig: { variables },
})
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(mockUseConfigurations).toHaveBeenCalledWith(variables)
})
it('should use empty array when paramsConfig.variables is undefined', () => {
- // Arrange
setupMocks({ paramsConfig: undefined })
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(mockUseInitialData).toHaveBeenCalledWith([])
expect(mockUseConfigurations).toHaveBeenCalledWith([])
})
})
- // -------------------------------------------------------------------------
- // Props Testing
- // -------------------------------------------------------------------------
describe('Props Testing', () => {
it('should pass dataSourceNodeId to useInputVariables hook', () => {
- // Arrange
const customNodeId = 'custom-datasource-node'
setupMocks()
- // Act
renderWithQueryClient(
<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', () => {
- // Arrange
const mockOnProcess = vi.fn()
setupMocks({ configurations: [] })
- // Act
const { container } = renderWithQueryClient(
<DocumentProcessing
{...defaultProps}
@@ -336,16 +284,13 @@ describe('DocumentProcessing', () => {
/>,
)
- // Assert - form should be rendered
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should pass onBack callback to Actions component', () => {
- // Arrange
const mockOnBack = vi.fn()
setupMocks()
- // Act
renderWithQueryClient(
<DocumentProcessing
{...defaultProps}
@@ -353,37 +298,28 @@ describe('DocumentProcessing', () => {
/>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Callback Stability and Memoization Tests
- // -------------------------------------------------------------------------
describe('Callback Stability and Memoization', () => {
it('should memoize renderCustomActions callback', () => {
- // Arrange
setupMocks()
const { rerender } = renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Act - rerender with same props
rerender(
<QueryClientProvider client={createQueryClient()}>
<DocumentProcessing {...defaultProps} />
</QueryClientProvider>,
)
- // Assert - component should render correctly without issues
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
it('should update renderCustomActions when isFetchingParams changes', () => {
- // Arrange
setupMocks({ isFetchingParams: false })
const { rerender } = renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Act
setupMocks({ isFetchingParams: true })
rerender(
<QueryClientProvider client={createQueryClient()}>
@@ -391,12 +327,10 @@ describe('DocumentProcessing', () => {
</QueryClientProvider>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
it('should update renderCustomActions when onBack changes', () => {
- // Arrange
const onBack1 = vi.fn()
const onBack2 = vi.fn()
setupMocks()
@@ -404,28 +338,21 @@ describe('DocumentProcessing', () => {
<DocumentProcessing {...defaultProps} onBack={onBack1} />,
)
- // Act
rerender(
<QueryClientProvider client={createQueryClient()}>
<DocumentProcessing {...defaultProps} onBack={onBack2} />
</QueryClientProvider>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // User Interactions Tests
- // -------------------------------------------------------------------------
describe('User Interactions', () => {
it('should call onBack when back button is clicked', () => {
- // Arrange
const mockOnBack = vi.fn()
setupMocks()
- // Act
renderWithQueryClient(
<DocumentProcessing
{...defaultProps}
@@ -435,16 +362,13 @@ describe('DocumentProcessing', () => {
const backButton = screen.getByText('datasetPipeline.operations.backToDataSource')
fireEvent.click(backButton)
- // Assert
expect(mockOnBack).toHaveBeenCalledTimes(1)
})
it('should handle form submission', () => {
- // Arrange
const mockOnProcess = vi.fn()
setupMocks()
- // Act
renderWithQueryClient(
<DocumentProcessing
{...defaultProps}
@@ -454,33 +378,25 @@ describe('DocumentProcessing', () => {
const processButton = screen.getByText('datasetPipeline.operations.process')
fireEvent.click(processButton)
- // Assert
expect(mockHandleSubmit).toHaveBeenCalled()
})
})
- // -------------------------------------------------------------------------
- // Component Memoization Tests
- // -------------------------------------------------------------------------
describe('Component Memoization', () => {
it('should be wrapped with React.memo', () => {
- // Arrange
setupMocks()
const { rerender } = renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Act - rerender with same props
rerender(
<QueryClientProvider client={createQueryClient()}>
<DocumentProcessing {...defaultProps} />
</QueryClientProvider>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
it('should not break when re-rendering with different props', () => {
- // Arrange
const initialProps = {
...defaultProps,
dataSourceNodeId: 'node-1',
@@ -488,7 +404,6 @@ describe('DocumentProcessing', () => {
setupMocks()
const { rerender } = renderWithQueryClient(<DocumentProcessing {...initialProps} />)
- // Act
const newProps = {
...defaultProps,
dataSourceNodeId: 'node-2',
@@ -499,52 +414,38 @@ describe('DocumentProcessing', () => {
</QueryClientProvider>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle undefined paramsConfig', () => {
- // Arrange
setupMocks({ paramsConfig: undefined })
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(mockUseInitialData).toHaveBeenCalledWith([])
expect(mockUseConfigurations).toHaveBeenCalledWith([])
})
it('should handle paramsConfig with empty variables', () => {
- // Arrange
setupMocks({ paramsConfig: { variables: [] } })
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(mockUseInitialData).toHaveBeenCalledWith([])
expect(mockUseConfigurations).toHaveBeenCalledWith([])
})
it('should handle null pipelineId', () => {
- // Arrange
setupMocks({ pipelineId: null })
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
it('should handle large number of variables', () => {
- // Arrange
const variables = Array.from({ length: 50 }, (_, i) =>
createRAGPipelineVariable({ variable: `var_${i}` }))
const configurations = Array.from({ length: 50 }, (_, i) =>
@@ -554,18 +455,14 @@ describe('DocumentProcessing', () => {
configurations,
})
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
expect(screen.getAllByTestId(/^field-var_/)).toHaveLength(50)
})
it('should handle special characters in node id', () => {
- // Arrange
setupMocks()
- // Act
renderWithQueryClient(
<DocumentProcessing
{...defaultProps}
@@ -573,46 +470,31 @@ describe('DocumentProcessing', () => {
/>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Loading State Tests
- // -------------------------------------------------------------------------
describe('Loading State', () => {
it('should pass isFetchingParams to Actions component', () => {
- // Arrange
setupMocks({ isFetchingParams: true })
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert - check that the process button is disabled when fetching
const processButton = screen.getByText('datasetPipeline.operations.process')
expect(processButton.closest('button')).toBeDisabled()
})
it('should enable process button when not fetching', () => {
- // Arrange
setupMocks({ isFetchingParams: false })
- // Act
renderWithQueryClient(<DocumentProcessing {...defaultProps} />)
- // Assert
const processButton = screen.getByText('datasetPipeline.operations.process')
expect(processButton.closest('button')).not.toBeDisabled()
})
})
})
-// ============================================================================
-// Actions Component Tests
-// ============================================================================
-
-// Helper to create mock form params for Actions tests
const createMockFormParams = (overrides?: Partial<{
handleSubmit: ReturnType<typeof vi.fn>
isSubmitting: boolean
@@ -631,10 +513,8 @@ describe('Actions', () => {
describe('Rendering', () => {
it('should render back button', () => {
- // Arrange
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -642,15 +522,12 @@ describe('Actions', () => {
/>,
)
- // Assert
expect(screen.getByText('datasetPipeline.operations.backToDataSource')).toBeInTheDocument()
})
it('should render process button', () => {
- // Arrange
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -658,17 +535,14 @@ describe('Actions', () => {
/>,
)
- // Assert
expect(screen.getByText('datasetPipeline.operations.process')).toBeInTheDocument()
})
})
describe('Button States', () => {
it('should disable process button when runDisabled is true', () => {
- // Arrange
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -677,16 +551,13 @@ describe('Actions', () => {
/>,
)
- // Assert
const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')
expect(processButton).toBeDisabled()
})
it('should disable process button when isSubmitting is true', () => {
- // Arrange
const mockFormParams = createMockFormParams({ isSubmitting: true })
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -694,16 +565,13 @@ describe('Actions', () => {
/>,
)
- // Assert
const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')
expect(processButton).toBeDisabled()
})
it('should disable process button when canSubmit is false', () => {
- // Arrange
const mockFormParams = createMockFormParams({ canSubmit: false })
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -711,19 +579,16 @@ describe('Actions', () => {
/>,
)
- // Assert
const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')
expect(processButton).toBeDisabled()
})
it('should disable process button when workflow is running', () => {
- // Arrange
mockWorkflowRunningData = {
result: { status: WorkflowRunningStatus.Running },
}
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -731,19 +596,16 @@ describe('Actions', () => {
/>,
)
- // Assert
const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')
expect(processButton).toBeDisabled()
})
it('should enable process button when all conditions are met', () => {
- // Arrange
mockWorkflowRunningData = {
result: { status: WorkflowRunningStatus.Succeeded },
}
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -752,7 +614,6 @@ describe('Actions', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockOnBack = vi.fn()
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -774,16 +633,13 @@ describe('Actions', () => {
fireEvent.click(screen.getByText('datasetPipeline.operations.backToDataSource'))
- // Assert
expect(mockOnBack).toHaveBeenCalledTimes(1)
})
it('should call form.handleSubmit when process button is clicked', () => {
- // Arrange
const mockSubmit = vi.fn()
const mockFormParams = createMockFormParams({ handleSubmit: mockSubmit })
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -793,17 +649,14 @@ describe('Actions', () => {
fireEvent.click(screen.getByText('datasetPipeline.operations.process'))
- // Assert
expect(mockSubmit).toHaveBeenCalledTimes(1)
})
})
describe('Loading State', () => {
it('should show loading state when isSubmitting', () => {
- // Arrange
const mockFormParams = createMockFormParams({ isSubmitting: true })
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -811,19 +664,16 @@ describe('Actions', () => {
/>,
)
- // Assert
const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')
expect(processButton).toBeDisabled()
})
it('should show loading state when workflow is running', () => {
- // Arrange
mockWorkflowRunningData = {
result: { status: WorkflowRunningStatus.Running },
}
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -831,7 +681,6 @@ describe('Actions', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -850,17 +697,14 @@ describe('Actions', () => {
/>,
)
- // Assert
const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')
expect(processButton).not.toBeDisabled()
})
it('should handle undefined workflowRunningData', () => {
- // Arrange
mockWorkflowRunningData = undefined
const mockFormParams = createMockFormParams()
- // Act
render(
<Actions
formParams={mockFormParams}
@@ -868,7 +712,6 @@ describe('Actions', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockFormParams = createMockFormParams()
const mockOnBack = vi.fn()
const { rerender } = render(
@@ -886,7 +728,6 @@ describe('Actions', () => {
/>,
)
- // Act - rerender with same props
rerender(
<Actions
formParams={mockFormParams}
@@ -894,16 +735,11 @@ describe('Actions', () => {
/>,
)
- // Assert
expect(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', () => {
- // Arrange
const props = {
initialData: {},
configurations: [],
@@ -921,15 +756,12 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
const { container } = render(<Options {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should render fields based on configurations', () => {
- // Arrange
const configurations = [
createBaseConfiguration({ variable: 'name', label: 'Name' }),
createBaseConfiguration({ variable: 'email', label: 'Email' }),
@@ -942,16 +774,13 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
render(<Options {...props} />)
- // Assert
expect(screen.getByTestId('field-name')).toBeInTheDocument()
expect(screen.getByTestId('field-email')).toBeInTheDocument()
})
it('should render CustomActions', () => {
- // Arrange
const props = {
initialData: {},
configurations: [],
@@ -962,15 +791,12 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
render(<Options {...props} />)
- // Assert
expect(screen.getByTestId('custom-action')).toBeInTheDocument()
})
it('should render with correct class name', () => {
- // Arrange
const props = {
initialData: {},
configurations: [],
@@ -979,10 +805,8 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
const { container } = render(<Options {...props} />)
- // Assert
const form = container.querySelector('form')
expect(form).toHaveClass('w-full')
})
@@ -990,7 +814,6 @@ describe('Options', () => {
describe('Form Submission', () => {
it('should prevent default form submission', () => {
- // Arrange
const mockOnSubmit = vi.fn()
const props = {
initialData: {},
@@ -1000,7 +823,6 @@ describe('Options', () => {
onSubmit: mockOnSubmit,
}
- // Act
const { 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)
- // Assert
expect(preventDefaultSpy).toHaveBeenCalled()
})
it('should stop propagation on form submit', () => {
- // Arrange
const mockOnSubmit = vi.fn()
const props = {
initialData: {},
@@ -1023,7 +843,6 @@ describe('Options', () => {
onSubmit: mockOnSubmit,
}
- // Act
const { 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)
- // Assert
expect(stopPropagationSpy).toHaveBeenCalled()
})
it('should call onSubmit when validation passes', () => {
- // Arrange
const mockOnSubmit = vi.fn()
const props = {
initialData: {},
@@ -1046,17 +863,14 @@ describe('Options', () => {
onSubmit: mockOnSubmit,
}
- // Act
const { container } = render(<Options {...props} />)
const form = container.querySelector('form')!
fireEvent.submit(form)
- // Assert
expect(mockOnSubmit).toHaveBeenCalled()
})
it('should not call onSubmit when validation fails', () => {
- // Arrange
const mockOnSubmit = vi.fn()
const failingSchema = {
safeParse: vi.fn().mockReturnValue({
@@ -1076,17 +890,14 @@ describe('Options', () => {
onSubmit: mockOnSubmit,
}
- // Act
const { container } = render(<Options {...props} />)
const form = container.querySelector('form')!
fireEvent.submit(form)
- // Assert
expect(mockOnSubmit).not.toHaveBeenCalled()
})
it('should show toast error when validation fails', () => {
- // Arrange
const failingSchema = {
safeParse: vi.fn().mockReturnValue({
success: false,
@@ -1105,12 +916,10 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
const { container } = render(<Options {...props} />)
const form = container.querySelector('form')!
fireEvent.submit(form)
- // Assert
expect(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', () => {
- // Arrange
const failingSchema = {
safeParse: vi.fn().mockReturnValue({
success: false,
@@ -1137,12 +945,10 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
const { container } = render(<Options {...props} />)
const form = container.querySelector('form')!
fireEvent.submit(form)
- // Assert
expect(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', () => {
- // Arrange
const failingSchema = {
safeParse: vi.fn().mockReturnValue({
success: false,
@@ -1171,12 +976,10 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
const { container } = render(<Options {...props} />)
const form = container.querySelector('form')!
fireEvent.submit(form)
- // Assert - should only show first error
expect(mockToastNotify).toHaveBeenCalledTimes(1)
expect(mockToastNotify).toHaveBeenCalledWith({
type: 'error',
@@ -1185,7 +988,6 @@ describe('Options', () => {
})
it('should handle empty path in validation error', () => {
- // Arrange
const failingSchema = {
safeParse: vi.fn().mockReturnValue({
success: false,
@@ -1204,12 +1006,10 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
const { container } = render(<Options {...props} />)
const form = container.querySelector('form')!
fireEvent.submit(form)
- // Assert
expect(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', () => {
- // Arrange
const configurations = [
createBaseConfiguration({ variable: 'first', label: 'First' }),
createBaseConfiguration({ variable: 'second', label: 'Second' }),
@@ -1233,22 +1032,18 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
render(<Options {...props} />)
- // Assert - check that each field container exists with correct order
expect(screen.getByTestId('field-first')).toBeInTheDocument()
expect(screen.getByTestId('field-second')).toBeInTheDocument()
expect(screen.getByTestId('field-third')).toBeInTheDocument()
- // Verify order by checking labels within each field
expect(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', () => {
- // Arrange
const configurations = [
createBaseConfiguration({
variable: 'test',
@@ -1265,10 +1060,8 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
render(<Options {...props} />)
- // Assert
expect(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', () => {
- // Arrange
const props = {
initialData: {},
configurations: [createBaseConfiguration()],
@@ -1286,15 +1078,12 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
const { container } = render(<Options {...props} />)
- // Assert
expect(container.querySelector('form')).toBeInTheDocument()
})
it('should handle empty configurations', () => {
- // Arrange
const props = {
initialData: {},
configurations: [],
@@ -1303,15 +1092,12 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
render(<Options {...props} />)
- // Assert
expect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()
})
it('should handle configurations with all field types', () => {
- // Arrange
const configurations = [
createBaseConfiguration({ type: BaseFieldType.textInput, variable: 'text' }),
createBaseConfiguration({ type: BaseFieldType.paragraph, variable: 'paragraph' }),
@@ -1333,10 +1119,8 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
render(<Options {...props} />)
- // Assert
expect(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', () => {
- // Arrange
const configurations = Array.from({ length: 20 }, (_, i) =>
createBaseConfiguration({ variable: `field_${i}`, label: `Field ${i}` }))
const props = {
@@ -1356,21 +1139,14 @@ describe('Options', () => {
onSubmit: vi.fn(),
}
- // Act
render(<Options {...props} />)
- // Assert
expect(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 here
beforeEach(() => {
@@ -1382,10 +1158,8 @@ describe('useInputVariables Hook', () => {
describe('Return Values', () => {
it('should return isFetchingParams state', () => {
- // Arrange
setupMocks({ isFetchingParams: true })
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1395,17 +1169,14 @@ describe('useInputVariables Hook', () => {
/>,
)
- // Assert - verified by checking process button is disabled
const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')
expect(processButton).toBeDisabled()
})
it('should return paramsConfig when data is loaded', () => {
- // Arrange
const variables = [createRAGPipelineVariable()]
setupMocks({ paramsConfig: { variables } })
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1415,18 +1186,15 @@ describe('useInputVariables Hook', () => {
/>,
)
- // Assert
expect(mockUseInitialData).toHaveBeenCalledWith(variables)
})
})
describe('Query Behavior', () => {
it('should use pipelineId from store', () => {
- // Arrange
mockPipelineId = 'custom-pipeline-id'
setupMocks()
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1436,16 +1204,13 @@ describe('useInputVariables Hook', () => {
/>,
)
- // Assert - component renders successfully with the pipelineId
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
it('should handle null pipelineId gracefully', () => {
- // Arrange
mockPipelineId = null
setupMocks({ pipelineId: null })
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1455,16 +1220,11 @@ describe('useInputVariables Hook', () => {
/>,
)
- // Assert
expect(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', () => {
- // Arrange
const variables = [
createRAGPipelineVariable({ variable: 'input1', label: 'Input 1' }),
createRAGPipelineVariable({ variable: 'input2', label: 'Input 2' }),
@@ -1488,7 +1247,6 @@ describe('DocumentProcessing Integration', () => {
initialData: { input1: '', input2: '' },
})
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1498,7 +1256,6 @@ describe('DocumentProcessing Integration', () => {
/>,
)
- // Assert
expect(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', () => {
- // Arrange
const mockOnProcess = vi.fn()
const mockOnBack = vi.fn()
setupMocks()
- // Act
renderWithQueryClient(
<DocumentProcessing
dataSourceNodeId="test-node"
@@ -1520,22 +1275,18 @@ describe('DocumentProcessing Integration', () => {
/>,
)
- // Click back button
fireEvent.click(screen.getByText('datasetPipeline.operations.backToDataSource'))
- // Assert
expect(mockOnBack).toHaveBeenCalled()
})
})
describe('State Synchronization', () => {
it('should update when workflow running status changes', () => {
- // Arrange
setupMocks({
workflowRunningData: { result: { status: WorkflowRunningStatus.Running } },
})
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1545,16 +1296,13 @@ describe('DocumentProcessing Integration', () => {
/>,
)
- // Assert
const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')
expect(processButton).toBeDisabled()
})
it('should update when fetching params status changes', () => {
- // Arrange
setupMocks({ isFetchingParams: true })
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1564,17 +1312,12 @@ describe('DocumentProcessing Integration', () => {
/>,
)
- // Assert
const 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) => {
- // Act
renderWithQueryClient(
<DocumentProcessing
dataSourceNodeId={nodeId}
@@ -1598,18 +1340,15 @@ describe('Prop Variations', () => {
/>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
})
describe('Callback Variations', () => {
it('should work with synchronous onProcess', () => {
- // Arrange
const syncCallback = vi.fn()
setupMocks()
- // Act
renderWithQueryClient(
<DocumentProcessing
dataSourceNodeId="test-node"
@@ -1618,16 +1357,13 @@ describe('Prop Variations', () => {
/>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
it('should work with async onProcess', () => {
- // Arrange
const asyncCallback = vi.fn().mockResolvedValue(undefined)
setupMocks()
- // Act
renderWithQueryClient(
<DocumentProcessing
dataSourceNodeId="test-node"
@@ -1636,20 +1372,17 @@ describe('Prop Variations', () => {
/>,
)
- // Assert
expect(screen.getByTestId('form-actions')).toBeInTheDocument()
})
})
describe('Configuration Variations', () => {
it('should handle required fields', () => {
- // Arrange
const configurations = [
createBaseConfiguration({ variable: 'required', required: true }),
]
setupMocks({ configurations })
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1659,18 +1392,15 @@ describe('Prop Variations', () => {
/>,
)
- // Assert
expect(screen.getByTestId('field-required-required')).toHaveTextContent('true')
})
it('should handle optional fields', () => {
- // Arrange
const configurations = [
createBaseConfiguration({ variable: 'optional', required: false }),
]
setupMocks({ configurations })
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1680,12 +1410,10 @@ describe('Prop Variations', () => {
/>,
)
- // Assert
expect(screen.getByTestId('field-required-optional')).toHaveTextContent('false')
})
it('should handle mixed required and optional fields', () => {
- // Arrange
const configurations = [
createBaseConfiguration({ variable: 'required1', required: true }),
createBaseConfiguration({ variable: 'optional1', required: false }),
@@ -1693,7 +1421,6 @@ describe('Prop Variations', () => {
]
setupMocks({ configurations })
- // Act
renderWithQueryClient(
<DocumentProcessing {...{
dataSourceNodeId: 'test-node',
@@ -1703,7 +1430,6 @@ describe('Prop Variations', () => {
/>,
)
- // Assert
expect(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.tsx
similarity index 81%
rename from web/app/components/rag-pipeline/components/panel/test-run/result/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/test-run/result/__tests__/index.spec.tsx
index 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 store
vi.mock('@/app/components/workflow/store', () => ({
useStore: <T,>(selector: (state: { workflowRunningData: WorkflowRunningData | undefined }) => T) =>
selector({ workflowRunningData: mockWorkflowRunningData }),
}))
-// Mock child components
vi.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 data
const { rerender } = render(
<Tab isActive={true} label="Tab" value="tab" workflowRunningData={workflowData} onClick={mockOnClick} />,
)
expect(screen.getByRole('button')).not.toBeDisabled()
- // Inactive with data
rerender(
<Tab isActive={false} label="Tab" value="tab" workflowRunningData={workflowData} onClick={mockOnClick} />,
)
expect(screen.getByRole('button')).not.toBeDisabled()
- // Active without data
rerender(
<Tab isActive={true} label="Tab" value="tab" workflowRunningData={undefined} onClick={mockOnClick} />,
)
expect(screen.getByRole('button')).toBeDisabled()
- // Inactive without data
rerender(
<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 tab
expect(buttons[0]).toHaveClass('border-transparent')
- // DETAIL tab (active)
expect(buttons[1]).toHaveClass('border-util-colors-blue-brand-blue-brand-600')
- // TRACING tab
expect(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 undefined
expect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()
})
@@ -907,14 +808,10 @@ describe('ResultPreview', () => {
/>,
)
- // Error section should not render when isRunning is true
expect(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 value
rerender(
<ResultPreview
isRunning={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 rendered
expect(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 DETAIL
fireEvent.click(screen.getByText('runLog.detail'))
await waitFor(() => {
expect(screen.getByTestId('result-panel')).toBeInTheDocument()
})
- // Switch back to RESULT
fireEvent.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 rendered
expect(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 state
fireEvent.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 = undefined
render(<Result />)
- // All tabs should be disabled
const 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 stopped
expect(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 tab
fireEvent.click(screen.getByText('runLog.detail'))
await waitFor(() => {
expect(screen.getByTestId('result-panel')).toBeInTheDocument()
})
- // Re-render component
rerender(<Result />)
- // Should still be on DETAIL tab
expect(screen.getByTestId('result-panel')).toBeInTheDocument()
})
it('should render different states based on workflowRunningData', () => {
- // Test 1: Running state with no outputs
mockWorkflowRunningData = createMockWorkflowRunningData({
result: {
...createMockWorkflowRunningData().result,
@@ -1265,7 +1124,6 @@ describe('Result', () => {
expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()
unmount()
- // Test 2: Completed state with outputs
const 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 changes
rerender(<Result />)
- // Component should still be rendered correctly
expect(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.tsx
similarity index 79%
rename from web/app/components/rag-pipeline/components/panel/test-run/result/result-preview/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/test-run/result/result-preview/__tests__/index.spec.tsx
index 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 config
vi.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 & Act
const result = formatPreviewChunks(undefined)
- // Assert
expect(result).toBeUndefined()
})
it('should return undefined when outputs is null', () => {
- // Arrange & Act
const result = formatPreviewChunks(null)
- // Assert
expect(result).toBeUndefined()
})
})
- // -------------------------------------------------------------------------
- // General Chunks (text_model) Tests
- // -------------------------------------------------------------------------
describe('General Chunks (text_model)', () => {
it('should format general chunks correctly', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([
{ content: 'First chunk content' },
{ content: 'Second chunk content' },
{ content: 'Third chunk content' },
])
- // Act
const result = formatPreviewChunks(outputs) as GeneralChunks
- // Assert
expect(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)', () => {
- // Arrange
const outputs = createGeneralChunkOutputs(createMockGeneralChunks(30))
- // Act
const result = formatPreviewChunks(outputs) as GeneralChunks
- // Assert
expect(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', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([])
- // Act
const result = formatPreviewChunks(outputs) as GeneralChunks
- // Assert
expect(result).toEqual([])
})
it('should handle general chunks with empty content', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([
{ content: '' },
{ content: 'Valid content' },
])
- // Act
const result = formatPreviewChunks(outputs) as GeneralChunks
- // Assert
expect(result).toEqual([
{ content: '', summary: undefined },
{ content: 'Valid content', summary: undefined },
@@ -193,17 +146,14 @@ describe('formatPreviewChunks', () => {
})
it('should handle general chunks with special characters', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([
{ content: '<script>alert("xss")</script>' },
{ content: '中文内容 🎉' },
{ content: 'Line1\nLine2\tTab' },
])
- // Act
const result = formatPreviewChunks(outputs) as GeneralChunks
- // Assert
expect(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', () => {
- // Arrange
const longContent = 'A'.repeat(10000)
const outputs = createGeneralChunkOutputs([{ content: longContent }])
- // Act
const result = formatPreviewChunks(outputs) as GeneralChunks
- // Assert
expect((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', () => {
- // Arrange
const outputs = createParentChildChunkOutputs([
{ content: 'Parent 1', child_chunks: ['Child 1-1', 'Child 1-2'] },
{ content: 'Parent 2', child_chunks: ['Child 2-1'] },
], 'paragraph')
- // Act
const result = formatPreviewChunks(outputs) as ParentChildChunks
- // Assert
expect(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', () => {
- // Arrange
const outputs = createParentChildChunkOutputs(createMockParentChildChunks(30, 2), 'paragraph')
- // Act
const result = formatPreviewChunks(outputs) as ParentChildChunks
- // Assert
expect(result.parent_child_chunks).toHaveLength(20)
})
it('should NOT limit child chunks in paragraph mode', () => {
- // Arrange
const outputs = createParentChildChunkOutputs([
{ content: 'Parent 1', child_chunks: Array.from({ length: 50 }, (_, i) => `Child ${i + 1}`) },
], 'paragraph')
- // Act
const result = formatPreviewChunks(outputs) as ParentChildChunks
- // Assert
expect(result.parent_child_chunks[0].child_contents).toHaveLength(50)
})
it('should handle empty child_chunks in paragraph mode', () => {
- // Arrange
const outputs = createParentChildChunkOutputs([
{ content: 'Parent with no children', child_chunks: [] },
], 'paragraph')
- // Act
const result = formatPreviewChunks(outputs) as ParentChildChunks
- // Assert
expect(result.parent_child_chunks[0].child_contents).toEqual([])
})
})
describe('Full-Doc Mode', () => {
it('should format parent-child chunks in full-doc mode correctly', () => {
- // Arrange
const outputs = createParentChildChunkOutputs([
{ content: 'Full Doc Parent', child_chunks: ['Child 1', 'Child 2', 'Child 3'] },
], 'full-doc')
- // Act
const result = formatPreviewChunks(outputs) as ParentChildChunks
- // Assert
expect(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', () => {
- // Arrange
const outputs = createParentChildChunkOutputs(createMockParentChildChunks(30, 2), 'full-doc')
- // Act
const 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', () => {
- // Arrange
const outputs = createParentChildChunkOutputs([
{ content: 'Parent', child_chunks: Array.from({ length: 50 }, (_, i) => `Child ${i + 1}`) },
], 'full-doc')
- // Act
const result = formatPreviewChunks(outputs) as ParentChildChunks
- // Assert
expect(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', () => {
- // Arrange
const 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')
- // Act
const result = formatPreviewChunks(outputs) as ParentChildChunks
- // Assert
expect(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', () => {
- // Arrange
const outputs = createParentChildChunkOutputs([], 'paragraph')
- // Act
const result = formatPreviewChunks(outputs) as ParentChildChunks
- // Assert
expect(result.parent_child_chunks).toEqual([])
})
})
- // -------------------------------------------------------------------------
- // QA Chunks (qa_model) Tests
- // -------------------------------------------------------------------------
describe('QA Chunks (qa_model)', () => {
it('should format QA chunks correctly', () => {
- // Arrange
const outputs = createQAChunkOutputs([
{ question: 'What is Dify?', answer: 'Dify is an LLM application platform.' },
{ question: 'How to use it?', answer: 'You can create apps easily.' },
])
- // Act
const result = formatPreviewChunks(outputs) as QAChunks
- // Assert
expect(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)', () => {
- // Arrange
const outputs = createQAChunkOutputs(createMockQAChunks(30))
- // Act
const result = formatPreviewChunks(outputs) as QAChunks
- // Assert
expect(result.qa_chunks).toHaveLength(20)
})
it('should handle empty qa_preview array', () => {
- // Arrange
const outputs = createQAChunkOutputs([])
- // Act
const result = formatPreviewChunks(outputs) as QAChunks
- // Assert
expect(result.qa_chunks).toEqual([])
})
it('should handle QA chunks with empty question or answer', () => {
- // Arrange
const outputs = createQAChunkOutputs([
{ question: '', answer: 'Answer without question' },
{ question: 'Question without answer', answer: '' },
])
- // Act
const result = formatPreviewChunks(outputs) as QAChunks
- // Assert
expect(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', () => {
- // Arrange
const outputs = {
chunk_structure: ChunkingMode.qa,
qa_preview: [
@@ -437,90 +338,63 @@ describe('formatPreviewChunks', () => {
] as unknown as Array<{ question: string, answer: string }>,
}
- // Act
const result = formatPreviewChunks(outputs) as QAChunks
- // Assert
expect(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', () => {
- // Arrange
const outputs = {
chunk_structure: 'unknown_mode' as ChunkingMode,
preview: [],
}
- // Act
const result = formatPreviewChunks(outputs)
- // Assert
expect(result).toBeUndefined()
})
it('should return undefined when chunk_structure is missing', () => {
- // Arrange
const outputs = {
preview: [{ content: 'test' }],
}
- // Act
const result = formatPreviewChunks(outputs)
- // Assert
expect(result).toBeUndefined()
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle exactly RAG_PIPELINE_PREVIEW_CHUNK_NUM (20) chunks', () => {
- // Arrange
const outputs = createGeneralChunkOutputs(createMockGeneralChunks(20))
- // Act
const result = formatPreviewChunks(outputs) as GeneralChunks
- // Assert
expect(result).toHaveLength(20)
})
it('should handle outputs with additional properties', () => {
- // Arrange
const outputs = {
...createGeneralChunkOutputs([{ content: 'Test' }]),
extra_field: 'should not affect result',
metadata: { some: 'data' },
}
- // Act
const result = formatPreviewChunks(outputs) as GeneralChunks
- // Assert
expect(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 & Act
render(<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 & Act
render(<ResultPreview {...defaultProps} isRunning={true} outputs={undefined} />)
- // Assert
expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()
})
it('should render loading spinner icon when loading', () => {
- // Arrange & Act
const { 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 & Act
render(<ResultPreview {...defaultProps} isRunning={false} error="Something went wrong" />)
- // Assert
expect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /pipeline\.result\.resultPreview\.viewDetails/i })).toBeInTheDocument()
})
it('should render outputs when available', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Test chunk' }])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()
})
it('should render footer tip when outputs available', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Test chunk' }])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
expect(screen.getByText(/pipeline\.result\.resultPreview\.footerTip/)).toBeInTheDocument()
})
it('should not render loading when outputs exist even if isRunning', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Test' }])
- // Act
render(<ResultPreview {...defaultProps} isRunning={true} outputs={outputs} />)
- // Assert - Should show outputs, not loading
expect(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 & Act
render(<ResultPreview {...defaultProps} isRunning={true} error="Error message" outputs={undefined} />)
- // Assert - Should show loading, not error
expect(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 & Act
render(<ResultPreview {...defaultProps} isRunning={true} />)
- // Assert
expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()
})
it('should not show loading when isRunning=false', () => {
- // Arrange & Act
render(<ResultPreview {...defaultProps} isRunning={false} />)
- // Assert
expect(screen.queryByText('pipeline.result.resultPreview.loading')).not.toBeInTheDocument()
})
it('should prioritize outputs over loading state', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Data' }])
- // Act
render(<ResultPreview {...defaultProps} isRunning={true} outputs={outputs} />)
- // Assert
expect(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', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Test' }])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const chunkList = screen.getByTestId('chunk-card-list')
expect(chunkList).toHaveAttribute('data-chunk-type', ChunkingMode.text)
})
it('should format and pass previewChunks to ChunkCardList', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([
{ content: 'Chunk 1' },
{ content: 'Chunk 2' },
])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const 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', () => {
- // Arrange
const outputs = createParentChildChunkOutputs([
{ content: 'Parent', child_chunks: ['Child 1', 'Child 2'] },
])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const chunkList = screen.getByTestId('chunk-card-list')
expect(chunkList).toHaveAttribute('data-chunk-type', ChunkingMode.parentChild)
})
it('should handle QA outputs', () => {
- // Arrange
const outputs = createQAChunkOutputs([
{ question: 'Q1', answer: 'A1' },
])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const 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 & Act
render(<ResultPreview {...defaultProps} error="Network error" />)
- // Assert
expect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()
})
it('should show error state when error is an empty string', () => {
- // Arrange & Act
render(<ResultPreview {...defaultProps} error="" />)
- // Assert - Empty string is falsy, so error state should NOT show
expect(screen.queryByText('pipeline.result.resultPreview.error')).not.toBeInTheDocument()
})
it('should render both outputs and error when both exist (independent conditions)', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Data' }])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} error="Error" />)
- // Assert - Both are rendered because conditions are independent in the component
expect(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', () => {
- // Arrange
const onSwitchToDetail = vi.fn()
render(<ResultPreview {...defaultProps} error="Error" onSwitchToDetail={onSwitchToDetail} />)
- // Act
fireEvent.click(screen.getByRole('button', { name: /viewDetails/i }))
- // Assert
expect(onSwitchToDetail).toHaveBeenCalledTimes(1)
})
it('should not be called automatically on render', () => {
- // Arrange
const onSwitchToDetail = vi.fn()
- // Act
render(<ResultPreview {...defaultProps} error="Error" onSwitchToDetail={onSwitchToDetail} />)
- // Assert
expect(onSwitchToDetail).not.toHaveBeenCalled()
})
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests
- // -------------------------------------------------------------------------
describe('Memoization', () => {
describe('React.memo wrapper', () => {
it('should be wrapped with React.memo', () => {
- // Arrange & Act
const { rerender } = render(<ResultPreview {...defaultProps} />)
rerender(<ResultPreview {...defaultProps} />)
- // Assert - Component renders correctly after rerender
expect(document.body).toBeInTheDocument()
})
it('should update when props change', () => {
- // Arrange
const { rerender } = render(<ResultPreview {...defaultProps} isRunning={false} />)
- // Act
rerender(<ResultPreview {...defaultProps} isRunning={true} />)
- // Assert
expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()
})
it('should update when outputs change', () => {
- // Arrange
const outputs1 = createGeneralChunkOutputs([{ content: 'First' }])
const { rerender } = render(<ResultPreview {...defaultProps} outputs={outputs1} />)
- // Act
const outputs2 = createGeneralChunkOutputs([{ content: 'Second' }])
rerender(<ResultPreview {...defaultProps} outputs={outputs2} />)
- // Assert
const 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', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([
{ content: 'Memoized chunk 1' },
{ content: 'Memoized chunk 2' },
])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const 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', () => {
- // Arrange
const 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 outputs
const outputs2 = createGeneralChunkOutputs([{ content: 'Updated' }])
rerender(<ResultPreview {...defaultProps} outputs={outputs2} />)
- // Assert
chunkList = 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 & Act
render(<ResultPreview {...defaultProps} outputs={undefined} />)
- // Assert - No chunk list rendered
expect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()
})
})
})
- // -------------------------------------------------------------------------
- // Event Handlers Tests
- // -------------------------------------------------------------------------
describe('Event Handlers', () => {
it('should call onSwitchToDetail when view details button is clicked', () => {
- // Arrange
const onSwitchToDetail = vi.fn()
render(<ResultPreview {...defaultProps} error="Test error" onSwitchToDetail={onSwitchToDetail} />)
- // Act
fireEvent.click(screen.getByRole('button', { name: /viewDetails/i }))
- // Assert
expect(onSwitchToDetail).toHaveBeenCalledTimes(1)
})
it('should handle multiple clicks on view details button', () => {
- // Arrange
const onSwitchToDetail = vi.fn()
render(<ResultPreview {...defaultProps} error="Test error" onSwitchToDetail={onSwitchToDetail} />)
const button = screen.getByRole('button', { name: /viewDetails/i })
- // Act
fireEvent.click(button)
fireEvent.click(button)
fireEvent.click(button)
- // Assert
expect(onSwitchToDetail).toHaveBeenCalledTimes(3)
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle empty state (all props undefined/false)', () => {
- // Arrange & Act
const { container } = render(
<ResultPreview
isRunning={false}
@@ -895,240 +680,178 @@ describe('ResultPreview', () => {
/>,
)
- // Assert - Should render empty fragment
expect(container.firstChild).toBeNull()
})
it('should handle outputs with empty preview chunks', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([])
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const 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', () => {
- // Arrange
const outputs = {
chunk_structure: 'invalid_mode' as ChunkingMode,
preview: [],
}
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert - Should not render chunk list when previewChunks is undefined
expect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()
})
it('should handle unmount cleanly', () => {
- // Arrange
const { unmount } = render(<ResultPreview {...defaultProps} />)
- // Assert
expect(() => unmount()).not.toThrow()
})
it('should handle rapid prop changes', () => {
- // Arrange
const { rerender } = render(<ResultPreview {...defaultProps} />)
- // Act - Rapidly change props
rerender(<ResultPreview {...defaultProps} isRunning={true} />)
rerender(<ResultPreview {...defaultProps} isRunning={false} error="Error" />)
rerender(<ResultPreview {...defaultProps} outputs={createGeneralChunkOutputs([{ content: 'Test' }])} />)
rerender(<ResultPreview {...defaultProps} />)
- // Assert
expect(screen.queryByTestId('chunk-card-list')).not.toBeInTheDocument()
})
it('should handle very large number of chunks', () => {
- // Arrange
const outputs = createGeneralChunkOutputs(createMockGeneralChunks(1000))
- // Act
render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert - Should only show first 20 chunks
const 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)', () => {
- // Arrange
const 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 input
expect(() => render(<ResultPreview {...defaultProps} outputs={outputs} />)).toThrow()
})
})
- // -------------------------------------------------------------------------
- // Integration Tests
- // -------------------------------------------------------------------------
describe('Integration', () => {
it('should transition from loading to output state', () => {
- // Arrange
const { rerender } = render(<ResultPreview {...defaultProps} isRunning={true} />)
expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()
- // Act
const outputs = createGeneralChunkOutputs([{ content: 'Loaded data' }])
rerender(<ResultPreview {...defaultProps} isRunning={false} outputs={outputs} />)
- // Assert
expect(screen.queryByText('pipeline.result.resultPreview.loading')).not.toBeInTheDocument()
expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()
})
it('should transition from loading to error state', () => {
- // Arrange
const { rerender } = render(<ResultPreview {...defaultProps} isRunning={true} />)
expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()
- // Act
rerender(<ResultPreview {...defaultProps} isRunning={false} error="Failed to load" />)
- // Assert
expect(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', () => {
- // Arrange
const { rerender } = render(<ResultPreview {...defaultProps} error="Initial error" />)
expect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()
- // Act - Outputs provided while error still exists
const 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', () => {
- // Arrange
const { rerender } = render(<ResultPreview {...defaultProps} error="Initial error" />)
expect(screen.getByText('pipeline.result.resultPreview.error')).toBeInTheDocument()
- // Act - Clear error and provide outputs
const outputs = createGeneralChunkOutputs([{ content: 'Success data' }])
rerender(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert - Only outputs shown when error is cleared
expect(screen.queryByText('pipeline.result.resultPreview.error')).not.toBeInTheDocument()
expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()
})
it('should handle complete flow: empty -> loading -> outputs', () => {
- // Arrange
const { rerender, container } = render(<ResultPreview {...defaultProps} />)
expect(container.firstChild).toBeNull()
- // Act - Start loading
rerender(<ResultPreview {...defaultProps} isRunning={true} />)
expect(screen.getByText('pipeline.result.resultPreview.loading')).toBeInTheDocument()
- // Act - Receive outputs
const outputs = createGeneralChunkOutputs([{ content: 'Final data' }])
rerender(<ResultPreview {...defaultProps} isRunning={false} outputs={outputs} />)
- // Assert
expect(screen.getByTestId('chunk-card-list')).toBeInTheDocument()
})
})
- // -------------------------------------------------------------------------
- // Styling Tests
- // -------------------------------------------------------------------------
describe('Styling', () => {
it('should have correct container classes for loading state', () => {
- // Arrange & Act
const { container } = render(<ResultPreview {...defaultProps} isRunning={true} />)
- // Assert
const loadingContainer = container.querySelector('.flex.grow.flex-col.items-center.justify-center')
expect(loadingContainer).toBeInTheDocument()
})
it('should have correct container classes for error state', () => {
- // Arrange & Act
const { container } = render(<ResultPreview {...defaultProps} error="Error" />)
- // Assert
const errorContainer = container.querySelector('.flex.grow.flex-col.items-center.justify-center')
expect(errorContainer).toBeInTheDocument()
})
it('should have correct container classes for outputs state', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Test' }])
- // Act
const { container } = render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const outputContainer = container.querySelector('.flex.grow.flex-col.bg-background-body')
expect(outputContainer).toBeInTheDocument()
})
it('should have gradient dividers in footer', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Test' }])
- // Act
const { container } = render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const 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 & Act
render(<ResultPreview {...defaultProps} error="Error" />)
- // Assert
const button = screen.getByRole('button')
expect(button).toBeInTheDocument()
})
it('should have title attribute on footer tip for long text', () => {
- // Arrange
const outputs = createGeneralChunkOutputs([{ content: 'Test' }])
- // Act
const { container } = render(<ResultPreview {...defaultProps} outputs={outputs} />)
- // Assert
const 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 & Act
const { container } = render(
<ResultPreview
isRunning={isRunning}
@@ -1157,7 +879,6 @@ describe('State Transition Matrix', () => {
/>,
)
- // Assert
switch (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.tsx
similarity index 81%
rename from web/app/components/rag-pipeline/components/panel/test-run/result/tabs/index.spec.tsx
rename to web/app/components/rag-pipeline/components/panel/test-run/result/tabs/__tests__/index.spec.tsx
index 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', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -81,16 +55,13 @@ describe('Tab', () => {
/>,
)
- // Assert
expect(screen.getByRole('button', { name: 'Test Label' })).toBeInTheDocument()
})
it('should render as button element with correct type', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -101,23 +72,17 @@ describe('Tab', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={true}
@@ -128,18 +93,15 @@ describe('Tab', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -150,7 +112,6 @@ describe('Tab', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -174,16 +133,13 @@ describe('Tab', () => {
/>,
)
- // Assert
expect(screen.getByText('Custom Label Text')).toBeInTheDocument()
})
it('should handle empty label', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -194,18 +150,15 @@ describe('Tab', () => {
/>,
)
- // Assert
expect(screen.getByRole('button')).toBeInTheDocument()
expect(screen.getByRole('button')).toHaveTextContent('')
})
it('should handle long label text', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
const longLabel = 'This is a very long label text for testing purposes'
- // Act
render(
<Tab
isActive={false}
@@ -216,19 +169,16 @@ describe('Tab', () => {
/>,
)
- // Assert
expect(screen.getByText(longLabel)).toBeInTheDocument()
})
})
describe('value prop', () => {
it('should pass value to onClick handler when clicked', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
const testValue = 'CUSTOM_VALUE'
- // Act
render(
<Tab
isActive={false}
@@ -240,18 +190,15 @@ describe('Tab', () => {
)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(mockOnClick).toHaveBeenCalledWith(testValue)
})
})
describe('workflowRunningData prop', () => {
it('should enable button when workflowRunningData is provided', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -262,15 +209,12 @@ describe('Tab', () => {
/>,
)
- // Assert
expect(screen.getByRole('button')).not.toBeDisabled()
})
it('should disable button when workflowRunningData is undefined', () => {
- // Arrange
const mockOnClick = vi.fn()
- // Act
render(
<Tab
isActive={false}
@@ -281,15 +225,12 @@ describe('Tab', () => {
/>,
)
- // Assert
expect(screen.getByRole('button')).toBeDisabled()
})
it('should apply disabled styles when workflowRunningData is undefined', () => {
- // Arrange
const mockOnClick = vi.fn()
- // Act
render(
<Tab
isActive={false}
@@ -300,18 +241,15 @@ describe('Tab', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -322,7 +260,6 @@ describe('Tab', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -351,16 +283,13 @@ describe('Tab', () => {
)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(mockOnClick).toHaveBeenCalledTimes(1)
expect(mockOnClick).toHaveBeenCalledWith('RESULT')
})
it('should not call onClick when disabled (no workflowRunningData)', () => {
- // Arrange
const mockOnClick = vi.fn()
- // Act
render(
<Tab
isActive={false}
@@ -372,16 +301,13 @@ describe('Tab', () => {
)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(mockOnClick).not.toHaveBeenCalled()
})
it('should handle multiple clicks correctly', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -396,17 +322,12 @@ describe('Tab', () => {
fireEvent.click(button)
fireEvent.click(button)
- // Assert
expect(mockOnClick).toHaveBeenCalledTimes(3)
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests - Verify React.memo optimization
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should not re-render when props are the same', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
const renderSpy = vi.fn()
@@ -417,7 +338,6 @@ describe('Tab', () => {
}
const MemoizedTabWithSpy = React.memo(TabWithSpy)
- // Act
const { rerender } = render(
<MemoizedTabWithSpy
isActive={false}
@@ -428,7 +348,6 @@ describe('Tab', () => {
/>,
)
- // Re-render with same props
rerender(
<MemoizedTabWithSpy
isActive={false}
@@ -439,16 +358,13 @@ describe('Tab', () => {
/>,
)
- // Assert - React.memo should prevent re-render with same props
expect(renderSpy).toHaveBeenCalledTimes(1)
})
it('should re-render when isActive prop changes', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
const { rerender } = render(
<Tab
isActive={false}
@@ -459,10 +375,8 @@ describe('Tab', () => {
/>,
)
- // Assert initial state
expect(screen.getByRole('button')).toHaveClass('text-text-tertiary')
- // Rerender with changed prop
rerender(
<Tab
isActive={true}
@@ -473,16 +387,13 @@ describe('Tab', () => {
/>,
)
- // Assert updated state
expect(screen.getByRole('button')).toHaveClass('text-text-primary')
})
it('should re-render when label prop changes', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
const { rerender } = render(
<Tab
isActive={false}
@@ -493,10 +404,8 @@ describe('Tab', () => {
/>,
)
- // Assert initial state
expect(screen.getByText('Original Label')).toBeInTheDocument()
- // Rerender with changed prop
rerender(
<Tab
isActive={false}
@@ -507,17 +416,14 @@ describe('Tab', () => {
/>,
)
- // Assert updated state
expect(screen.getByText('Updated Label')).toBeInTheDocument()
expect(screen.queryByText('Original Label')).not.toBeInTheDocument()
})
it('should use stable handleClick callback with useCallback', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
const { rerender } = render(
<Tab
isActive={false}
@@ -531,7 +437,6 @@ describe('Tab', () => {
fireEvent.click(screen.getByRole('button'))
expect(mockOnClick).toHaveBeenCalledWith('TEST_VALUE')
- // Rerender with same value and onClick
rerender(
<Tab
isActive={true}
@@ -548,17 +453,12 @@ describe('Tab', () => {
})
})
- // -------------------------------------------------------------------------
- // Edge Cases Tests - Verify boundary conditions
- // -------------------------------------------------------------------------
describe('Edge Cases', () => {
it('should handle special characters in label', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
const specialLabel = 'Tab <>&"\''
- // Act
render(
<Tab
isActive={false}
@@ -569,16 +469,13 @@ describe('Tab', () => {
/>,
)
- // Assert
expect(screen.getByText(specialLabel)).toBeInTheDocument()
})
it('should handle special characters in value', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -590,16 +487,13 @@ describe('Tab', () => {
)
fireEvent.click(screen.getByRole('button'))
- // Assert
expect(mockOnClick).toHaveBeenCalledWith('SPECIAL_VALUE_123')
})
it('should handle unicode in label', () => {
- // Arrange
const mockOnClick = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tab
isActive={false}
@@ -610,15 +504,12 @@ describe('Tab', () => {
/>,
)
- // Assert
expect(screen.getByText('结果 🚀')).toBeInTheDocument()
})
it('should combine isActive and disabled states correctly', () => {
- // Arrange
const mockOnClick = vi.fn()
- // Act - Active but disabled (no workflowRunningData)
render(
<Tab
isActive={true}
@@ -629,7 +520,6 @@ describe('Tab', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -666,18 +547,15 @@ describe('Tabs', () => {
/>,
)
- // Assert - Check all three tabs are rendered with i18n keys
expect(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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
const { container } = render(
<Tabs
currentTab="RESULT"
@@ -686,7 +564,6 @@ describe('Tabs', () => {
/>,
)
- // Assert
const tabsContainer = container.firstChild
expect(tabsContainer).toHaveClass('flex')
expect(tabsContainer).toHaveClass('shrink-0')
@@ -698,11 +575,9 @@ describe('Tabs', () => {
})
it('should render exactly three tab buttons', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -711,23 +586,17 @@ describe('Tabs', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -736,7 +605,6 @@ describe('Tabs', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="DETAIL"
@@ -760,7 +626,6 @@ describe('Tabs', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="TRACING"
@@ -784,7 +647,6 @@ describe('Tabs', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="UNKNOWN"
@@ -808,7 +668,6 @@ describe('Tabs', () => {
/>,
)
- // Assert - All tabs should be inactive
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -834,7 +691,6 @@ describe('Tabs', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -854,7 +708,6 @@ describe('Tabs', () => {
/>,
)
- // Assert
const buttons = screen.getAllByRole('button')
buttons.forEach((button) => {
expect(button).toBeDisabled()
@@ -863,11 +716,9 @@ describe('Tabs', () => {
})
it('should pass workflowRunningData to all Tab components', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -900,22 +748,16 @@ describe('Tabs', () => {
)
fireEvent.click(screen.getByRole('button', { name: 'runLog.detail' }))
- // Assert
expect(mockSwitchTab).toHaveBeenCalledWith('DETAIL')
})
})
})
- // -------------------------------------------------------------------------
- // Event Handlers Tests - Verify click behavior
- // -------------------------------------------------------------------------
describe('Event Handlers', () => {
it('should call switchTab with RESULT when RESULT tab is clicked', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="DETAIL"
@@ -925,16 +767,13 @@ describe('Tabs', () => {
)
fireEvent.click(screen.getByRole('button', { name: 'runLog.result' }))
- // Assert
expect(mockSwitchTab).toHaveBeenCalledWith('RESULT')
})
it('should call switchTab with DETAIL when DETAIL tab is clicked', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -944,16 +783,13 @@ describe('Tabs', () => {
)
fireEvent.click(screen.getByRole('button', { name: 'runLog.detail' }))
- // Assert
expect(mockSwitchTab).toHaveBeenCalledWith('DETAIL')
})
it('should call switchTab with TRACING when TRACING tab is clicked', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -963,15 +799,12 @@ describe('Tabs', () => {
)
fireEvent.click(screen.getByRole('button', { name: 'runLog.tracing' }))
- // Assert
expect(mockSwitchTab).toHaveBeenCalledWith('TRACING')
})
it('should not call switchTab when tabs are disabled', () => {
- // Arrange
const mockSwitchTab = vi.fn()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -985,16 +818,13 @@ describe('Tabs', () => {
fireEvent.click(button)
})
- // Assert
expect(mockSwitchTab).not.toHaveBeenCalled()
})
it('should allow clicking the currently active tab', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -1004,17 +834,12 @@ describe('Tabs', () => {
)
fireEvent.click(screen.getByRole('button', { name: 'runLog.result' }))
- // Assert
expect(mockSwitchTab).toHaveBeenCalledWith('RESULT')
})
})
- // -------------------------------------------------------------------------
- // Memoization Tests - Verify React.memo optimization
- // -------------------------------------------------------------------------
describe('Memoization', () => {
it('should not re-render when props are the same', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
const renderSpy = vi.fn()
@@ -1025,7 +850,6 @@ describe('Tabs', () => {
}
const MemoizedTabsWithSpy = React.memo(TabsWithSpy)
- // Act
const { rerender } = render(
<MemoizedTabsWithSpy
currentTab="RESULT"
@@ -1034,7 +858,6 @@ describe('Tabs', () => {
/>,
)
- // Re-render with same props
rerender(
<MemoizedTabsWithSpy
currentTab="RESULT"
@@ -1043,16 +866,13 @@ describe('Tabs', () => {
/>,
)
- // Assert - React.memo should prevent re-render with same props
expect(renderSpy).toHaveBeenCalledTimes(1)
})
it('should re-render when currentTab changes', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
const { rerender } = render(
<Tabs
currentTab="RESULT"
@@ -1061,10 +881,8 @@ describe('Tabs', () => {
/>,
)
- // Assert initial state
expect(screen.getByRole('button', { name: 'runLog.result' })).toHaveClass('text-text-primary')
- // Rerender with changed prop
rerender(
<Tabs
currentTab="DETAIL"
@@ -1073,17 +891,14 @@ describe('Tabs', () => {
/>,
)
- // Assert updated state
expect(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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
const { rerender } = render(
<Tabs
currentTab="RESULT"
@@ -1092,13 +907,11 @@ describe('Tabs', () => {
/>,
)
- // Assert initial disabled state
const buttons = screen.getAllByRole('button')
buttons.forEach((button) => {
expect(button).toBeDisabled()
})
- // Rerender with workflowRunningData
rerender(
<Tabs
currentTab="RESULT"
@@ -1107,7 +920,6 @@ describe('Tabs', () => {
/>,
)
- // Assert enabled state
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab=""
@@ -1133,7 +940,6 @@ describe('Tabs', () => {
/>,
)
- // Assert - All tabs should be inactive
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act - lowercase "result" should not match "RESULT"
render(
<Tabs
currentTab="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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab=" RESULT "
@@ -1172,12 +973,10 @@ describe('Tabs', () => {
/>,
)
- // Assert - Should not match due to whitespace
expect(screen.getByRole('button', { name: 'runLog.result' })).toHaveClass('text-text-tertiary')
})
it('should render correctly with minimal workflowRunningData', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const minimalWorkflowData: WorkflowRunningData = {
result: {
@@ -1188,7 +987,6 @@ describe('Tabs', () => {
},
}
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -1197,7 +995,6 @@ describe('Tabs', () => {
/>,
)
- // Assert
const 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)', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="RESULT"
@@ -1218,7 +1013,6 @@ describe('Tabs', () => {
/>,
)
- // Assert
const 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', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act
render(
<Tabs
currentTab="DETAIL"
@@ -1244,22 +1033,18 @@ describe('Tabs', () => {
/>,
)
- // Assert - Verify each tab has correct props
const 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 states
expect(resultTab).toHaveClass('text-text-tertiary')
expect(detailTab).toHaveClass('text-text-primary')
expect(tracingTab).toHaveClass('text-text-tertiary')
- // Check enabled states
expect(resultTab).not.toBeDisabled()
expect(detailTab).not.toBeDisabled()
expect(tracingTab).not.toBeDisabled()
- // Check click handlers
fireEvent.click(resultTab)
expect(mockSwitchTab).toHaveBeenCalledWith('RESULT')
@@ -1268,12 +1053,10 @@ describe('Tabs', () => {
})
it('should support full tab switching workflow', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
let currentTab = 'RESULT'
- // Act
const { rerender } = render(
<Tabs
currentTab={currentTab}
@@ -1282,11 +1065,9 @@ describe('Tabs', () => {
/>,
)
- // Simulate clicking DETAIL tab
fireEvent.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 active
expect(screen.getByRole('button', { name: 'runLog.detail' })).toHaveClass('text-text-primary')
- // Simulate clicking TRACING tab
fireEvent.click(screen.getByRole('button', { name: 'runLog.tracing' }))
expect(mockSwitchTab).toHaveBeenCalledWith('TRACING')
- // Update currentTab and rerender
currentTab = 'TRACING'
rerender(
<Tabs
@@ -1313,16 +1091,13 @@ describe('Tabs', () => {
/>,
)
- // Assert TRACING is now active
expect(screen.getByRole('button', { name: 'runLog.tracing' })).toHaveClass('text-text-primary')
})
it('should transition from disabled to enabled state', () => {
- // Arrange
const mockSwitchTab = vi.fn()
const workflowData = createWorkflowRunningData()
- // Act - Initial disabled state
const { rerender } = render(
<Tabs
currentTab="RESULT"
@@ -1331,11 +1106,9 @@ describe('Tabs', () => {
/>,
)
- // Try clicking - should not trigger
fireEvent.click(screen.getByRole('button', { name: 'runLog.detail' }))
expect(mockSwitchTab).not.toHaveBeenCalled()
- // Enable tabs
rerender(
<Tabs
currentTab="RESULT"
@@ -1344,7 +1117,6 @@ describe('Tabs', () => {
/>,
)
- // Now click should work
fireEvent.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.tsx
similarity index 84%
rename from web/app/components/rag-pipeline/components/rag-pipeline-header/index.spec.tsx
rename to web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/index.spec.tsx
index 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 store
const mockSetShowInputFieldPanel = vi.fn()
const mockSetShowEnvPanel = vi.fn()
const mockSetIsPreparingDataSource = vi.fn()
@@ -51,7 +42,6 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-// Mock workflow hooks
const 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 component
vi.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/navigation
const mockPush = vi.fn()
vi.mock('next/navigation', () => ({
useParams: () => ({ datasetId: 'test-dataset-id' }),
useRouter: () => ({ push: mockPush }),
}))
-// Mock next/link
vi.mock('next/link', () => ({
default: ({ children, href, ...props }: PropsWithChildren<{ href: string }>) => (
<a href={href} {...props}>{children}</a>
),
}))
-// Mock service hooks
const 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 hooks
const mockMutateDatasetRes = vi.fn()
vi.mock('@/context/dataset-detail', () => ({
useDatasetDetailContextWithSelector: () => mockMutateDatasetRes,
@@ -145,7 +130,6 @@ vi.mock('@/context/provider-context', () => ({
selector(mockProviderContextValue),
}))
-// Mock event emitter context
const mockEventEmitter = {
useSubscription: vi.fn(),
}
@@ -156,7 +140,6 @@ vi.mock('@/context/event-emitter', () => ({
}),
}))
-// Mock hooks
vi.mock('@/hooks/use-api-access-url', () => ({
useDatasetApiAccessUrl: () => '/api/docs',
}))
@@ -167,12 +150,10 @@ vi.mock('@/hooks/use-format-time-from-now', () => ({
}),
}))
-// Mock amplitude tracking
vi.mock('@/app/components/base/amplitude', () => ({
trackEvent: vi.fn(),
}))
-// Mock toast context
const mockNotify = vi.fn()
vi.mock('@/app/components/base/toast', () => ({
useToastContext: () => ({
@@ -180,13 +161,11 @@ vi.mock('@/app/components/base/toast', () => ({
}),
}))
-// Mock workflow utils
vi.mock('@/app/components/workflow/utils', () => ({
getKeyboardKeyCodeBySystem: (key: string) => key,
getKeyboardKeyNameBySystem: (key: string) => key,
}))
-// Mock ahooks
vi.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 state
let portalOpenState = false
vi.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) => void
onCancel: () => 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 pipelineId
mockStoreState.pipelineId = 'pipeline-alpha'
const { unmount } = render(<RagPipelineHeader />)
let viewHistoryContent = screen.getByTestId('header-view-history').textContent
expect(viewHistoryContent).toContain('pipeline-alpha')
unmount()
- // Test with different pipelineId
mockStoreState.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 mockSetShowInputFieldPanel
render(<InputFieldButton />)
- // Should not throw when clicked
expect(() => 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 called
expect(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 keys
expect(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 button
const 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 disabled
expect(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 callback
let subscriptionCallback: ((v: { type: string }) => void) | null = null
mockEventEmitter.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 type
subscriptionCallback!({ 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 undefined
expect(() => render(<RunMode />)).not.toThrow()
})
@@ -951,14 +859,10 @@ describe('RunMode', () => {
render(<RunMode />)
- // useSubscription should not be called
expect(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 symbol
expect((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 />)
- // InputFieldButton
expect(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 behavior
expect(() => render(<RunMode />)).toThrow()
})
})
describe('RunMode Edge Cases', () => {
beforeEach(() => {
- // Ensure clean state for each test
mockStoreState.workflowRunningData = null
mockStoreState.isPreparingDataSource = false
})
it('should handle both isPreparingDataSource and isRunning being true', () => {
- // This shouldn't happen in practice, but test the priority
mockStoreState.isPreparingDataSource = true
mockStoreState.workflowRunningData = {
task_id: 'task-123',
@@ -1158,7 +1046,6 @@ describe('Edge Cases', () => {
render(<RunMode />)
- // Button should be disabled
const 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 text
const 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 text
const 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 exist
expect(screen.getByText('alt')).toBeInTheDocument()
expect(screen.getByText('R')).toBeInTheDocument()
})
@@ -1216,7 +1100,6 @@ describe('Edge Cases', () => {
render(<RunMode />)
- // Should have svg icon in the button
const 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 icon
const 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 crashing
expect(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.tsx
new file mode 100644
index 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.tsx
similarity index 81%
rename from web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.spec.tsx
rename to web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
index 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/navigation
const mockPush = vi.fn()
vi.mock('next/navigation', () => ({
useParams: () => ({ datasetId: 'test-dataset-id' }),
useRouter: () => ({ push: mockPush }),
}))
-// Mock next/link
vi.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 testing
let keyPressCallback: ((e: KeyboardEvent) => void) | null = null
vi.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 tests
keyPressCallback = callback
},
}))
-// Mock amplitude tracking
vi.mock('@/app/components/base/amplitude', () => ({
trackEvent: vi.fn(),
}))
-// Mock portal-to-follow-elem
let mockPortalOpen = false
vi.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 hooks
const 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 store
const 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 context
const 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-context
const mockSetShowPricingModal = vi.fn()
vi.mock('@/context/modal-context', () => ({
useModalContextSelector: () => mockSetShowPricingModal,
}))
-// Mock provider-context
const mockIsAllowPublishAsCustomKnowledgePipelineTemplate = vi.fn(() => true)
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => ({
@@ -135,7 +119,6 @@ vi.mock('@/context/provider-context', () => ({
selector({ isAllowPublishAsCustomKnowledgePipelineTemplate: mockIsAllowPublishAsCustomKnowledgePipelineTemplate() }),
}))
-// Mock toast context
const mockNotify = vi.fn()
vi.mock('@/app/components/base/toast', () => ({
useToastContext: () => ({
@@ -143,12 +126,10 @@ vi.mock('@/app/components/base/toast', () => ({
}),
}))
-// Mock API access URL hook
vi.mock('@/hooks/use-api-access-url', () => ({
useDatasetApiAccessUrl: () => 'https://api.dify.ai/v1/datasets/test-dataset-id',
}))
-// Mock format time hook
vi.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 hooks
const mockPublishWorkflow = vi.fn()
const mockPublishAsCustomizedPipeline = vi.fn()
const mockInvalidPublishedPipelineInfo = vi.fn()
@@ -191,14 +171,12 @@ vi.mock('@/service/use-workflow', () => ({
}),
}))
-// Mock workflow utils
vi.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: boolean
onConfirm: (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 = false
keyPressCallback = null
- // Reset mock return values to defaults
mockPublishedAt.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 & Act
renderWithQueryClient(<Publisher />)
- // Assert
expect(screen.getByRole('button')).toBeInTheDocument()
expect(screen.getByText('workflow.common.publish')).toBeInTheDocument()
})
it('should render portal element in closed state by default', () => {
- // Arrange & Act
renderWithQueryClient(<Publisher />)
- // Assert
expect(screen.getByTestId('portal-elem')).toHaveAttribute('data-open', 'false')
expect(screen.queryByTestId('portal-content')).not.toBeInTheDocument()
})
it('should render down arrow icon in button', () => {
- // Arrange & Act
renderWithQueryClient(<Publisher />)
- // Assert
const button = screen.getByRole('button')
expect(button.querySelector('svg')).toBeInTheDocument()
})
})
- // --------------------------------
- // State Management Tests
- // --------------------------------
describe('State Management', () => {
it('should open popup when trigger is clicked', async () => {
- // Arrange
renderWithQueryClient(<Publisher />)
- // Act
fireEvent.click(screen.getByTestId('portal-trigger'))
- // Assert
await waitFor(() => {
expect(screen.getByTestId('portal-content')).toBeInTheDocument()
})
})
it('should close popup when trigger is clicked again while open', async () => {
- // Arrange
renderWithQueryClient(<Publisher />)
fireEvent.click(screen.getByTestId('portal-trigger')) // open
- // Act
await waitFor(() => {
expect(screen.getByTestId('portal-content')).toBeInTheDocument()
})
fireEvent.click(screen.getByTestId('portal-trigger')) // close
- // Assert
await 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 () => {
- // Arrange
renderWithQueryClient(<Publisher />)
- // Act
fireEvent.click(screen.getByTestId('portal-trigger'))
- // Assert
expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true)
})
it('should not call handleSyncWorkflowDraft when popup closes', async () => {
- // Arrange
renderWithQueryClient(<Publisher />)
fireEvent.click(screen.getByTestId('portal-trigger')) // open
vi.clearAllMocks()
- // Act
await waitFor(() => {
expect(screen.getByTestId('portal-content')).toBeInTheDocument()
})
fireEvent.click(screen.getByTestId('portal-trigger')) // close
- // Assert
expect(mockHandleSyncWorkflowDraft).not.toHaveBeenCalled()
})
it('should be memoized with React.memo', () => {
- // Assert
expect(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 () => {
- // Arrange
renderWithQueryClient(<Publisher />)
- // Act
fireEvent.click(screen.getByTestId('portal-trigger'))
- // Assert
await 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', () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
expect(screen.getByText('workflow.common.currentDraftUnpublished')).toBeInTheDocument()
expect(screen.getByText(/workflow.common.autoSaved/)).toBeInTheDocument()
})
it('should render published state when publishedAt has value', () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
expect(screen.getByText('workflow.common.latestPublished')).toBeInTheDocument()
expect(screen.getByText(/workflow.common.publishedAt/)).toBeInTheDocument()
})
it('should render publish button with keyboard shortcuts', () => {
- // Arrange & Act
renderWithQueryClient(<Popup />)
- // Assert
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
expect(publishButton).toBeInTheDocument()
})
it('should render action buttons section', () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
expect(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', () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
const 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', () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
const 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', () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
expect(screen.getByText('billing.upgradeBtn.encourageShort')).toBeInTheDocument()
})
it('should not show premium badge when publish as template is allowed', () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
expect(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 () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert
await waitFor(() => {
expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()
})
})
it('should not show confirm modal when already published', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert - should call publish directly without confirm
await waitFor(() => {
expect(mockPublishWorkflow).toHaveBeenCalled()
})
})
it('should update to published state after successful publish', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert
await 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 () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
renderWithQueryClient(<Popup />)
- // Act
const addDocumentsButton = screen.getAllByRole('button').find(btn =>
btn.textContent?.includes('pipeline.common.goToAddDocuments'),
)
fireEvent.click(addDocumentsButton!)
- // Assert
expect(mockPush).toHaveBeenCalledWith('/datasets/test-dataset-id/documents/create-from-pipeline')
})
it('should show pricing modal when publish as template is clicked without permission', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false)
renderWithQueryClient(<Popup />)
- // Act
const publishAsButton = screen.getAllByRole('button').find(btn =>
btn.textContent?.includes('pipeline.common.publishAs'),
)
fireEvent.click(publishAsButton!)
- // Assert
expect(mockSetShowPricingModal).toHaveBeenCalled()
})
it('should show publish as knowledge pipeline modal when permitted', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)
renderWithQueryClient(<Popup />)
- // Act
const publishAsButton = screen.getAllByRole('button').find(btn =>
btn.textContent?.includes('pipeline.common.publishAs'),
)
fireEvent.click(publishAsButton!)
- // Assert
await waitFor(() => {
expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()
})
})
it('should close publish as knowledge pipeline modal when cancel is clicked', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)
renderWithQueryClient(<Popup />)
@@ -610,17 +488,14 @@ describe('publisher', () => {
expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()
})
- // Act
fireEvent.click(screen.getByTestId('modal-cancel'))
- // Assert
await waitFor(() => {
expect(screen.queryByTestId('publish-as-knowledge-pipeline-modal')).not.toBeInTheDocument()
})
})
it('should call publishAsCustomizedPipeline when confirm is clicked in modal', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishAsCustomizedPipeline.mockResolvedValue({})
renderWithQueryClient(<Popup />)
@@ -634,10 +509,8 @@ describe('publisher', () => {
expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()
})
- // Act
fireEvent.click(screen.getByTestId('modal-confirm'))
- // Assert
await 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 () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert
await 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 () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert
await waitFor(() => {
expect(mockNotify).toHaveBeenCalledWith(
expect.objectContaining({
@@ -695,32 +559,26 @@ describe('publisher', () => {
})
it('should update publishedAt in store after successful publish', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert
await waitFor(() => {
expect(mockSetPublishedAt).toHaveBeenCalledWith(1700100000)
})
})
it('should invalidate caches after successful publish', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert
await waitFor(() => {
expect(mockMutateDatasetRes).toHaveBeenCalled()
expect(mockInvalidPublishedPipelineInfo).toHaveBeenCalled()
@@ -729,7 +587,6 @@ describe('publisher', () => {
})
it('should show success notification for publish as template', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishAsCustomizedPipeline.mockResolvedValue({})
renderWithQueryClient(<Popup />)
@@ -743,10 +600,8 @@ describe('publisher', () => {
expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()
})
- // Act
fireEvent.click(screen.getByTestId('modal-confirm'))
- // Assert
await waitFor(() => {
expect(mockNotify).toHaveBeenCalledWith(
expect.objectContaining({
@@ -758,7 +613,6 @@ describe('publisher', () => {
})
it('should invalidate customized template list after publish as template', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishAsCustomizedPipeline.mockResolvedValue({})
renderWithQueryClient(<Popup />)
@@ -772,31 +626,23 @@ describe('publisher', () => {
expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()
})
- // Act
fireEvent.click(screen.getByTestId('modal-confirm'))
- // Assert
await waitFor(() => {
expect(mockInvalidCustomizedTemplateList).toHaveBeenCalled()
})
})
})
- // --------------------------------
- // Error Handling Tests
- // --------------------------------
describe('Error Handling', () => {
it('should not proceed with publish when check fails', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockHandleCheckBeforePublish.mockResolvedValue(false)
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert - publishWorkflow should not be called when check fails
await waitFor(() => {
expect(mockHandleCheckBeforePublish).toHaveBeenCalled()
})
@@ -804,16 +650,13 @@ describe('publisher', () => {
})
it('should show error notification when publish fails', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockRejectedValue(new Error('Publish failed'))
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert
await waitFor(() => {
expect(mockNotify).toHaveBeenCalledWith({
type: 'error',
@@ -823,7 +666,6 @@ describe('publisher', () => {
})
it('should show error notification when publish as template fails', async () => {
- // Arrange
mockPublishedAt.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()
})
- // Act
fireEvent.click(screen.getByTestId('modal-confirm'))
- // Assert
await waitFor(() => {
expect(mockNotify).toHaveBeenCalledWith({
type: 'error',
@@ -850,7 +690,6 @@ describe('publisher', () => {
})
it('should close modal after publish as template error', async () => {
- // Arrange
mockPublishedAt.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()
})
- // Act
fireEvent.click(screen.getByTestId('modal-confirm'))
- // Assert
await 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 () => {
- // Arrange
mockPublishedAt.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 modal
const 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 displayed
expect(screen.getByText('pipeline.common.confirmPublishContent')).toBeInTheDocument()
})
it('should publish when confirm is clicked in confirm modal', async () => {
- // Arrange
mockPublishedAt.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 displayed
expect(screen.getByText('pipeline.common.confirmPublishContent')).toBeInTheDocument()
})
})
- // --------------------------------
- // Component Memoization Tests
- // --------------------------------
describe('Component Memoization', () => {
it('should be memoized with React.memo', () => {
- // Assert
expect(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 permission
mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(true)
const { container } = renderWithQueryClient(<Popup />)
@@ -949,7 +767,6 @@ describe('publisher', () => {
})
it('should display correct width when permission is not allowed', () => {
- // Test without permission
mockIsAllowPublishAsCustomKnowledgePipelineTemplate.mockReturnValue(false)
const { container } = renderWithQueryClient(<Popup />)
@@ -958,63 +775,45 @@ describe('publisher', () => {
})
it('should display draft updated time when not published', () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
mockDraftUpdatedAt.mockReturnValue(1700000000)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
expect(screen.getByText(/workflow.common.autoSaved/)).toBeInTheDocument()
})
it('should handle null draftUpdatedAt gracefully', () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
mockDraftUpdatedAt.mockReturnValue(0)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
expect(screen.getByText(/workflow.common.autoSaved/)).toBeInTheDocument()
})
})
- // --------------------------------
- // API Reference Link Tests
- // --------------------------------
describe('API Reference Link', () => {
it('should render API reference link with correct href', () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
- // Act
renderWithQueryClient(<Popup />)
- // Assert
const 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 () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act - simulate keyboard shortcut
const mockEvent = { preventDefault: vi.fn() } as unknown as KeyboardEvent
keyPressCallback?.(mockEvent)
- // Assert
expect(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 () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // First publish via button click to set published state
const 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 published
const mockEvent = { preventDefault: vi.fn() } as unknown as KeyboardEvent
keyPressCallback?.(mockEvent)
- // Assert - should return early without publishing
expect(mockEvent.preventDefault).toHaveBeenCalled()
expect(mockPublishWorkflow).not.toHaveBeenCalled()
})
it('should show confirm modal when shortcut pressed on unpublished pipeline', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
renderWithQueryClient(<Popup />)
- // Act - simulate keyboard shortcut
const mockEvent = { preventDefault: vi.fn() } as unknown as KeyboardEvent
keyPressCallback?.(mockEvent)
- // Assert
await 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 control
let resolvePublish: () => void = () => {}
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockImplementation(() => new Promise((resolve) => {
@@ -1070,59 +861,45 @@ describe('publisher', () => {
}))
renderWithQueryClient(<Popup />)
- // Act - trigger publish via keyboard shortcut first
const mockEvent1 = { preventDefault: vi.fn() } as unknown as KeyboardEvent
keyPressCallback?.(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 publishing
const mockEvent2 = { preventDefault: vi.fn() } as unknown as KeyboardEvent
keyPressCallback?.(mockEvent2)
- // Assert - only one call to publishWorkflow
expect(mockPublishWorkflow).toHaveBeenCalledTimes(1)
- // Cleanup - resolve the promise
resolvePublish()
})
})
- // --------------------------------
- // Finally Block Cleanup Tests
- // --------------------------------
describe('Finally Block Cleanup', () => {
it('should reset publishing state after successful publish', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert - button should be disabled during publishing, then show published
await waitFor(() => {
expect(screen.getByRole('button', { name: /workflow.common.published/i })).toBeInTheDocument()
})
})
it('should reset publishing state after failed publish', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockRejectedValue(new Error('Publish failed'))
renderWithQueryClient(<Popup />)
- // Act
const 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 published
await waitFor(() => {
expect(screen.getByRole('button', { name: /workflow.common.publishUpdate/i })).toBeInTheDocument()
})
})
it('should hide confirm modal after publish from confirm', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Show confirm modal first
const 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 publish
fireEvent.click(publishButton)
- // Assert - confirm modal should be hidden after publish completes
await waitFor(() => {
expect(screen.getByRole('button', { name: /workflow.common.published/i })).toBeInTheDocument()
})
})
it('should hide confirm modal after failed publish', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
mockPublishWorkflow.mockRejectedValue(new Error('Publish failed'))
renderWithQueryClient(<Popup />)
- // Show confirm modal first
const 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 shown
await waitFor(() => {
expect(mockNotify).toHaveBeenCalledWith({
type: 'error',
@@ -1190,137 +955,104 @@ describe('publisher', () => {
})
})
- // ============================================================
- // Edge Cases
- // ============================================================
describe('Edge Cases', () => {
it('should handle undefined pipelineId gracefully', () => {
- // Arrange
mockPipelineId.mockReturnValue('')
- // Act
renderWithQueryClient(<Popup />)
- // Assert - should render without crashing
expect(screen.getByText('workflow.common.currentDraftUnpublished')).toBeInTheDocument()
})
it('should handle empty publish response', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue(null)
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert - should not call setPublishedAt or notify when response is null
await waitFor(() => {
expect(mockPublishWorkflow).toHaveBeenCalled()
})
- // setPublishedAt should not be called because res is falsy
expect(mockSetPublishedAt).not.toHaveBeenCalled()
})
it('should prevent multiple simultaneous publish calls', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
- // Create a promise that never resolves to simulate ongoing publish
mockPublishWorkflow.mockImplementation(() => new Promise(() => {}))
renderWithQueryClient(<Popup />)
- // Act - click publish button multiple times rapidly
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Wait for button to become disabled
await waitFor(() => {
expect(publishButton).toBeDisabled()
})
- // Try clicking again
fireEvent.click(publishButton)
fireEvent.click(publishButton)
- // Assert - publishWorkflow should only be called once due to guard
expect(mockPublishWorkflow).toHaveBeenCalledTimes(1)
})
it('should disable publish button when already published in session', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act - publish once
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert - button should show "published" state
await waitFor(() => {
expect(screen.getByRole('button', { name: /workflow.common.published/i })).toBeDisabled()
})
})
it('should not trigger publish when already publishing', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishWorkflow.mockImplementation(() => new Promise(() => {})) // Never resolves
renderWithQueryClient(<Popup />)
- // Act
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // The button should be disabled while publishing
await waitFor(() => {
expect(publishButton).toBeDisabled()
})
})
})
- // ============================================================
- // Integration Tests
- // ============================================================
describe('Integration Tests', () => {
it('should complete full publish flow for unpublished pipeline', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(null)
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- // Act - click publish to show confirm
const publishButton = screen.getByRole('button', { name: /workflow.common.publishUpdate/i })
fireEvent.click(publishButton)
- // Assert - confirm modal should appear
await waitFor(() => {
expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()
})
})
it('should complete full publish as template flow', async () => {
- // Arrange
mockPublishedAt.mockReturnValue(1700000000)
mockPublishAsCustomizedPipeline.mockResolvedValue({})
renderWithQueryClient(<Popup />)
- // Act - click publish as template button
const publishAsButton = screen.getAllByRole('button').find(btn =>
btn.textContent?.includes('pipeline.common.publishAs'),
)
fireEvent.click(publishAsButton!)
- // Assert - modal should appear
await waitFor(() => {
expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()
})
- // Act - confirm
fireEvent.click(screen.getByTestId('modal-confirm'))
- // Assert - success notification and modal closes
await 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 & Act
renderWithQueryClient(<Publisher />)
- // Click to open popup
fireEvent.click(screen.getByTestId('portal-trigger'))
- // Assert
await waitFor(() => {
expect(screen.getByTestId('portal-content')).toBeInTheDocument()
})
- // Verify sync was called when opening
expect(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.tsx
new file mode 100644
index 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.ts
similarity index 91%
rename from web/app/components/rag-pipeline/hooks/index.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/index.spec.ts
index 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 store
const _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 context
const mockNotify = vi.fn()
vi.mock('@/app/components/base/toast', () => ({
useToastContext: () => ({
@@ -54,7 +37,6 @@ vi.mock('@/app/components/base/toast', () => ({
}),
}))
-// Mock event emitter context
const mockEventEmit = vi.fn()
vi.mock('@/context/event-emitter', () => ({
useEventEmitterContextContext: () => ({
@@ -64,19 +46,16 @@ vi.mock('@/context/event-emitter', () => ({
}),
}))
-// Mock i18n docLink
vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,
}))
-// Mock workflow constants
vi.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/node
vi.mock('@/app/components/workflow/constants/node', () => ({
WORKFLOW_COMMON_NODES: [
{
@@ -90,7 +69,6 @@ vi.mock('@/app/components/workflow/constants/node', () => ({
],
}))
-// Mock data source defaults
vi.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 exports
vi.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 service
const mockExportPipelineConfig = vi.fn()
vi.mock('@/service/use-pipeline', () => ({
useExportPipelineDSL: () => ({
@@ -131,7 +107,6 @@ vi.mock('@/service/use-pipeline', () => ({
}),
}))
-// Mock workflow service
vi.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.ts
similarity index 90%
rename from web/app/components/rag-pipeline/hooks/use-DSL.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts
index 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 dependencies
const 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 downloadBlob
mockLink = {
href: '',
download: '',
@@ -71,7 +58,6 @@ describe('useDSL', () => {
remove: vi.fn(),
}
- // Save original and mock selectively - only intercept 'a' elements
originalCreateElement = 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 downloadBlob
originalAppendChild = 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 URL
mockCreateObjectURL = vi.spyOn(window.URL, 'createObjectURL').mockReturnValue('blob:test-url')
mockRevokeObjectURL = vi.spyOn(window.URL, 'revokeObjectURL').mockImplementation(() => {})
- // Default store state
mockGetState.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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
similarity index 93%
rename from web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts
index 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 reactflow
const mockGetNodes = vi.fn()
const mockStoreGetState = vi.fn()
@@ -22,7 +13,6 @@ vi.mock('reactflow', () => ({
}),
}))
-// Mock workflow store
const mockWorkflowStoreGetState = vi.fn()
vi.mock('@/app/components/workflow/store', () => ({
useWorkflowStore: () => ({
@@ -30,7 +20,6 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-// Mock useNodesReadOnly
const 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 arguments
vi.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 service
const mockSyncWorkflowDraft = vi.fn()
vi.mock('@/service/workflow', () => ({
syncWorkflowDraft: (params: unknown) => mockSyncWorkflowDraft(params),
}))
-// Mock usePipelineRefreshDraft
const mockHandleRefreshWorkflowDraft = vi.fn()
vi.mock('@/app/components/rag-pipeline/hooks', () => ({
usePipelineRefreshDraft: () => ({
@@ -63,26 +49,19 @@ vi.mock('@/app/components/rag-pipeline/hooks', () => ({
}),
}))
-// Mock API_PREFIX
vi.mock('@/config', () => ({
API_PREFIX: '/api',
}))
-// Mock postWithKeepalive from service/fetch
const mockPostWithKeepalive = vi.fn()
vi.mock('@/service/fetch', () => ({
postWithKeepalive: (...args: unknown[]) => mockPostWithKeepalive(...args),
}))
-// ============================================================================
-// Tests
-// ============================================================================
-
describe('useNodesSyncDraft', () => {
beforeEach(() => {
vi.clearAllMocks()
- // Default store state
mockStoreGetState.mockReturnValue({
getNodes: mockGetNodes,
edges: [],
@@ -204,7 +183,6 @@ describe('useNodesSyncDraft', () => {
result.current.syncWorkflowDraftWhenPageClose()
})
- // Should not call postWithKeepalive because after filtering temp nodes, array is empty
expect(mockPostWithKeepalive).not.toHaveBeenCalled()
})
@@ -347,7 +325,6 @@ describe('useNodesSyncDraft', () => {
await result.current.doSyncWorkflowDraft(false)
})
- // Wait for json to be called
await 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 called
await 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.ts
similarity index 92%
rename from web/app/components/rag-pipeline/hooks/use-pipeline-config.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts
index 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 store
const mockUseStore = vi.fn()
const mockWorkflowStoreGetState = vi.fn()
@@ -22,27 +13,20 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-// Mock useWorkflowConfig
const mockUseWorkflowConfig = vi.fn()
vi.mock('@/service/use-workflow', () => ({
useWorkflowConfig: (url: string, callback: (data: unknown) => void) => mockUseWorkflowConfig(url, callback),
}))
-// Mock useDataSourceList
const mockUseDataSourceList = vi.fn()
vi.mock('@/service/use-pipeline', () => ({
useDataSourceList: (enabled: boolean, callback: (data: unknown) => void) => mockUseDataSourceList(enabled, callback),
}))
-// Mock basePath
vi.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 place
expect(dataSourceList[0].declaration.identity.icon).toBe('/base/icon.png')
})
@@ -274,7 +257,6 @@ describe('usePipelineConfig', () => {
capturedCallback?.(dataSourceList)
- // Should not modify object icon
expect(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.ts
similarity index 92%
rename from web/app/components/rag-pipeline/hooks/use-pipeline-init.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts
index 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 store
const 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 context
const mockUseDatasetDetailContextWithSelector = vi.fn()
vi.mock('@/context/dataset-detail', () => ({
useDatasetDetailContextWithSelector: (selector: (state: Record<string, unknown>) => unknown) =>
mockUseDatasetDetailContextWithSelector(selector),
}))
-// Mock workflow service
const 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 succeeds
mockFetchWorkflowDraft.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.ts
similarity index 90%
rename from web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts
index 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 store
const mockWorkflowStoreGetState = vi.fn()
vi.mock('@/app/components/workflow/store', () => ({
useWorkflowStore: () => ({
@@ -20,7 +11,6 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-// Mock useWorkflowUpdate
const mockHandleUpdateWorkflowCanvas = vi.fn()
vi.mock('@/app/components/workflow/hooks', () => ({
useWorkflowUpdate: () => ({
@@ -28,24 +18,18 @@ vi.mock('@/app/components/workflow/hooks', () => ({
}),
}))
-// Mock workflow service
const 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.ts
similarity index 95%
rename from web/app/components/rag-pipeline/hooks/use-pipeline-run.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts
index 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 reactflow
const mockStoreGetState = vi.fn()
const mockGetViewport = vi.fn()
vi.mock('reactflow', () => ({
@@ -26,7 +17,6 @@ vi.mock('reactflow', () => ({
}),
}))
-// Mock workflow store
const mockUseStore = vi.fn()
const mockWorkflowStoreGetState = vi.fn()
const mockWorkflowStoreSetState = vi.fn()
@@ -38,15 +28,13 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-// Mock useNodesSyncDraft
const mockDoSyncWorkflowDraft = vi.fn()
-vi.mock('./use-nodes-sync-draft', () => ({
+vi.mock('../use-nodes-sync-draft', () => ({
useNodesSyncDraft: () => ({
doSyncWorkflowDraft: mockDoSyncWorkflowDraft,
}),
}))
-// Mock workflow hooks
vi.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 service
const 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 FlowType
vi.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 element
const 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 callback
await act(async () => {
capturedCallbacks.onWorkflowStarted?.({ task_id: 'task-1' })
})
@@ -748,7 +728,6 @@ describe('usePipelineRun', () => {
capturedCallbacks.onTextChunk?.({ text: 'chunk' })
})
- // Just verify it doesn't throw
expect(capturedCallbacks.onTextChunk).toBeDefined()
})
@@ -769,7 +748,6 @@ describe('usePipelineRun', () => {
capturedCallbacks.onTextReplace?.({ text: 'replaced' })
})
- // Just verify it doesn't throw
expect(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 callbacks
await act(async () => {
await result.current.handleRun({ inputs: {} })
})
- // Trigger all callbacks - they should not throw even without optional handlers
await 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 called
expect(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.ts
similarity index 90%
rename from web/app/components/rag-pipeline/hooks/use-pipeline-start-run.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-start-run.spec.ts
index 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 store
const 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 interactions
const mockHandleCancelDebugAndPreviewPanel = vi.fn()
vi.mock('@/app/components/workflow/hooks', () => ({
useWorkflowInteractions: () => ({
@@ -31,7 +21,6 @@ vi.mock('@/app/components/workflow/hooks', () => ({
}),
}))
-// Mock useNodesSyncDraft
const 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 handleWorkflowStartRunInWorkflow
expect(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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.tsx
new file mode 100644
index 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.ts
similarity index 94%
rename from web/app/components/rag-pipeline/hooks/use-update-dsl-modal.spec.ts
rename to web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
index 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 values
describe('initial state', () => {
it('should return correct defaults', () => {
const { result } = renderUpdateDSLModal()
@@ -115,7 +105,6 @@ describe('useUpdateDSLModal', () => {
})
})
- // File handling
describe('handleFile', () => {
it('should set currentFile when file is provided', () => {
const { result } = renderUpdateDSLModal()
@@ -142,7 +131,6 @@ describe('useUpdateDSLModal', () => {
})
})
- // Modal state management
describe('modal state', () => {
it('should allow toggling showErrorModal', () => {
const { result } = renderUpdateDSLModal()
@@ -161,7 +149,6 @@ describe('useUpdateDSLModal', () => {
})
})
- // Import flow
describe('handleImport', () => {
it('should call importDSL with correct parameters', async () => {
const { result } = renderUpdateDSLModal()
@@ -191,7 +178,6 @@ describe('useUpdateDSLModal', () => {
expect(mockImportDSL).not.toHaveBeenCalled()
})
- // COMPLETED status
it('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 status
it('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 status
it('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' }))
})
- // Exception
it('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_id
it('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 set
const 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 undefined
await act(async () => {
await (result.current.onUpdateDSLConfirm as unknown as AsyncFn)()
})
@@ -529,7 +507,6 @@ describe('useUpdateDSLModal', () => {
})
})
- // Optional onImport callback
describe('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 throwing
expect(mockOnCancel).toHaveBeenCalled()
})
})
diff --git a/web/app/components/rag-pipeline/store/index.spec.ts b/web/app/components/rag-pipeline/store/__tests__/index.spec.ts
similarity index 65%
rename from web/app/components/rag-pipeline/store/index.spec.ts
rename to web/app/components/rag-pipeline/store/__tests__/index.spec.ts
index 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 function
vi.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 exist
expect(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.ts
similarity index 93%
rename from web/app/components/rag-pipeline/utils/index.spec.ts
rename to web/app/components/rag-pipeline/utils/__tests__/index.spec.ts
index 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 constants
vi.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 = -200
expect(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 = -100
expect(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 = -200
expect(result.viewport).toEqual({
x: 400,
y: -200,
@@ -202,7 +191,6 @@ describe('processNodesWithoutDataSource', () => {
const result = processNodesWithoutDataSource(nodes)
- // Data source empty node position
const 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 added
expect(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 leftNode
expect(result.nodes.length).toBe(4)
})
@@ -317,7 +303,6 @@ describe('processNodesWithoutDataSource', () => {
const result = processNodesWithoutDataSource(nodes)
- // startX = -100 - 400 = -500
expect(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.json
index 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