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): cover node context menu clicks and drop hooks-store facade mocks (#44288)

Stephen Zhou857577555b1b
diff --git a/web/app/components/workflow/header/__tests__/run-and-history.spec.tsx b/web/app/components/workflow/header/__tests__/run-and-history.spec.tsx
index 82ada2095cb..5dd93e93a7c 100644
--- a/web/app/components/workflow/header/__tests__/run-and-history.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/run-and-history.spec.tsx
@@ -4,10 +4,6 @@ import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
import { fullWorkflowAccessControl } from '../../hooks-store/store'
import RunAndHistory from '../run-and-history'
-const startPreview = vi.hoisted(() => vi.fn())
-vi.mock('../../hooks/use-workflow-start-run', () => ({
- useWorkflowStartRun: () => ({ handleWorkflowStartRunInChatflow: startPreview }),
-}))
vi.mock('../view-history', () => ({ default: () => null }))
vi.mock('../checklist', () => ({ default: () => null }))
@@ -38,8 +34,12 @@ it('passes denied run permission to a custom run control', async () => {
it('keeps preview visible but prevents starting it when run permission is denied', async () => {
const user = userEvent.setup()
+ const startPreview = vi.fn()
renderWorkflowComponent(<RunAndHistory showPreviewButton />, {
- hooksStoreProps: { accessControl: { ...fullWorkflowAccessControl, canRun: false } },
+ hooksStoreProps: {
+ accessControl: { ...fullWorkflowAccessControl, canRun: false },
+ handleWorkflowStartRunInChatflow: startPreview,
+ },
})
const preview = screen.getByRole('button', { name: 'workflow.common.debugAndPreview' })
diff --git a/web/app/components/workflow/node-actions-menu/__tests__/context-menu-content.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/context-menu-content.spec.tsx
new file mode 100644
index 00000000000..3535dc94c53
--- /dev/null
+++ b/web/app/components/workflow/node-actions-menu/__tests__/context-menu-content.spec.tsx
@@ -0,0 +1,142 @@
+import type { AvailableNodesMetaData } from '../../hooks-store'
+import { ContextMenu } from '@langgenius/dify-ui/context-menu'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { use, useLayoutEffect } from 'react'
+import { useNodes } from 'reactflow'
+import { createNode } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { BlockEnum } from '@/app/components/workflow/types'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { HooksStoreContext } from '../../hooks-store'
+import { useNodeMetaData } from '../../hooks/use-nodes-meta-data'
+import { useWorkflowNodeCatalog } from '../../node-catalog'
+import { NodeActionsContextMenuContent } from '../context-menu-content'
+
+// Node metadata comes from the per-app block registry, which has its own suite.
+vi.mock('../../hooks/use-nodes-meta-data', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../hooks/use-nodes-meta-data')>()
+
+ return {
+ ...actual,
+ useNodeMetaData: 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, {
+ 'workspaces.current.tools.workflow.get': async () => [],
+ }),
+ }
+})
+
+vi.mock('../change-block-popup', () => ({
+ ChangeBlockPopup: () => <div data-testid="node-actions-change-block" />,
+}))
+
+const mockUseNodeMetaData = vi.mocked(useNodeMetaData)
+
+// Publishes the real block catalog so copy/duplicate know which nodes are copyable.
+const CanvasNodes = () => {
+ const catalog = useWorkflowNodeCatalog()
+ const hooksStore = use(HooksStoreContext)!
+ useLayoutEffect(() => {
+ const nodesMap = catalog.nodesMap as NonNullable<AvailableNodesMetaData['nodesMap']>
+ hooksStore.setState({
+ availableNodesMetaData: {
+ nodes: catalog.nodes.map((node) => nodesMap[node.metaData.type]),
+ nodesMap,
+ },
+ })
+ }, [catalog, hooksStore])
+ const nodes = useNodes()
+ return <output aria-label="Canvas nodes">{nodes.map((node) => node.id).join(',')}</output>
+}
+
+const canvasNodeIds = () =>
+ (screen.getByRole('status', { hidden: true }).textContent ?? '').split(',').filter(Boolean)
+
+const renderContextMenu = (readOnly = false) => {
+ const { queryClient } = createConsoleQueryWrapper({ appDslVersion: '0.6.0' })
+ seedModelProviderQueries(queryClient)
+
+ return renderWorkflowFlowComponent(
+ <>
+ <ContextMenu open>
+ <NodeActionsContextMenuContent
+ id="node-1"
+ data={{ type: BlockEnum.Code, title: 'Code Node', desc: '' }}
+ onClose={() => undefined}
+ showHelpLink={false}
+ />
+ </ContextMenu>
+ <CanvasNodes />
+ </>,
+ {
+ initialStoreState: { canvasReadOnly: readOnly },
+ nodes: [
+ createNode({
+ id: 'node-1',
+ width: 240,
+ height: 80,
+ data: { type: BlockEnum.Code, title: 'Code Node' },
+ }),
+ ],
+ edges: [],
+ queryClient,
+ },
+ )
+}
+
+describe('NodeActionsContextMenuContent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockUseNodeMetaData.mockReturnValue({
+ isTypeFixed: false,
+ isSingleton: false,
+ isUndeletable: false,
+ description: 'Node description',
+ author: 'Dify',
+ helpLinkUri: 'https://docs.example.com/node',
+ } as ReturnType<typeof useNodeMetaData>)
+ })
+
+ it.each([
+ { name: /workflow\.common\.copy/, clipboard: ['node-1'], nodeCount: 1 },
+ { name: /workflow\.common\.duplicate/, clipboard: undefined, nodeCount: 2 },
+ ])('runs the $name context-menu item on click', async ({ name, clipboard, nodeCount }) => {
+ const user = userEvent.setup()
+ const { store } = renderContextMenu()
+
+ await user.click(screen.getByRole('menuitem', { name }))
+
+ if (clipboard)
+ expect(store.getState().clipboardElements.map((node) => node.id)).toEqual(clipboard)
+ await waitFor(() => expect(canvasNodeIds()).toHaveLength(nodeCount))
+ })
+
+ it('hides editing actions and blocks their shortcuts when the canvas is readonly', () => {
+ const { store } = renderContextMenu(true)
+
+ expect(
+ screen.queryByRole('menuitem', { name: /workflow\.common\.copy/ }),
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('menuitem', { name: /workflow\.common\.duplicate/ }),
+ ).not.toBeInTheDocument()
+
+ const modifier = detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }
+ const menu = screen.getByRole('menu')
+ fireEvent.keyDown(menu, { key: 'c', ...modifier })
+ fireEvent.keyDown(menu, { key: 'd', ...modifier })
+
+ expect(store.getState().clipboardElements).toEqual([])
+ expect(canvasNodeIds()).toEqual(['node-1'])
+ })
+})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts
index 42704484ee1..088c6851aa7 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts
@@ -5,18 +5,17 @@ import { useChat } from '../../hooks'
type Callbacks = NonNullable<Parameters<ReturnType<typeof useWorkflowRun>['handleRun']>[1]>
const mocks = vi.hoisted(() => ({ run: vi.fn(), invalidate: vi.fn(), inspect: vi.fn() }))
-vi.mock('../../../../hooks/use-workflow-run', () => ({
- useWorkflowRun: () => ({ handleRun: mocks.run }),
-}))
-vi.mock('../../../../hooks/use-set-workflow-vars-with-value', () => ({
- useSetWorkflowVarsWithValue: () => ({ fetchInspectVars: mocks.inspect }),
-}))
vi.mock('@/service/use-workflow', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/use-workflow')>()),
useInvalidateAllLastRun: () => mocks.invalidate,
}))
beforeEach(() => vi.resetAllMocks())
+const hooksStoreProps = {
+ handleRun: mocks.run,
+ fetchInspectVars: mocks.inspect,
+}
+
it.each(['handleStop', 'handleRestart'] as const)(
'%s aborts an active run, stops its server task and resets iteration counters',
(operation) => {
@@ -32,6 +31,7 @@ it.each(['handleStop', 'handleRestart'] as const)(
})
const { result, store } = renderHook(() => useChat({}, undefined, undefined, stopChat), {
initialStoreState: { iterTimes: 4, loopTimes: 8 },
+ hooksStoreProps,
})
act(() => {
result.current.handleSend({ query: 'test' }, {})
@@ -49,7 +49,9 @@ it.each(['handleStop', 'handleRestart'] as const)(
it('does not send an empty task id when stopped before any run', () => {
const stopChat = vi.fn()
- const { result } = renderHook(() => useChat({}, undefined, undefined, stopChat))
+ const { result } = renderHook(() => useChat({}, undefined, undefined, stopChat), {
+ hooksStoreProps,
+ })
act(() => {
result.current.handleStop()
})
@@ -66,8 +68,9 @@ it('cancels suggested questions on stop and removes loaded suggestions on restar
onCancel(cancel)
return Promise.resolve({ data: ['Follow up'] })
})
- const { result } = renderHook(() =>
- useChat({ suggested_questions_after_answer: { enabled: true } }),
+ const { result } = renderHook(
+ () => useChat({ suggested_questions_after_answer: { enabled: true } }),
+ { hooksStoreProps },
)
act(() => {
result.current.handleSend({ query: 'test' }, { onGetSuggestedQuestions: getSuggested })
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts
index 3a8ff2260b2..c9796e4cf6b 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts
@@ -1,18 +1,7 @@
import { renderWorkflowFlowHook as renderHook } from '../../../../__tests__/workflow-test-env'
import { useChat } from '../../hooks'
-vi.mock('../../../../hooks/use-workflow-run', () => ({
- useWorkflowRun: () => ({ handleRun: vi.fn() }),
-}))
-vi.mock('../../../../hooks/use-set-workflow-vars-with-value', () => ({
- useSetWorkflowVarsWithValue: () => ({ fetchInspectVars: vi.fn() }),
-}))
-
describe('workflow debug useChat – opening statement stability', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
it('should return empty chatList when config has no opening_statement', () => {
const { result } = renderHook(() => useChat({}), {
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },