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(web): replace AP32 owner doubles with real UI behavior (#45342)

Stephen Zhouc00dc71967a9
diff --git a/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
index d5e2b4ddb45..82f227330a0 100644
--- a/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
+++ b/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
@@ -1,102 +1,119 @@
-import { render, screen } from '@testing-library/react'
+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'
+import type { ComponentProps } from 'react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import CreateAppTemplateDialog from '../index'
-// Mock external dependencies (not base components)
-vi.mock('../app-list', () => ({
- default: function MockAppList({
- onCreateFromBlank,
- onClose,
- }: {
- onCreateFromBlank?: () => void
- onClose: () => void
- }) {
- return (
- <div role="region" aria-label="App list">
- <button type="button" onClick={onClose}>
- Success
- </button>
- {onCreateFromBlank && (
- <button type="button" onClick={onCreateFromBlank}>
- Create from Blank
- </button>
- )}
- </div>
- )
+const { importApp, push } = vi.hoisted(() => ({ importApp: vi.fn(), push: vi.fn() }))
+const template: RecommendedAppResponse = {
+ app_id: 'catalog-app',
+ app: {
+ id: 'nested-app',
+ name: 'Template',
+ mode: 'chat',
+ icon_type: 'emoji',
+ icon: '🙂',
+ icon_background: '#fff',
+ icon_url: null,
},
-}))
-
-describe('CreateAppTemplateDialog', () => {
- const defaultProps = {
- show: false,
- onClose: vi.fn(),
- onCreateFromBlank: vi.fn(),
+ can_trial: false,
+ categories: ['Assistant'],
+ description: 'Template description',
+ position: 0,
+}
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push }), useParams: () => ({}) }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'explore.apps.get': () => ({ recommended_apps: [template], categories: ['Assistant'] }),
+ 'explore.apps.byAppId.get': () => ({
+ id: 'catalog-app',
+ name: 'Template',
+ mode: 'chat',
+ can_trial: false,
+ export_data: 'template-dsl',
+ }),
+ 'apps.imports.post': importApp,
+ 'apps.imports.byAppId.checkDependencies.get': () => ({ leaked_dependencies: [] }),
+ }),
}
-
- beforeEach(() => {
- vi.clearAllMocks()
+})
+beforeEach(() => {
+ importApp.mockResolvedValue({
+ id: 'import-1',
+ status: 'completed',
+ app_id: 'created-app',
+ app_mode: 'chat',
+ permission_keys: ['app.edit'],
})
-
- describe('Rendering', () => {
- it('should not render create from blank button when onCreateFromBlank is not provided', () => {
- const { onCreateFromBlank: _onCreateFromBlank, ...propsWithoutOnCreate } = defaultProps
-
- render(<CreateAppTemplateDialog {...propsWithoutOnCreate} show={true} />)
-
- expect(screen.queryByRole('button', { name: 'Create from Blank' })).not.toBeInTheDocument()
- })
+})
+const setup = (props: Partial<ComponentProps<typeof CreateAppTemplateDialog>> = {}) =>
+ render(<CreateAppTemplateDialog show onClose={vi.fn()} {...props} />, {
+ workspacePermissionKeys: ['app.create_and_management'],
})
- describe('Props', () => {
- it('should pass show prop to the dialog shell', () => {
- const { rerender } = render(<CreateAppTemplateDialog {...defaultProps} />)
-
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
-
- rerender(<CreateAppTemplateDialog {...defaultProps} show={true} />)
- expect(screen.getByRole('dialog'))!.toBeInTheDocument()
- })
-
- it('should close from the dialog shell close button', async () => {
- const user = userEvent.setup()
- const mockOnClose = vi.fn()
-
- render(<CreateAppTemplateDialog {...defaultProps} show={true} onClose={mockOnClose} />)
+it('omits create from blank when no callback is available', async () => {
+ setup()
+ await screen.findByTitle('Template')
+ expect(
+ screen.queryByRole('button', { name: 'app.newApp.startFromBlank' }),
+ ).not.toBeInTheDocument()
+})
- const closeButton = screen.getByRole('button', { name: 'Close' })
- expect(closeButton)!.toBeInTheDocument()
+it('opens the template catalog when shown', async () => {
+ const { rerender } = setup({ show: false })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ rerender(<CreateAppTemplateDialog show onClose={vi.fn()} />)
+ expect(await screen.findByTitle('Template')).toBeInTheDocument()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+})
- await user.click(closeButton)
+it('closes from the dialog shell close button', async () => {
+ const user = userEvent.setup()
+ function Scenario() {
+ const [show, setShow] = useState(true)
+ return <CreateAppTemplateDialog show={show} onClose={() => setShow(false)} />
+ }
+ render(<Scenario />)
+ await user.click(screen.getByRole('button', { name: 'Close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+})
- expect(mockOnClose).toHaveBeenCalledTimes(1)
- })
+it('imports the selected template with the edited name and closes the picker', async () => {
+ const user = userEvent.setup()
+ function Scenario() {
+ const [show, setShow] = useState(true)
+ return <CreateAppTemplateDialog show={show} onClose={() => setShow(false)} />
+ }
+ render(<Scenario />, { workspacePermissionKeys: ['app.create_and_management'] })
+ await user.click(await screen.findByRole('button', { name: /^app.newApp.useTemplate/ }))
+ const name = screen.getByRole('textbox', { name: 'app.newApp.name' })
+ await user.clear(name)
+ await user.type(name, 'My assistant')
+ await user.click(screen.getByRole('button', { name: /common.operation.create/ }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(importApp).toHaveBeenCalledExactlyOnceWith({
+ body: expect.objectContaining({ name: 'My assistant', yaml_content: 'template-dsl' }),
})
+})
- describe('User Interactions', () => {
- it('should close when an app is created from the list', async () => {
- const user = userEvent.setup()
- const mockOnClose = vi.fn()
- render(<CreateAppTemplateDialog {...defaultProps} show={true} onClose={mockOnClose} />)
-
- await user.click(screen.getByRole('button', { name: 'Success' }))
-
- expect(mockOnClose).toHaveBeenCalledTimes(1)
- })
-
- it('should call onCreateFromBlank when create from blank is clicked', async () => {
- const user = userEvent.setup()
- const mockOnCreateFromBlank = vi.fn()
- render(
- <CreateAppTemplateDialog
- {...defaultProps}
- show={true}
- onCreateFromBlank={mockOnCreateFromBlank}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: 'Create from Blank' }))
-
- expect(mockOnCreateFromBlank).toHaveBeenCalledTimes(1)
- })
- })
+it('offers the caller create-from-blank action through the real sidebar', async () => {
+ const user = userEvent.setup()
+ function Scenario() {
+ const [blank, setBlank] = useState(false)
+ return blank ? (
+ <p>Blank app form</p>
+ ) : (
+ <CreateAppTemplateDialog show onClose={vi.fn()} onCreateFromBlank={() => setBlank(true)} />
+ )
+ }
+ render(<Scenario />)
+ await user.click(await screen.findByRole('button', { name: 'app.newApp.startFromBlank' }))
+ expect(screen.getByText('Blank app form')).toBeInTheDocument()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
diff --git a/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx b/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx
index 746c5112ff1..7bc9a905ed7 100644
--- a/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx
+++ b/web/app/components/app/text-generate/item/__tests__/workflow-body.spec.tsx
@@ -1,79 +1,62 @@
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
+import { InputVarType } from '@/app/components/workflow/types'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import {
createHumanInputFormFixture,
createWorkflowProcessFixture,
} from '@/test/fixtures/workflow-process'
import WorkflowBody from '../workflow-body'
-const mockSubmit = vi.fn()
+const mockSubmit = vi.fn().mockResolvedValue(undefined)
const mockSwitchTab = vi.fn()
-vi.mock('@/app/components/base/chat/chat/answer/workflow-process', () => ({
- default: () => <div>workflow-process</div>,
-}))
-
-vi.mock('@/app/components/base/chat/chat/answer/human-input-form-list', () => ({
- default: ({ onHumanInputFormSubmit }: { onHumanInputFormSubmit: typeof mockSubmit }) => (
- <button
- onClick={() =>
- onHumanInputFormSubmit('token-1', { inputs: { name: 'dify' }, action: 'submit' })
- }
- >
- submit-human-input
- </button>
- ),
-}))
-
-vi.mock('@/app/components/base/chat/chat/answer/human-input-filled-form-list', () => ({
- default: () => <div>filled-human-input</div>,
-}))
-
-vi.mock('../result-tab', () => ({
- default: ({ currentTab }: { currentTab: string }) => <div>{`result-tab:${currentTab}`}</div>,
-}))
+const form = createHumanInputFormFixture({
+ form_content: 'Name: {{#$output.name#}}',
+ inputs: [
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'name',
+ default: { type: 'constant', value: '', selector: [] },
+ },
+ ],
+ actions: [{ id: 'submit', title: 'Submit', button_style: UserActionButtonType.Primary }],
+})
describe('WorkflowBody', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
it('should render workflow information and allow tab switching', async () => {
const user = userEvent.setup()
- render(
- <WorkflowBody
- content="detail"
- currentTab="RESULT"
- depth={2}
- isError={false}
- onSubmitHumanInputForm={mockSubmit}
- onSwitchTab={mockSwitchTab}
- showResultTabs
- siteInfo={{ title: 'Test app', show_workflow_steps: true }}
- taskId="task-1"
- workflowProcessData={createWorkflowProcessFixture({
- resultText: 'done',
- humanInputFormDataList: [createHumanInputFormFixture()],
- humanInputFilledFormDataList: [
- {
- form_id: 'filled-form-1',
- node_id: 'filled-1',
- node_title: 'Human Input',
- rendered_content: '',
- action_id: 'submit',
- action_text: 'Submit',
- },
- ],
- })}
- />,
- )
+ function Scenario() {
+ const [tab, setTab] = useState('RESULT')
+ return (
+ <WorkflowBody
+ content="detail"
+ currentTab={tab}
+ depth={2}
+ isError={false}
+ onSubmitHumanInputForm={mockSubmit}
+ onSwitchTab={setTab}
+ showResultTabs
+ siteInfo={{ title: 'Test app', show_workflow_steps: true }}
+ taskId="task-1"
+ workflowProcessData={createWorkflowProcessFixture({
+ resultText: 'done',
+ })}
+ />
+ )
+ }
+ render(<Scenario />)
- expect(screen.getByText('workflow-process')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /workflowProcessSucceeded/ })).toBeInTheDocument()
expect(screen.getByText('task-1-1')).toBeInTheDocument()
- expect(screen.getByText('result-tab:RESULT')).toBeInTheDocument()
+ expect(await screen.findByText('done')).toBeInTheDocument()
await user.click(screen.getByText(/(?:^|\.)detail(?=$|:)/))
- expect(mockSwitchTab).toHaveBeenCalledWith('DETAIL')
+ expect(screen.queryByText('done')).not.toBeInTheDocument()
+ expect(screen.getByRole('textbox')).toHaveAttribute('readonly')
+ expect(screen.getByRole('textbox')).toHaveValue(JSON.stringify('detail', null, 2))
})
it('should forward human input submissions', async () => {
@@ -90,12 +73,13 @@ describe('WorkflowBody', () => {
siteInfo={null}
workflowProcessData={createWorkflowProcessFixture({
resultText: 'done',
- humanInputFormDataList: [createHumanInputFormFixture()],
+ humanInputFormDataList: [form],
})}
/>,
)
- await user.click(screen.getByText('submit-human-input'))
+ await user.type(screen.getByRole('textbox'), 'dify')
+ await user.click(screen.getByRole('button', { name: 'Submit' }))
expect(mockSubmit).toHaveBeenCalledWith('token-1', {
action: 'submit',
diff --git a/web/app/components/base/agent-log-modal/__tests__/result.spec.tsx b/web/app/components/base/agent-log-modal/__tests__/result.spec.tsx
index 1cceeb2ef50..8a7d645abc8 100644
--- a/web/app/components/base/agent-log-modal/__tests__/result.spec.tsx
+++ b/web/app/components/base/agent-log-modal/__tests__/result.spec.tsx
@@ -1,18 +1,7 @@
import { screen } from '@testing-library/react'
-import * as React from 'react'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import ResultPanel from '../result'
-// Code editing is independently covered; keep the status widget real to verify API status mapping.
-vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
- default: ({ title, value }: { title: React.ReactNode; value: string | object }) => (
- <div data-testid="code-editor">
- <div data-testid="code-editor-title">{title}</div>
- <div data-testid="code-editor-value">{JSON.stringify(value)}</div>
- </div>
- ),
-}))
-
vi.mock('@/hooks/use-timestamp', () => ({
default: () => ({
formatTime: vi.fn((ts, _format) => `formatted-${ts}`),
@@ -39,8 +28,12 @@ describe('ResultPanel', () => {
expect(screen.getByText('INPUT')).toBeInTheDocument()
expect(screen.getByText('OUTPUT')).toBeInTheDocument()
- expect(screen.getByText(JSON.stringify(mockProps.inputs))).toBeInTheDocument()
- expect(screen.getByText(JSON.stringify(mockProps.outputs))).toBeInTheDocument()
+ const editors = screen.getAllByRole('textbox') as HTMLTextAreaElement[]
+ expect(editors.map((editor) => JSON.parse(editor.value))).toEqual([
+ mockProps.inputs,
+ mockProps.outputs,
+ ])
+ editors.forEach((editor) => expect(editor).toHaveAttribute('readonly'))
expect(screen.getByText('User Name')).toBeInTheDocument()
expect(screen.getByRole('status')).toHaveTextContent('appLog.status.succeeded')
expect(screen.getByRole('status')).toHaveTextContent('1.235s')
diff --git a/web/app/components/base/chat/chat/__tests__/index.spec.tsx b/web/app/components/base/chat/chat/__tests__/index.spec.tsx
index d583230d175..fe449f72885 100644
--- a/web/app/components/base/chat/chat/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat/__tests__/index.spec.tsx
@@ -5,24 +5,6 @@ import userEvent from '@testing-library/user-event'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import Chat from '../index'
-// Keep answer rendering at the component boundary; exercise real questions,
-// suggestions and input controls through Chat's shared context.
-vi.mock('../answer', () => ({
- default: ({
- item,
- responding,
- question,
- }: {
- item: ChatItem
- responding?: boolean
- question: string
- }) => (
- <article aria-label={`Answer to ${question}`} aria-busy={!!responding}>
- {item.content}
- </article>
- ),
-}))
-
vi.mock('@/next/navigation', () => ({
useParams: () => ({}),
usePathname: () => '/chat',
@@ -82,7 +64,7 @@ describe('Chat', () => {
})
})
- it('renders conversation order and marks only the latest answer as responding', async () => {
+ it('renders conversation order and enables answer actions after streaming ends', async () => {
const chatList = [
makeChatItem({ id: 'q1', content: 'First question' }),
makeChatItem({ id: 'a1', content: 'First answer', isAnswer: true }),
@@ -92,19 +74,14 @@ describe('Chat', () => {
const { rerender } = renderChat({ chatList, isResponding: true })
expect(await screen.findByText('First question')).toBeInTheDocument()
expect(screen.getByText('Second question')).toBeInTheDocument()
- const answers = screen.getAllByRole('article')
- expect(answers.map((answer) => answer.textContent)).toEqual(['First answer', 'Second answer'])
- expect(answers[0]).toHaveAccessibleName('Answer to First question')
- expect(answers[1]).toHaveAccessibleName('Answer to Second question')
- expect(answers[0]).toHaveAttribute('aria-busy', 'false')
- expect(answers[1]).toHaveAttribute('aria-busy', 'true')
+ const firstAnswer = await screen.findByText('First answer')
+ const secondAnswer = await screen.findByText('Second answer')
+ expect(firstAnswer.compareDocumentPosition(secondAnswer)).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
+ // Two question copy controls plus only the completed answer's action.
+ expect(screen.getAllByRole('button', { name: 'common.operation.copy' })).toHaveLength(3)
rerender(<Chat chatList={chatList} isResponding={false} />)
- expect(
- screen
- .getAllByRole('article')
- .every((answer) => answer.getAttribute('aria-busy') === 'false'),
- ).toBe(true)
+ expect(screen.getAllByRole('button', { name: 'common.operation.copy' })).toHaveLength(4)
})
it('sends a typed message without requiring upload configuration', async () => {
diff --git a/web/app/components/base/message-log-modal/__tests__/index.spec.tsx b/web/app/components/base/message-log-modal/__tests__/index.spec.tsx
index 889d22ba400..34822717f19 100644
--- a/web/app/components/base/message-log-modal/__tests__/index.spec.tsx
+++ b/web/app/components/base/message-log-modal/__tests__/index.spec.tsx
@@ -1,14 +1,60 @@
-import type { ComponentProps } from 'react'
-import type Run from '@/app/components/workflow/run'
-import { render, screen } from '@testing-library/react'
+import type { WorkflowRunDetailResponse } from '@/models/log'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { createNodeTracing } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'
import MessageLogModal from '../index'
-const run = vi.hoisted(() => vi.fn<(_props: ComponentProps<typeof Run>) => null>(() => null))
-// The run viewer is independently tested; this owner selects its run and tab.
-vi.mock('@/app/components/workflow/run', () => ({
- default: (props: ComponentProps<typeof Run>) => run(props),
+const { fetchRunDetail, fetchTracingList } = vi.hoisted(() => ({
+ fetchRunDetail: vi.fn(),
+ fetchTracingList: vi.fn(),
}))
+vi.mock('@/service/log', () => ({ fetchRunDetail, fetchTracingList }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.traceRuns.bySourceKind.bySourceId.get': () => ({ status: 'not_collected' }),
+ }),
+ }
+})
+beforeEach(() => {
+ fetchRunDetail.mockImplementation(async (url: string): Promise<WorkflowRunDetailResponse> => {
+ if (
+ url !== '/apps/inspected-app/workflow-runs/run-1' &&
+ url !== '/apps/app-1/workflow-runs/run-1'
+ )
+ throw new Error(`Unexpected detail: ${url}`)
+ return {
+ id: 'run-1',
+ version: '1',
+ graph: { nodes: [], edges: [] },
+ inputs: '{}',
+ inputs_truncated: false,
+ outputs: 'message output',
+ outputs_truncated: false,
+ status: 'succeeded',
+ elapsed_time: 1,
+ total_tokens: 3,
+ total_steps: 1,
+ created_by_role: 'account',
+ created_by_account: { id: 'user', name: 'Alice', email: '[email protected]' },
+ created_at: 1710000000,
+ finished_at: 1710000001,
+ }
+ })
+ fetchTracingList.mockImplementation(async ({ url }: { url: string }) => {
+ if (
+ url !== '/apps/inspected-app/workflow-runs/run-1/node-executions' &&
+ url !== '/apps/app-1/workflow-runs/run-1/node-executions'
+ )
+ throw new Error(`Unexpected tracing: ${url}`)
+ return { data: [createNodeTracing({ title: 'Message execution' })] }
+ })
+})
const log = { id: 'message-1', content: 'Message', isAnswer: true, workflow_run_id: 'run-1' }
it.each([undefined, { ...log, workflow_run_id: undefined }])(
@@ -23,7 +69,8 @@ it.each([undefined, { ...log, workflow_run_id: undefined }])(
/>,
)
expect(container).toBeEmptyDOMElement()
- expect(run).not.toHaveBeenCalled()
+ expect(fetchRunDetail).not.toHaveBeenCalled()
+ expect(fetchTracingList).not.toHaveBeenCalled()
},
)
@@ -32,27 +79,41 @@ it.each([false, true])(
async (fixedWidth) => {
const user = userEvent.setup()
const onCancel = vi.fn()
- render(
- <MessageLogModal
- appId="inspected-app"
- width={800}
- onCancel={onCancel}
- currentLogItem={log}
- defaultTab="TRACING"
- fixedWidth={fixedWidth}
- />,
+ function Viewer() {
+ const [open, setOpen] = useState(true)
+ return (
+ open && (
+ <MessageLogModal
+ appId="inspected-app"
+ width={800}
+ onCancel={() => {
+ onCancel()
+ setOpen(false)
+ }}
+ currentLogItem={log}
+ defaultTab="TRACING"
+ fixedWidth={fixedWidth}
+ />
+ )
+ )
+ }
+ render(<Viewer />)
+ expect(screen.getByRole('tab', { name: 'runLog.tracing' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
)
- expect(run).toHaveBeenLastCalledWith(
- expect.objectContaining({
- appId: 'inspected-app',
- activeTab: 'TRACING',
- hideResult: true,
- runDetailUrl: '/apps/inspected-app/workflow-runs/run-1',
- tracingListUrl: '/apps/inspected-app/workflow-runs/run-1/node-executions',
- }),
+ expect(screen.queryByRole('tab', { name: 'runLog.result' })).not.toBeInTheDocument()
+ expect(await screen.findByText('Message execution')).toBeInTheDocument()
+ expect(fetchRunDetail).toHaveBeenCalledWith('/apps/inspected-app/workflow-runs/run-1', {
+ silent: true,
+ })
+ expect(fetchTracingList).toHaveBeenCalledWith(
+ { url: '/apps/inspected-app/workflow-runs/run-1/node-executions' },
+ { silent: true },
)
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
expect(onCancel).toHaveBeenCalledTimes(1)
+ expect(screen.queryByText('Message execution')).not.toBeInTheDocument()
},
)
diff --git a/web/app/components/plugins/plugin-page/__tests__/debug-info.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/debug-info.spec.tsx
index 912d7fc312e..ce5cc21512b 100644
--- a/web/app/components/plugins/plugin-page/__tests__/debug-info.spec.tsx
+++ b/web/app/components/plugins/plugin-page/__tests__/debug-info.spec.tsx
@@ -1,69 +1,55 @@
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import DebugInfo from '../debug-info'
vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.example.com${path}`,
}))
-const mockDebugKey = vi.hoisted(() => ({
- data: null as null | { key: string; host: string; port: number },
- isLoading: false,
-}))
-
-vi.mock('@/service/use-plugins', () => ({
- useDebugKey: () => mockDebugKey,
-}))
-
-vi.mock('../../base/key-value-item', () => ({
- default: ({
- label,
- value,
- maskedValue,
- }: {
- label: string
- value: string
- maskedValue?: string
- }) => (
- <div data-testid={`kv-${label}`}>
- {label}:{maskedValue || value}
- </div>
- ),
-}))
+const debugKey = vi.hoisted(() => vi.fn())
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.plugin.debuggingKey.get': debugKey,
+ }),
+ }
+})
describe('DebugInfo', () => {
beforeEach(() => {
- vi.clearAllMocks()
- mockDebugKey.data = null
- mockDebugKey.isLoading = false
+ debugKey.mockResolvedValue(null)
})
it('renders nothing while the debug key is loading', () => {
- mockDebugKey.isLoading = true
+ debugKey.mockReturnValue(new Promise(() => {}))
const { container } = render(<DebugInfo />)
expect(container.innerHTML).toBe('')
})
- it('renders a disabled trigger when debug info is unavailable', () => {
+ it('renders a disabled trigger when debug info is unavailable', async () => {
render(<DebugInfo />)
- const trigger = screen.getByRole('button', { name: 'plugin.debugInfo.title' })
+ const trigger = await screen.findByRole('button', { name: 'plugin.debugInfo.title' })
expect(trigger).toBeDisabled()
})
it('opens a popover with debug metadata and masks the key when info is available', async () => {
- mockDebugKey.data = {
+ debugKey.mockResolvedValue({
host: '127.0.0.1',
port: 5001,
key: '12345678abcdefghijklmnopqrst87654321',
- }
+ })
const user = userEvent.setup()
render(<DebugInfo />)
- const trigger = screen.getByRole('button', { name: 'plugin.debugInfo.title' })
+ const trigger = await screen.findByRole('button', { name: 'plugin.debugInfo.title' })
expect(trigger).toBeEnabled()
// Popover is closed initially — content not rendered yet
@@ -76,7 +62,8 @@ describe('DebugInfo', () => {
'href',
'https://docs.example.com/develop-plugin/features-and-specs/plugin-types/remote-debug-a-plugin',
)
- expect(screen.getByTestId('kv-Port')).toHaveTextContent('Port:127.0.0.1:5001')
- expect(screen.getByTestId('kv-Key')).toHaveTextContent('Key:12345678********87654321')
+ expect(screen.getByRole('group', { name: 'Port' })).toHaveTextContent('127.0.0.1:5001')
+ expect(screen.getByRole('group', { name: 'Key' })).toHaveTextContent('12345678********87654321')
+ expect(screen.queryByText('12345678abcdefghijklmnopqrst87654321')).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/workflow/comment/comment-input.spec.tsx b/web/app/components/workflow/comment/comment-input.spec.tsx
index 7e252756258..89cc65e04a5 100644
--- a/web/app/components/workflow/comment/comment-input.spec.tsx
+++ b/web/app/components/workflow/comment/comment-input.spec.tsx
@@ -2,21 +2,12 @@ import type { ReactElement } from 'react'
import { fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { createAccountProfileQueryWrapper } from '@/test/console/account-profile'
-import { render as renderWithConsoleState } from '@/test/console/render'
+import { describe, expect, it, vi } from 'vite-plus/test'
+import { seedAccountProfileQuery } from '@/test/console/account-profile'
+import { createConsoleQueryClient } from '@/test/console/query-data'
+import { renderWorkflowComponent } from '../__tests__/workflow-test-env'
import { CommentInput } from './comment-input'
-type MentionInputProps = {
- value: string
- onChange: (value: string) => void
- onSubmit: (content: string, mentionedUserIds: string[]) => void
- placeholder?: string
- disabled?: boolean
- autoFocus?: boolean
- className?: string
-}
-
const mockConsoleState = vi.hoisted(() => ({
userProfile: {
id: 'user-1',
@@ -25,37 +16,21 @@ const mockConsoleState = vi.hoisted(() => ({
},
}))
-const render = (ui: ReactElement) =>
- renderWithConsoleState(ui, {
- wrapper: createAccountProfileQueryWrapper(mockConsoleState.userProfile),
+const render = (ui: ReactElement) => {
+ const queryClient = createConsoleQueryClient()
+ seedAccountProfileQuery(queryClient, mockConsoleState.userProfile)
+ return renderWorkflowComponent(ui, {
+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
+ queryClient,
+ initialStoreState: {
+ mentionableUsersCache: {
+ 'app-1': [{ id: 'user-2', name: 'Bob', email: '[email protected]', avatar_url: '' }],
+ },
+ },
})
-
-// Mention parsing is independently tested; retain the owner's controlled draft and reset behavior.
-vi.mock('./mention-input', () => ({
- MentionInput: (props: MentionInputProps) => (
- <>
- <textarea
- aria-label="Comment draft"
- value={props.value}
- disabled={props.disabled}
- onChange={(event) => props.onChange(event.target.value)}
- />
- <button
- type="button"
- disabled={props.disabled}
- onClick={() => props.onSubmit(props.value, ['user-2'])}
- >
- Submit mention
- </button>
- </>
- ),
-}))
+}
describe('CommentInput', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
it('moves the draft using a focused handle and finishes moving with Enter', async () => {
const user = userEvent.setup()
const onPositionChange = vi.fn()
@@ -63,6 +38,7 @@ describe('CommentInput', () => {
const [position, setPosition] = useState({ x: 100, y: 100 })
return (
<CommentInput
+ autoFocus={false}
position={position}
onCancel={vi.fn()}
onSubmit={vi.fn()}
@@ -74,8 +50,8 @@ describe('CommentInput', () => {
)
}
render(<Draft />)
- await user.tab()
const handle = screen.getByRole('button', { name: 'workflow.keyboard.moveDraftComment' })
+ handle.focus()
await user.keyboard('{Enter}{ArrowRight}{Shift>}{ArrowDown}{/Shift}')
expect(onPositionChange).toHaveBeenLastCalledWith(
expect.objectContaining({ elementX: 105, elementY: 120 }),
@@ -85,7 +61,7 @@ describe('CommentInput', () => {
expect(handle).toHaveAttribute('aria-pressed', 'false')
expect(onPositionChange).toHaveBeenCalledTimes(2)
await user.tab()
- expect(screen.getByRole('textbox', { name: 'Comment draft' })).toHaveFocus()
+ expect(screen.getByRole('textbox')).toHaveFocus()
})
it('does not offer keyboard movement while disabled', () => {
@@ -110,21 +86,23 @@ describe('CommentInput', () => {
fireEvent.keyDown(document, { key: 'Escape' })
expect(onCancel).not.toHaveBeenCalled()
- fireEvent.keyDown(screen.getByRole('textbox', { name: 'Comment draft' }), { key: 'Escape' })
+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Escape' })
expect(onCancel).toHaveBeenCalledTimes(1)
})
- it('submits the draft and clears it after the mention editor reports submission', async () => {
+ it('submits the real mention and clears the draft', async () => {
const onSubmit = vi.fn()
render(<CommentInput position={{ x: 0, y: 0 }} onSubmit={onSubmit} onCancel={vi.fn()} />)
const user = userEvent.setup()
- await user.type(screen.getByRole('textbox', { name: 'Comment draft' }), 'Hello')
- await user.click(screen.getByRole('button', { name: 'Submit mention' }))
+ await user.type(screen.getByRole('textbox'), '@Bo')
+ await user.click(await screen.findByText('[email protected]'))
+ await user.type(screen.getByRole('textbox'), 'Hello')
+ await user.click(screen.getByRole('button', { name: 'common.operation.send' }))
- expect(onSubmit).toHaveBeenCalledWith('Hello', ['user-2'])
- expect(screen.getByRole('textbox', { name: 'Comment draft' })).toHaveValue('')
+ expect(onSubmit).toHaveBeenCalledWith('@Bob Hello', ['user-2'])
+ expect(screen.getByRole('textbox')).toHaveValue('')
})
})
diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx
index edbd4931450..43510774618 100644
--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx
@@ -1,259 +1,120 @@
+import type { ComponentProps } from 'react'
import { act, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'
+import { useState } from 'react'
+import { createNodeTracing } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowComponent as render } from '@/app/components/workflow/__tests__/workflow-test-env'
import { NodeRunningStatus } from '@/app/components/workflow/types'
import { createHttpError } from '@/service/http-error'
+import { createDeferred } from '@/test/deferred'
import LastRun from '../index'
-const mockUseLastRun = vi.hoisted(() => vi.fn())
-const mockResultPanel = vi.hoisted(() => vi.fn())
-
-vi.mock('@remixicon/react', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@remixicon/react')>()),
- RiLoader2Line: () => <div data-testid="loading-icon" />,
-}))
-
-vi.mock('@/service/use-workflow', () => ({
- useLastRun: (...args: unknown[]) => mockUseLastRun(...args),
-}))
-
-vi.mock('@/app/components/workflow/run/result-panel', () => ({
- __esModule: true,
- default: (props: Record<string, unknown>) => {
- mockResultPanel(props)
- return <div data-testid="result-panel">{String(props.status)}</div>
- },
-}))
-
-describe('LastRun', () => {
- const updateNodeRunningStatus = vi.fn()
- const onSingleRunClicked = vi.fn()
- let visibilityState = 'visible'
- const originalVisibility = Object.getOwnPropertyDescriptor(document, 'visibilityState')
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseLastRun.mockReturnValue({
- data: undefined,
- isFetching: false,
- error: undefined,
- })
- visibilityState = 'visible'
- Object.defineProperty(document, 'visibilityState', {
- configurable: true,
- get: () => visibilityState,
- })
- })
-
- afterEach(() => {
- if (originalVisibility) Object.defineProperty(document, 'visibilityState', originalVisibility)
- else Reflect.deleteProperty(document, 'visibilityState')
- })
-
- it('should show a loader while fetching the last run before any single run starts', () => {
- mockUseLastRun.mockReturnValue({
- data: undefined,
- isFetching: true,
- error: undefined,
- })
-
- render(
- <LastRun
- nodeId="node-1"
- canSingleRun
- isRunAfterSingleRun={false}
- updateNodeRunningStatus={updateNodeRunningStatus}
- onSingleRunClicked={onSingleRunClicked}
- />,
- { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
- )
-
- expect(screen.getByTestId('loading-icon')).toBeInTheDocument()
- expect(screen.queryByTestId('result-panel')).not.toBeInTheDocument()
- })
-
- it('should show a running result panel while a single run is still executing', () => {
- render(
- <LastRun
- nodeId="node-1"
- canSingleRun
- isRunAfterSingleRun
- updateNodeRunningStatus={updateNodeRunningStatus}
- onSingleRunClicked={onSingleRunClicked}
- runningStatus={NodeRunningStatus.Running}
- />,
- { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
- )
+const lastRun = vi.hoisted(() => vi.fn())
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflows.draft.nodes.byNodeId.lastRun.get': lastRun,
+ }),
+ }
+})
- expect(screen.getByTestId('result-panel')).toHaveTextContent('running')
- expect(mockResultPanel).toHaveBeenCalledWith(
- expect.objectContaining({
- status: 'running',
- showSteps: false,
- }),
- )
+const result = createNodeTracing({
+ outputs: { answer: 'Saved answer' },
+ execution_metadata: { total_tokens: 9, total_price: 0, currency: 'USD' },
+})
+const props = {
+ nodeId: 'node-1',
+ canSingleRun: true,
+ isRunAfterSingleRun: true,
+ updateNodeRunningStatus: vi.fn(),
+ onSingleRunClicked: vi.fn(),
+}
+const setup = (overrides: Partial<ComponentProps<typeof LastRun>> = {}) =>
+ render(<LastRun {...props} {...overrides} />, {
+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
})
-
- it('should render the no-data state for 404 last-run responses and forward single-run clicks', async () => {
- const user = userEvent.setup()
- mockUseLastRun.mockReturnValue({
- data: undefined,
- isFetching: false,
- error: createHttpError(new Response(null, { status: 404 })),
- })
-
- render(
- <LastRun
- nodeId="node-1"
- canSingleRun
- isRunAfterSingleRun={false}
- updateNodeRunningStatus={updateNodeRunningStatus}
- onSingleRunClicked={onSingleRunClicked}
- />,
- { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
- )
-
- await user.click(screen.getByRole('button', { name: 'workflowDebug.debug.noData.runThisNode' }))
-
- expect(onSingleRunClicked).toHaveBeenCalledTimes(1)
+let visibilityState = 'visible'
+const originalVisibility = Object.getOwnPropertyDescriptor(document, 'visibilityState')
+beforeEach(() => {
+ lastRun.mockResolvedValue(result)
+ visibilityState = 'visible'
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => visibilityState,
})
-
- it('should render resolved result data and let paused state override the final status', () => {
- mockUseLastRun.mockReturnValue({
- data: {
- status: NodeRunningStatus.Succeeded,
- execution_metadata: { total_tokens: 9 },
- created_by_account: { created_by: 'Alice' },
- },
- isFetching: false,
- error: undefined,
- })
-
- render(
- <LastRun
- nodeId="node-1"
- canSingleRun
- isRunAfterSingleRun
- updateNodeRunningStatus={updateNodeRunningStatus}
- onSingleRunClicked={onSingleRunClicked}
- runningStatus={NodeRunningStatus.Succeeded}
- isPaused
- />,
- { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
- )
-
- expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Stopped)
- expect(mockResultPanel).toHaveBeenCalledWith(
- expect.objectContaining({
- status: NodeRunningStatus.Stopped,
- total_tokens: 9,
- created_by: 'Alice',
- showSteps: false,
- }),
- )
+})
+afterEach(() => {
+ if (originalVisibility) Object.defineProperty(document, 'visibilityState', originalVisibility)
+ else Reflect.deleteProperty(document, 'visibilityState')
+})
+const changeVisibility = (value: string) =>
+ act(() => {
+ visibilityState = value
+ document.dispatchEvent(new Event('visibilitychange'))
})
- it('should respect stopped and listening one-step statuses', () => {
- mockUseLastRun.mockReturnValue({
- data: {
- status: NodeRunningStatus.Succeeded,
- },
- isFetching: false,
- error: undefined,
- })
-
- const { rerender } = render(
- <LastRun
- nodeId="node-1"
- canSingleRun
- isRunAfterSingleRun
- updateNodeRunningStatus={updateNodeRunningStatus}
- onSingleRunClicked={onSingleRunClicked}
- runningStatus={NodeRunningStatus.Stopped}
- />,
- { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
- )
+it('waits for the selected node last run before showing its saved output', async () => {
+ const pending = createDeferred<typeof result>()
+ lastRun.mockReturnValue(pending.promise)
+ setup({ isRunAfterSingleRun: false })
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
+ await act(async () => pending.resolve(result))
+ expect(await screen.findByDisplayValue(/Saved answer/)).toHaveAttribute('readonly')
+ expect(lastRun).toHaveBeenCalledWith({ params: { app_id: 'app-1', node_id: 'node-1' } })
+})
- expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Stopped)
+it('shows the actual running status before the single run completes', () => {
+ setup({ runningStatus: NodeRunningStatus.Running })
+ expect(screen.getByRole('status')).toHaveTextContent('appLog.status.running')
+ expect(lastRun).not.toHaveBeenCalled()
+})
- rerender(
- <LastRun
- nodeId="node-1"
- canSingleRun
- isRunAfterSingleRun
- updateNodeRunningStatus={updateNodeRunningStatus}
- onSingleRunClicked={onSingleRunClicked}
- runningStatus={NodeRunningStatus.Listening}
- />,
- )
+it('offers single run for a missing last run', async () => {
+ lastRun.mockRejectedValue(createHttpError(new Response(null, { status: 404 })))
+ const user = userEvent.setup()
+ setup({ isRunAfterSingleRun: false })
+ await user.click(
+ await screen.findByRole('button', { name: 'workflowDebug.debug.noData.runThisNode' }),
+ )
+ expect(props.onSingleRunClicked).toHaveBeenCalledOnce()
+})
- expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Listening)
- })
+it('shows saved execution data while paused overrides its completed status', async () => {
+ setup({ runningStatus: NodeRunningStatus.Succeeded, isPaused: true })
+ expect(await screen.findByDisplayValue(/Saved answer/)).toHaveAttribute('readonly')
+ expect(screen.getByRole('status')).toHaveTextContent('appLog.status.stopped')
+ expect(screen.getByRole('status')).toHaveTextContent('9 Tokens')
+})
- it('should react to page visibility changes while keeping the current result rendered', () => {
- mockUseLastRun.mockReturnValue({
- data: {
- status: NodeRunningStatus.Succeeded,
- },
- isFetching: false,
- error: undefined,
- })
+it('respects a stopped single-run status', () => {
+ setup({ runningStatus: NodeRunningStatus.Stopped })
+ expect(screen.getByRole('status')).toHaveTextContent('appLog.status.stopped')
+})
- render(
- <LastRun
- nodeId="node-1"
- canSingleRun
- isRunAfterSingleRun
- updateNodeRunningStatus={updateNodeRunningStatus}
- onSingleRunClicked={onSingleRunClicked}
- runningStatus={NodeRunningStatus.Succeeded}
- />,
- { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },
+it('restores a completed status after hiding the page loses transient canvas state', async () => {
+ function Scenario({ status }: { status: NodeRunningStatus }) {
+ const [restoredStatus, setRestoredStatus] = useState<NodeRunningStatus>()
+ return (
+ <>
+ <output aria-label="Restored node status">{restoredStatus}</output>
+ <LastRun {...props} runningStatus={status} updateNodeRunningStatus={setRestoredStatus} />
+ </>
)
-
- act(() => {
- visibilityState = 'hidden'
- document.dispatchEvent(new Event('visibilitychange'))
- visibilityState = 'visible'
- document.dispatchEvent(new Event('visibilitychange'))
- })
-
- expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Succeeded)
- })
-
- it('should restore a completed last run when refreshing the canvas loses its transient status', () => {
- mockUseLastRun.mockReturnValue({
- data: {
- status: NodeRunningStatus.Succeeded,
- },
- isFetching: false,
- error: undefined,
- })
-
- const props = {
- nodeId: 'node-1',
- canSingleRun: true,
- isRunAfterSingleRun: true,
- updateNodeRunningStatus,
- onSingleRunClicked,
- }
- const { rerender } = render(<LastRun {...props} runningStatus={NodeRunningStatus.Running} />, {
- resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
- })
- rerender(<LastRun {...props} runningStatus={NodeRunningStatus.Succeeded} />)
-
- act(() => {
- visibilityState = 'hidden'
- document.dispatchEvent(new Event('visibilitychange'))
- })
- rerender(<LastRun {...props} runningStatus={NodeRunningStatus.NotStart} />)
- expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Succeeded)
-
- act(() => {
- visibilityState = 'visible'
- document.dispatchEvent(new Event('visibilitychange'))
- })
-
- expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Succeeded)
- expect(updateNodeRunningStatus).toHaveBeenCalledWith(NodeRunningStatus.Succeeded)
+ }
+ const { rerender } = render(<Scenario status={NodeRunningStatus.Running} />, {
+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
})
+ rerender(<Scenario status={NodeRunningStatus.Succeeded} />)
+ expect(await screen.findByDisplayValue(/Saved answer/)).toBeInTheDocument()
+ changeVisibility('hidden')
+ rerender(<Scenario status={NodeRunningStatus.NotStart} />)
+ expect(screen.getByRole('status', { name: 'Restored node status' })).toBeEmptyDOMElement()
+ changeVisibility('visible')
+ expect(screen.getByRole('status', { name: 'Restored node status' })).toHaveTextContent(
+ 'succeeded',
+ )
+ expect(screen.getByDisplayValue(/Saved answer/)).toBeInTheDocument()
})
diff --git a/web/app/components/workflow/run/__tests__/result-panel.spec.tsx b/web/app/components/workflow/run/__tests__/result-panel.spec.tsx
index f59c3feebdb..0c6fadff81d 100644
--- a/web/app/components/workflow/run/__tests__/result-panel.spec.tsx
+++ b/web/app/components/workflow/run/__tests__/result-panel.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import type { AgentLogItemWithChildren, NodeTracing } from '@/types/workflow'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -6,20 +5,6 @@ import { renderWorkflowComponent as render } from '../../__tests__/workflow-test
import { BlockEnum, NodeRunningStatus } from '../../types'
import ResultPanel from '../result-panel'
-vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
- __esModule: true,
- default: (props: { title: ReactNode; value: unknown; footer?: ReactNode; tip?: ReactNode }) => {
- return (
- <section data-testid="code-editor">
- <div>{props.title}</div>
- <div>{typeof props.value === 'string' ? props.value : JSON.stringify(props.value)}</div>
- {props.tip}
- {props.footer}
- </section>
- )
- },
-}))
-
const createNodeInfo = (overrides: Partial<NodeTracing> = {}): NodeTracing => ({
id: 'trace-node-1',
index: 0,
@@ -104,7 +89,14 @@ describe('ResultPanel', () => {
expect(screen.getByText('WORKFLOW.COMMON.INPUT')).toBeInTheDocument()
expect(screen.getByText('WORKFLOW.COMMON.PROCESSDATA')).toBeInTheDocument()
expect(screen.getByText('WORKFLOW.COMMON.OUTPUT')).toBeInTheDocument()
- expect(screen.getByText('{"answer":"done"}')).toBeInTheDocument()
+ const editors = screen.getAllByRole('textbox') as HTMLTextAreaElement[]
+ const values = editors.map((editor) => {
+ const value = JSON.parse(editor.value)
+ // Accept either serialized JSON inputs or already-decoded data.
+ return typeof value === 'string' ? JSON.parse(value) : value
+ })
+ expect(values).toEqual([{ topic: 'AI' }, { step: 1 }, { answer: 'done' }])
+ editors.forEach((editor) => expect(editor).toHaveAttribute('readonly'))
expect(
screen.getAllByText('workflowDebug.debug.variableInspect.largeDataNoExport'),
).toHaveLength(3)
diff --git a/web/app/components/workflow/run/loop-log/__tests__/loop-result-panel.spec.tsx b/web/app/components/workflow/run/loop-log/__tests__/loop-result-panel.spec.tsx
index ecedddaf4d6..17854118deb 100644
--- a/web/app/components/workflow/run/loop-log/__tests__/loop-result-panel.spec.tsx
+++ b/web/app/components/workflow/run/loop-log/__tests__/loop-result-panel.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NodeRunningStatus } from '@/app/components/workflow/types'
@@ -6,15 +5,6 @@ import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createNodeTracing } from '../../../__tests__/fixtures'
import LoopResultPanel from '../loop-result-panel'
-vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
- default: ({ title, value }: { title: ReactNode; value: unknown }) => (
- <section>
- {title}
- <output aria-label="Loop variables">{JSON.stringify(value)}</output>
- </section>
- ),
-}))
-
it('expands and collapses loop details with the keyboard and returns to the summary', async () => {
const user = userEvent.setup()
const onBack = vi.fn()
@@ -37,17 +27,18 @@ it('expands and collapses loop details with the keyboard and returns to the summ
const header = screen.getByRole('button', { name: /workflow.singleRun.loop 1/ })
expect(header).toHaveTextContent('1.20s')
expect(header).toHaveAttribute('aria-expanded', 'false')
- expect(screen.queryByRole('status', { name: 'Loop variables' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
header.focus()
await user.keyboard('{Enter}')
expect(header).toHaveAttribute('aria-expanded', 'true')
- expect(screen.getByRole('status', { name: 'Loop variables' })).toHaveTextContent(
- '{"item":"alpha"}',
- )
+ expect(screen.getByRole('textbox')).toHaveAttribute('readonly')
+ expect(JSON.parse((screen.getByRole('textbox') as HTMLTextAreaElement).value)).toEqual({
+ item: 'alpha',
+ })
expect(screen.getByText('Summarize item')).toBeInTheDocument()
await user.keyboard(' ')
expect(header).toHaveAttribute('aria-expanded', 'false')
- expect(screen.queryByRole('status', { name: 'Loop variables' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'workflow.singleRun.back' }))
expect(onBack).toHaveBeenCalledOnce()
})
@@ -77,8 +68,9 @@ it.each([
/>,
)
await user.click(screen.getByRole('button', { name: /workflow.singleRun.loop 1/ }))
- expect(screen.getByRole('status', { name: 'Loop variables' })).toHaveTextContent(
- JSON.stringify({ item: expected }),
- )
+ expect(screen.getByRole('textbox')).toHaveAttribute('readonly')
+ expect(JSON.parse((screen.getByRole('textbox') as HTMLTextAreaElement).value)).toEqual({
+ item: expected,
+ })
},
)