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): remove Base UI component mocks (#39877)

yyh802fe70423b6
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index d459c3fafe7..f42c0310ed5 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -44,44 +44,6 @@
"count": 3
}
},
- "web/__mocks__/base-ui-dropdown-menu.tsx": {
- "jsx_a11y/click-events-have-key-events": {
- "count": 3
- },
- "jsx_a11y/interactive-supports-focus": {
- "count": 2
- },
- "jsx_a11y/role-has-required-aria-props": {
- "count": 1
- }
- },
- "web/__mocks__/base-ui-popover.tsx": {
- "jsx_a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx_a11y/no-static-element-interactions": {
- "count": 1
- }
- },
- "web/__mocks__/base-ui-select.tsx": {
- "jsx_a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx_a11y/interactive-supports-focus": {
- "count": 1
- },
- "jsx_a11y/role-has-required-aria-props": {
- "count": 2
- }
- },
- "web/__mocks__/base-ui-tooltip.tsx": {
- "jsx_a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx_a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/__mocks__/zustand.ts": {
"no-barrel-files/no-barrel-files": {
"count": 1
@@ -568,11 +530,6 @@
"count": 1
}
},
- "web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx": {
- "jsx_a11y/role-has-required-aria-props": {
- "count": 1
- }
- },
"web/app/components/app/configuration/debug/__tests__/index.spec.tsx": {
"typescript/no-explicit-any": {
"count": 1
@@ -3420,14 +3377,6 @@
"count": 1
}
},
- "web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsx": {
- "jsx_a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx_a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-picker.tsx": {
"jsx_a11y/click-events-have-key-events": {
"count": 1
@@ -3762,14 +3711,6 @@
"count": 1
}
},
- "web/app/components/tools/labels/__tests__/selector.spec.tsx": {
- "jsx_a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx_a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/tools/labels/filter.tsx": {
"no-restricted-imports": {
"count": 1
@@ -4024,14 +3965,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx": {
- "jsx_a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx_a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsx": {
"jsx_a11y/click-events-have-key-events": {
"count": 1
@@ -5244,11 +5177,6 @@
"count": 1
}
},
- "web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx": {
- "jsx_a11y/click-events-have-key-events": {
- "count": 1
- }
- },
"web/app/components/workflow/note-node/note-editor/toolbar/color-picker.tsx": {
"jsx_a11y/click-events-have-key-events": {
"count": 1
diff --git a/web/__mocks__/__tests__/base-ui-popover.spec.tsx b/web/__mocks__/__tests__/base-ui-popover.spec.tsx
deleted file mode 100644
index 915895977a8..00000000000
--- a/web/__mocks__/__tests__/base-ui-popover.spec.tsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import * as React from 'react'
-import { Popover, PopoverContent, PopoverTrigger } from '../base-ui-popover'
-
-type PopoverHarnessProps = {
- useRenderElement?: boolean
- preventDefaultOnTrigger?: boolean
-}
-
-const PopoverHarness = ({
- useRenderElement = false,
- preventDefaultOnTrigger = false,
-}: PopoverHarnessProps) => {
- const [open, setOpen] = React.useState(false)
-
- return (
- <div>
- <div data-testid="outside-area">outside</div>
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger
- render={
- useRenderElement ? (
- <button
- type="button"
- data-testid="custom-trigger"
- onClick={(event) => {
- if (preventDefaultOnTrigger) event.preventDefault()
- }}
- >
- toggle
- </button>
- ) : undefined
- }
- >
- fallback trigger
- </PopoverTrigger>
- <PopoverContent
- className="custom-content"
- placement="bottom-start"
- sideOffset={4}
- alignOffset={8}
- positionerProps={
- { 'data-positioner': 'true' } as unknown as React.HTMLAttributes<HTMLDivElement>
- }
- popupProps={{ 'data-popup': 'true' } as unknown as React.HTMLAttributes<HTMLDivElement>}
- >
- <div>popover body</div>
- </PopoverContent>
- </Popover>
- <div data-testid="open-state">{open ? 'open' : 'closed'}</div>
- </div>
- )
-}
-
-describe('base-ui-popover mock', () => {
- it('should toggle popover content from the fallback trigger and expose content props', () => {
- render(<PopoverHarness />)
-
- expect(screen.getByTestId('open-state')).toHaveTextContent('closed')
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
-
- fireEvent.click(screen.getByTestId('popover-trigger'))
-
- expect(screen.getByTestId('open-state')).toHaveTextContent('open')
- expect(screen.getByTestId('popover-content')).toHaveAttribute('data-placement', 'bottom-start')
- expect(screen.getByTestId('popover-content')).toHaveAttribute('data-side-offset', '4')
- expect(screen.getByTestId('popover-content')).toHaveAttribute('data-align-offset', '8')
- expect(screen.getByTestId('popover-content')).toHaveAttribute('data-positioner', 'true')
- expect(screen.getByTestId('popover-content')).toHaveAttribute('data-popup', 'true')
- expect(screen.getByTestId('popover-content')).toHaveClass('custom-content')
- })
-
- it('should keep the popover open on inside clicks and close it on outside clicks or escape', () => {
- render(<PopoverHarness useRenderElement />)
-
- fireEvent.click(screen.getByTestId('custom-trigger'))
- expect(screen.getByTestId('open-state')).toHaveTextContent('open')
-
- fireEvent.mouseDown(screen.getByTestId('popover-content'))
- expect(screen.getByTestId('open-state')).toHaveTextContent('open')
-
- fireEvent.keyDown(document, { key: 'Escape' })
- expect(screen.getByTestId('open-state')).toHaveTextContent('closed')
-
- fireEvent.click(screen.getByTestId('custom-trigger'))
- expect(screen.getByTestId('open-state')).toHaveTextContent('open')
-
- fireEvent.mouseDown(screen.getByTestId('outside-area'))
- expect(screen.getByTestId('open-state')).toHaveTextContent('closed')
- })
-
- it('should preserve rendered trigger props and respect preventDefault', () => {
- render(<PopoverHarness useRenderElement preventDefaultOnTrigger />)
-
- fireEvent.click(screen.getByTestId('custom-trigger'))
-
- expect(screen.getByTestId('custom-trigger')).toHaveAttribute('data-popover-trigger', 'true')
- expect(screen.getByTestId('open-state')).toHaveTextContent('closed')
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
- })
-
- it('should keep the popover closed when the fallback trigger click is prevented', () => {
- const handleClick = (event: React.MouseEvent<HTMLElement>) => {
- event.preventDefault()
- }
-
- render(
- <div>
- <Popover open={false} onOpenChange={vi.fn()}>
- <PopoverTrigger onClick={handleClick}>fallback trigger</PopoverTrigger>
- <PopoverContent>
- <div>popover body</div>
- </PopoverContent>
- </Popover>
- </div>,
- )
-
- fireEvent.click(screen.getByTestId('popover-trigger'))
-
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
- })
-})
diff --git a/web/__mocks__/base-ui-dropdown-menu.tsx b/web/__mocks__/base-ui-dropdown-menu.tsx
deleted file mode 100644
index d3b439f0dfc..00000000000
--- a/web/__mocks__/base-ui-dropdown-menu.tsx
+++ /dev/null
@@ -1,230 +0,0 @@
-import type { ReactNode } from 'react'
-import * as React from 'react'
-
-const DropdownMenuContext = React.createContext({
- open: false,
- onOpenChange: (_open: boolean) => {},
-})
-
-type DropdownMenuProps = {
- children?: ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
-}
-
-type TriggerHtmlProps = React.HTMLAttributes<HTMLElement> & {
- 'data-testid'?: string
- 'data-disabled'?: string
- 'data-popup-open'?: string
-}
-
-type DropdownMenuTriggerProps = TriggerHtmlProps & {
- children?: ReactNode
- disabled?: boolean
- nativeButton?: boolean
- render?:
- | React.ReactElement
- | ((props: TriggerHtmlProps, state: { open: boolean }) => React.ReactElement)
-}
-
-type DropdownMenuContentProps = React.HTMLAttributes<HTMLDivElement> & {
- children?: ReactNode
- placement?: string
- sideOffset?: number
- alignOffset?: number
- popupClassName?: string
-}
-
-export const DropdownMenu = ({ children, open, onOpenChange }: DropdownMenuProps) => {
- const [localOpen, setLocalOpen] = React.useState(false)
- const resolvedOpen = open ?? localOpen
- const handleOpenChange = React.useCallback(
- (nextOpen: boolean) => {
- setLocalOpen(nextOpen)
- onOpenChange?.(nextOpen)
- },
- [onOpenChange],
- )
-
- return (
- <DropdownMenuContext.Provider value={{ open: resolvedOpen, onOpenChange: handleOpenChange }}>
- <div data-testid="dropdown-menu" data-open={String(resolvedOpen)}>
- {children}
- </div>
- </DropdownMenuContext.Provider>
- )
-}
-
-export const DropdownMenuTrigger = ({
- children,
- render,
- nativeButton: _nativeButton,
- onClick,
- disabled,
- ...props
-}: DropdownMenuTriggerProps) => {
- const { open, onOpenChange } = React.useContext(DropdownMenuContext)
- const handleClick = (event: React.MouseEvent<HTMLElement>) => {
- if (disabled) return
- onClick?.(event)
- if (!event.defaultPrevented) onOpenChange(!open)
- }
-
- if (typeof render === 'function') {
- return render(
- {
- ...props,
- 'aria-disabled': disabled || undefined,
- 'data-testid': props['data-testid'] ?? 'dropdown-menu-trigger',
- 'data-disabled': disabled ? '' : undefined,
- 'data-popup-open': open ? '' : undefined,
- onClick: handleClick,
- },
- { open },
- )
- }
-
- const node = render ?? children
- const isNativeButton = React.isValidElement(node) && node.type === 'button'
-
- if (React.isValidElement(node)) {
- const triggerElement = node as React.ReactElement<Record<string, unknown>>
- const childProps = (triggerElement.props ?? {}) as React.HTMLAttributes<HTMLElement> & {
- 'data-testid'?: string
- }
- const triggerProps = props as React.HTMLAttributes<HTMLElement> & { 'data-testid'?: string }
- const role =
- childProps.role ??
- triggerProps.role ??
- (!isNativeButton && (childProps['aria-label'] || triggerProps['aria-label'])
- ? 'button'
- : undefined)
- return React.cloneElement(
- triggerElement,
- {
- ...props,
- ...childProps,
- 'data-testid':
- childProps['data-testid'] ?? triggerProps['data-testid'] ?? 'dropdown-menu-trigger',
- 'data-disabled': disabled ? '' : undefined,
- 'data-popup-open': open ? '' : undefined,
- disabled: isNativeButton ? disabled : undefined,
- 'aria-disabled': !isNativeButton && disabled ? true : childProps['aria-disabled'],
- role,
- tabIndex:
- childProps.tabIndex ?? triggerProps.tabIndex ?? (role === 'button' ? 0 : undefined),
- onClick: (event: React.MouseEvent<HTMLElement>) => {
- childProps.onClick?.(event)
- handleClick(event)
- },
- },
- render ? (children ?? childProps.children) : childProps.children,
- )
- }
-
- return (
- <div
- data-testid="dropdown-menu-trigger"
- role="button"
- tabIndex={0}
- onClick={handleClick}
- {...props}
- >
- {node}
- </div>
- )
-}
-
-export const DropdownMenuContent = ({
- children,
- className,
- popupClassName,
- placement,
- sideOffset,
- alignOffset,
- ...props
-}: DropdownMenuContentProps) => {
- const { open } = React.useContext(DropdownMenuContext)
- if (!open) return null
-
- return (
- <div
- data-testid="dropdown-menu-content"
- data-placement={placement}
- data-side-offset={sideOffset}
- data-align-offset={alignOffset}
- className={className || popupClassName}
- {...props}
- >
- {children}
- </div>
- )
-}
-
-export const DropdownMenuItem = ({
- children,
- onClick,
- ...props
-}: React.HTMLAttributes<HTMLDivElement> & { children?: ReactNode }) => (
- <div role="menuitem" onClick={onClick} {...props}>
- {children}
- </div>
-)
-
-export const DropdownMenuRadioGroup = ({
- children,
- onValueChange,
- ...props
-}: React.HTMLAttributes<HTMLDivElement> & {
- children?: ReactNode
- value?: unknown
- onValueChange?: (value: unknown) => void
-}) => (
- <div role="radiogroup" {...props} data-on-value-change={onValueChange ? 'true' : undefined}>
- {React.Children.map(children, (child) => {
- if (!React.isValidElement(child)) return child
- return React.cloneElement(
- child as React.ReactElement<{ __onValueChange?: (value: unknown) => void }>,
- { __onValueChange: onValueChange },
- )
- })}
- </div>
-)
-
-export const DropdownMenuRadioItem = ({
- children,
- value,
- onClick,
- __onValueChange,
- ...props
-}: React.HTMLAttributes<HTMLDivElement> & {
- children?: ReactNode
- value?: unknown
- __onValueChange?: (value: unknown) => void
-}) => (
- <div
- role="radio"
- onClick={(event) => {
- onClick?.(event)
- __onValueChange?.(value)
- }}
- {...props}
- >
- {children}
- </div>
-)
-
-export const DropdownMenuRadioItemIndicator = ({ children }: { children?: ReactNode }) => (
- <>{children}</>
-)
-export const DropdownMenuCheckboxItem = DropdownMenuItem
-export const DropdownMenuCheckboxItemIndicator = ({ children }: { children?: ReactNode }) => (
- <>{children}</>
-)
-export const DropdownMenuLabel = ({ children }: { children?: ReactNode }) => <>{children}</>
-export const DropdownMenuSeparator = (props: React.HTMLAttributes<HTMLDivElement>) => (
- <div role="separator" {...props} />
-)
-export const DropdownMenuSub = ({ children }: { children?: ReactNode }) => <>{children}</>
-export const DropdownMenuSubTrigger = DropdownMenuItem
-export const DropdownMenuSubContent = ({ children }: { children?: ReactNode }) => <>{children}</>
diff --git a/web/__mocks__/base-ui-popover.tsx b/web/__mocks__/base-ui-popover.tsx
deleted file mode 100644
index 65324a56733..00000000000
--- a/web/__mocks__/base-ui-popover.tsx
+++ /dev/null
@@ -1,190 +0,0 @@
-import type { ReactNode } from 'react'
-import * as React from 'react'
-
-const PopoverContext = React.createContext({
- open: false,
- onOpenChange: (_open: boolean) => {},
-})
-
-type PopoverProps = {
- children?: ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
-}
-
-type TriggerHtmlProps = React.HTMLAttributes<HTMLElement> & {
- 'data-testid'?: string
- 'data-popover-trigger'?: string
- 'data-popup-open'?: string
-}
-
-type PopoverTriggerProps = TriggerHtmlProps & {
- children?: ReactNode
- nativeButton?: boolean
- render?:
- | React.ReactElement
- | ((props: TriggerHtmlProps, state: { open: boolean }) => React.ReactElement)
-}
-
-type PopoverContentProps = React.HTMLAttributes<HTMLDivElement> & {
- children?: ReactNode
- placement?: string
- sideOffset?: number
- alignOffset?: number
- popupClassName?: string
- positionerProps?: React.HTMLAttributes<HTMLDivElement>
- popupProps?: React.HTMLAttributes<HTMLDivElement>
-}
-
-export const Popover = ({ children, open, onOpenChange }: PopoverProps) => {
- const [localOpen, setLocalOpen] = React.useState(false)
- const resolvedOpen = open ?? localOpen
- const handleOpenChange = React.useCallback(
- (nextOpen: boolean) => {
- setLocalOpen(nextOpen)
- onOpenChange?.(nextOpen)
- },
- [onOpenChange],
- )
-
- React.useEffect(() => {
- if (!resolvedOpen) return
-
- const handleMouseDown = (event: MouseEvent) => {
- const target = event.target as Element | null
- if (target?.closest?.('[data-popover-trigger="true"], [data-popover-content="true"]')) return
-
- handleOpenChange(false)
- }
-
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.key === 'Escape') handleOpenChange(false)
- }
-
- document.addEventListener('mousedown', handleMouseDown)
- document.addEventListener('keydown', handleKeyDown)
-
- return () => {
- document.removeEventListener('mousedown', handleMouseDown)
- document.removeEventListener('keydown', handleKeyDown)
- }
- }, [resolvedOpen, handleOpenChange])
-
- return (
- <PopoverContext.Provider
- value={{
- open: resolvedOpen,
- onOpenChange: handleOpenChange,
- }}
- >
- <div data-testid="popover" data-open={String(resolvedOpen)}>
- {children}
- </div>
- </PopoverContext.Provider>
- )
-}
-
-export const PopoverTrigger = ({
- children,
- render,
- nativeButton: _nativeButton,
- onClick,
- ...props
-}: PopoverTriggerProps) => {
- const { open, onOpenChange } = React.useContext(PopoverContext)
- if (typeof render === 'function') {
- const triggerProps: TriggerHtmlProps = {
- ...props,
- 'data-testid': props['data-testid'] ?? 'popover-trigger',
- 'data-popover-trigger': 'true',
- 'data-popup-open': open ? '' : undefined,
- onClick: (event: React.MouseEvent<HTMLElement>) => {
- onClick?.(event)
- if (event.defaultPrevented) return
- onOpenChange(!open)
- },
- }
- return render(triggerProps, { open })
- }
-
- const node = render ?? children
-
- if (React.isValidElement(node)) {
- const triggerElement = node as React.ReactElement<Record<string, unknown>>
- const childProps = (triggerElement.props ?? {}) as React.HTMLAttributes<HTMLElement> & {
- 'data-testid'?: string
- }
- const triggerProps = props as React.HTMLAttributes<HTMLElement> & { 'data-testid'?: string }
-
- return React.cloneElement(
- triggerElement,
- {
- ...props,
- ...childProps,
- 'data-testid':
- childProps['data-testid'] ?? triggerProps['data-testid'] ?? 'popover-trigger',
- 'data-popover-trigger': 'true',
- 'data-popup-open': open ? '' : undefined,
- onClick: (event: React.MouseEvent<HTMLElement>) => {
- childProps.onClick?.(event)
- onClick?.(event)
- if (event.defaultPrevented) return
- onOpenChange(!open)
- },
- },
- render ? (children ?? childProps.children) : childProps.children,
- )
- }
-
- return (
- <div
- data-testid="popover-trigger"
- data-popover-trigger="true"
- data-popup-open={open ? '' : undefined}
- onClick={(event) => {
- onClick?.(event)
- if (event.defaultPrevented) return
- onOpenChange(!open)
- }}
- {...props}
- >
- {node}
- </div>
- )
-}
-
-export const PopoverContent = ({
- children,
- className,
- placement,
- sideOffset,
- alignOffset,
- popupClassName,
- positionerProps,
- popupProps,
- ...props
-}: PopoverContentProps) => {
- const { open } = React.useContext(PopoverContext)
-
- if (!open) return null
-
- return (
- <div
- data-testid="popover-content"
- data-popover-content="true"
- data-placement={placement}
- data-side-offset={sideOffset}
- data-align-offset={alignOffset}
- className={className || popupClassName}
- {...positionerProps}
- {...popupProps}
- {...props}
- >
- {children}
- </div>
- )
-}
-
-export const PopoverClose = ({ children }: { children?: ReactNode }) => <>{children}</>
-export const PopoverTitle = ({ children }: { children?: ReactNode }) => <>{children}</>
-export const PopoverDescription = ({ children }: { children?: ReactNode }) => <>{children}</>
diff --git a/web/__mocks__/base-ui-select.tsx b/web/__mocks__/base-ui-select.tsx
deleted file mode 100644
index 80fce8a5a9b..00000000000
--- a/web/__mocks__/base-ui-select.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import type { ReactNode } from 'react'
-import * as React from 'react'
-
-const SelectContext = React.createContext({
- value: undefined as unknown,
- onValueChange: (_value: unknown) => {},
-})
-
-type SelectProps = {
- children?: ReactNode
- value?: unknown
- onValueChange?: (value: unknown) => void
-}
-
-export const Select = ({ children, value, onValueChange }: SelectProps) => (
- <SelectContext.Provider value={{ value, onValueChange: onValueChange ?? (() => {}) }}>
- <div data-testid="select-root">{children}</div>
- </SelectContext.Provider>
-)
-
-export const SelectTrigger = ({
- children,
- ...props
-}: React.ButtonHTMLAttributes<HTMLButtonElement> & { children?: ReactNode }) => (
- <button type="button" role="combobox" {...props}>
- {children}
- </button>
-)
-
-export const SelectValue = ({ placeholder }: { placeholder?: ReactNode }) => <>{placeholder}</>
-
-export const SelectContent = ({
- children,
- popupClassName,
-}: {
- children?: ReactNode
- popupClassName?: string
-}) => (
- <div data-side="bottom" data-testid="select-content" className={popupClassName}>
- {children}
- </div>
-)
-
-export const SelectItem = ({
- children,
- value,
- onClick,
- ...props
-}: React.HTMLAttributes<HTMLDivElement> & { children?: ReactNode; value?: unknown }) => {
- const select = React.useContext(SelectContext)
- return (
- <div
- role="option"
- onClick={(event) => {
- onClick?.(event)
- select.onValueChange(value)
- }}
- {...props}
- >
- {children}
- </div>
- )
-}
-
-export const SelectItemText = ({ children }: { children?: ReactNode }) => <>{children}</>
-export const SelectItemIndicator = ({ children }: { children?: ReactNode }) => <>{children}</>
-export const SelectGroup = ({ children }: { children?: ReactNode }) => <>{children}</>
-export const SelectLabel = () => null
-export const SelectGroupLabel = ({ children }: { children?: ReactNode }) => <>{children}</>
-export const SelectSeparator = (props: React.HTMLAttributes<HTMLDivElement>) => (
- <div role="separator" {...props} />
-)
diff --git a/web/__mocks__/base-ui-tooltip.tsx b/web/__mocks__/base-ui-tooltip.tsx
deleted file mode 100644
index c1ee0790b0a..00000000000
--- a/web/__mocks__/base-ui-tooltip.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import type { ReactNode } from 'react'
-import * as React from 'react'
-
-const TooltipContext = React.createContext({
- open: false,
- onOpenChange: (_open: boolean) => {},
-})
-
-type TooltipProps = {
- children?: ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
-}
-
-export const Tooltip = ({ children, open, onOpenChange }: TooltipProps) => {
- const [localOpen, setLocalOpen] = React.useState(false)
- const resolvedOpen = open ?? localOpen
- const handleOpenChange = React.useCallback(
- (nextOpen: boolean) => {
- setLocalOpen(nextOpen)
- onOpenChange?.(nextOpen)
- },
- [onOpenChange],
- )
-
- return (
- <TooltipContext.Provider value={{ open: resolvedOpen, onOpenChange: handleOpenChange }}>
- {children}
- </TooltipContext.Provider>
- )
-}
-
-export const TooltipTrigger = ({
- children,
- render,
- nativeButton: _nativeButton,
- ...props
-}: React.HTMLAttributes<HTMLElement> & {
- children?: ReactNode
- render?: React.ReactElement
- nativeButton?: boolean
-}) => {
- const { open, onOpenChange } = React.useContext(TooltipContext)
- const node = render ?? children
-
- if (React.isValidElement(node)) {
- const triggerElement = node as React.ReactElement<Record<string, unknown>>
- const childProps = (triggerElement.props ?? {}) as React.HTMLAttributes<HTMLElement>
-
- return React.cloneElement(triggerElement, {
- ...props,
- ...childProps,
- onMouseEnter: (event: React.MouseEvent<HTMLElement>) => {
- childProps.onMouseEnter?.(event)
- props.onMouseEnter?.(event)
- onOpenChange(true)
- },
- onMouseLeave: (event: React.MouseEvent<HTMLElement>) => {
- childProps.onMouseLeave?.(event)
- props.onMouseLeave?.(event)
- onOpenChange(false)
- },
- onClick: (event: React.MouseEvent<HTMLElement>) => {
- childProps.onClick?.(event)
- props.onClick?.(event)
- onOpenChange(!open)
- },
- })
- }
-
- return (
- <span
- {...props}
- onMouseEnter={(event) => {
- props.onMouseEnter?.(event)
- onOpenChange(true)
- }}
- onMouseLeave={(event) => {
- props.onMouseLeave?.(event)
- onOpenChange(false)
- }}
- onClick={(event) => {
- props.onClick?.(event)
- onOpenChange(!open)
- }}
- >
- {node}
- </span>
- )
-}
-
-export const TooltipContent = ({
- children,
- ...props
-}: React.HTMLAttributes<HTMLDivElement> & { children?: ReactNode }) => {
- const { open } = React.useContext(TooltipContext)
- if (!open) return null
- return <div {...props}>{children}</div>
-}
-
-export const TooltipProvider = ({ children }: { children?: ReactNode }) => <>{children}</>
diff --git a/web/__tests__/interactive-component-mock-boundary.spec.ts b/web/__tests__/interactive-component-mock-boundary.spec.ts
new file mode 100644
index 00000000000..668bb4c47ca
--- /dev/null
+++ b/web/__tests__/interactive-component-mock-boundary.spec.ts
@@ -0,0 +1,37 @@
+import { readdirSync, readFileSync } from 'node:fs'
+import { relative, resolve } from 'node:path'
+
+const testFilePattern = /\.(?:spec|test)\.[cm]?[jt]sx?$/
+const interactivePrimitiveMockPattern =
+ /vi\.mock\(\s*['"]@langgenius\/dify-ui\/(?:alert-dialog|avatar|button|dialog|dropdown-menu|pagination|popover|select|slider|switch|textarea|tooltip)['"]/
+const interactiveWrapperMockPattern =
+ /vi\.mock\(\s*['"][^'"]*(?:block-selector|plugin-version-picker|time-picker)['"]/
+
+const collectTestFiles = (directory: string): string[] => {
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const path = resolve(directory, entry.name)
+ if (entry.isDirectory()) return collectTestFiles(path)
+ return testFilePattern.test(entry.name) ? [path] : []
+ })
+}
+
+describe('interactive component mock boundary', () => {
+ it('keeps Dify UI primitives and feature-owned interactive wrappers real', () => {
+ const webRoot = process.cwd()
+ const testFiles = ['__tests__', 'app', 'features'].flatMap((directory) =>
+ collectTestFiles(resolve(webRoot, directory)),
+ )
+ const violations = testFiles.flatMap((file) => {
+ const source = readFileSync(file, 'utf8')
+ if (
+ !interactivePrimitiveMockPattern.test(source) &&
+ !interactiveWrapperMockPattern.test(source)
+ ) {
+ return []
+ }
+ return [relative(webRoot, file)]
+ })
+
+ expect(violations).toEqual([])
+ })
+})
diff --git a/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx b/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx
index f92d245027e..db2d9345f74 100644
--- a/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx
+++ b/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx
@@ -58,32 +58,6 @@ vi.mock('@/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view',
default: ({ appId }: { appId: string }) => <div data-testid="card-view" data-app-id={appId} />,
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- className,
- size,
- variant,
- }: {
- children: React.ReactNode
- onClick?: () => void
- className?: string
- size?: string
- variant?: string
- }) => (
- <button
- type="button"
- onClick={onClick}
- className={className}
- data-size={size}
- data-variant={variant}
- >
- {children}
- </button>
- ),
-}))
-
vi.mock('../app-operations', () => ({
default: ({
primaryOperations,
diff --git a/web/app/components/app-sidebar/snippet-info/__tests__/dropdown.spec.tsx b/web/app/components/app-sidebar/snippet-info/__tests__/dropdown.spec.tsx
index a10c856fad4..0dddfd30adb 100644
--- a/web/app/components/app-sidebar/snippet-info/__tests__/dropdown.spec.tsx
+++ b/web/app/components/app-sidebar/snippet-info/__tests__/dropdown.spec.tsx
@@ -14,8 +14,6 @@ const mockUpdateMutate = vi.fn()
const mockExportMutateAsync = vi.fn()
const mockDeleteMutate = vi.fn()
let mockWorkspacePermissionKeys: string[] = ['snippets.create_and_modify', 'snippets.management']
-let mockDropdownOpen = false
-let mockDropdownOnOpenChange: ((open: boolean) => void) | undefined
const mockConsoleState = vi.hoisted(() => ({
current: {
get workspacePermissionKeys() {
@@ -46,51 +44,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
},
}))
-vi.mock('@langgenius/dify-ui/dropdown-menu', () => ({
- DropdownMenu: ({
- open,
- onOpenChange,
- children,
- }: {
- open?: boolean
- onOpenChange?: (open: boolean) => void
- children: React.ReactNode
- }) => {
- mockDropdownOpen = !!open
- mockDropdownOnOpenChange = onOpenChange
- return <div>{children}</div>
- },
- DropdownMenuTrigger: ({
- children,
- className,
- }: {
- children: React.ReactNode
- className?: string
- }) => (
- <button
- type="button"
- className={className}
- onClick={() => mockDropdownOnOpenChange?.(!mockDropdownOpen)}
- >
- {children}
- </button>
- ),
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) =>
- mockDropdownOpen ? <div>{children}</div> : null,
- DropdownMenuItem: ({
- children,
- onClick,
- }: {
- children: React.ReactNode
- onClick?: () => void
- }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- DropdownMenuSeparator: () => <hr />,
-}))
-
vi.mock('@/service/use-snippets', () => ({
useUpdateSnippetMutation: () => ({
mutate: mockUpdateMutate,
@@ -173,8 +126,6 @@ describe('SnippetInfoDropdown', () => {
beforeEach(() => {
vi.clearAllMocks()
mockWorkspacePermissionKeys = ['snippets.create_and_modify', 'snippets.management']
- mockDropdownOpen = false
- mockDropdownOnOpenChange = undefined
})
// Rendering coverage for the menu trigger itself.
diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
index ae5cf4a4e9f..1b1a82991bd 100644
--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
@@ -171,8 +171,6 @@ vi.mock('@/app/components/tools/workflow-tool', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
vi.mock('../sections', () => ({
PublisherSummarySection: (props: Record<string, any>) => {
sectionProps.summary = props
diff --git a/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx b/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx
index 6991ea8aab7..1d840da7e9b 100644
--- a/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/publish-with-multiple-model.spec.tsx
@@ -17,91 +17,6 @@ vi.mock('../../header/account-setting/model-provider-page/model-icon', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const ReactModule = await vi.importActual<typeof import('react')>('react')
- const OpenContext = ReactModule.createContext<{
- open: boolean
- setOpen: (nextOpen: boolean) => void
- } | null>(null)
-
- const useOpenContext = () => {
- const context = ReactModule.use(OpenContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <OpenContext.Provider value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div data-testid="portal-root">{children}</div>
- </OpenContext.Provider>
- ),
- DropdownMenuTrigger: ({
- children,
- render,
- }: {
- children: React.ReactNode
- render?: React.ReactElement
- }) => {
- const { open, setOpen } = useOpenContext()
-
- if (render) {
- return ReactModule.cloneElement(
- render,
- {
- onClick: () => setOpen(!open),
- } as Record<string, unknown>,
- children,
- )
- }
-
- return (
- <button type="button" onClick={() => setOpen(!open)}>
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({
- children,
- popupClassName,
- }: {
- children: React.ReactNode
- popupClassName?: string
- }) => {
- const context = useOpenContext()
- return context.open ? <div className={popupClassName}>{children}</div> : null
- },
- DropdownMenuItem: ({
- children,
- onClick,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- }) => {
- const { setOpen } = useOpenContext()
- return (
- <button
- type="button"
- onClick={(event) => {
- onClick?.(event)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- }
-})
-
describe('PublishWithMultipleModel', () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx b/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
index 7ffa5d72524..1983417a0c1 100644
--- a/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
@@ -3,13 +3,6 @@ import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
import EditModal from '../edit-modal'
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, open }: { children: React.ReactNode; open?: boolean }) =>
- open === false ? null : <>{children}</>,
- DialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
describe('Conversation history edit modal', () => {
const data: ConversationHistoriesRole = {
user_prefix: 'user',
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
index 7a471f053a9..822629be8f9 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/form-fields.spec.tsx
@@ -1,6 +1,7 @@
/* oxlint-disable typescript/no-explicit-any */
import type { ReactNode } from 'react'
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { InputVarType } from '@/app/components/workflow/types'
import { withSelectorKey } from '@/test/i18n-mock'
import ConfigModalFormFields from '../form-fields'
@@ -84,46 +85,6 @@ vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', (
),
}))
-vi.mock('@langgenius/dify-ui/select', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@langgenius/dify-ui/select')>()
-
- return {
- ...actual,
- Select: ({
- value,
- onValueChange,
- children,
- }: {
- value: string
- onValueChange: (value: string) => void
- children: ReactNode
- }) => (
- <div>
- <button
- type="button"
- onClick={() => onValueChange(value === 'true' ? 'false' : 'beta')}
- >{`ui-select:${value}`}</button>
- <button type="button" onClick={() => onValueChange('__empty__')}>
- ui-select-empty
- </button>
- {children}
- </div>
- ),
- SelectTrigger: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- SelectValue: () => <span>select-value</span>,
- SelectContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- SelectItemText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- SelectItemIndicator: () => <span data-testid="select-item-indicator" />,
- }
-})
-
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- TooltipTrigger: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- TooltipContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
-
vi.mock('../field', () => ({
default: ({ children, title }: { children: ReactNode; title: string }) => (
<div>
@@ -201,7 +162,8 @@ const createBaseProps = () => {
}
describe('ConfigModalFormFields', () => {
- it('should update paragraph, number, checkbox, and select defaults', () => {
+ it('should update paragraph, number, checkbox, and select defaults', async () => {
+ const user = userEvent.setup()
const paragraphProps = createBaseProps()
paragraphProps.tempPayload = {
...paragraphProps.tempPayload,
@@ -229,9 +191,12 @@ describe('ConfigModalFormFields', () => {
default: false,
}
checkboxProps.checkboxDefaultSelectValue = 'true'
- render(<ConfigModalFormFields {...checkboxProps} />)
- fireEvent.click(screen.getByText('ui-select:true'))
+ const checkboxView = render(<ConfigModalFormFields {...checkboxProps} />)
+ await user.click(screen.getByRole('combobox'))
+ const checkboxOptions = await screen.findAllByRole('option')
+ await user.click(checkboxOptions[1]!)
expect(checkboxProps.payloadChangeHandlers.default).toHaveBeenCalledWith(false)
+ checkboxView.unmount()
const selectProps = createBaseProps()
selectProps.tempPayload = {
@@ -242,7 +207,9 @@ describe('ConfigModalFormFields', () => {
selectProps.options = ['alpha', 'beta']
render(<ConfigModalFormFields {...selectProps} />)
fireEvent.click(screen.getByText('config-select'))
- fireEvent.click(screen.getByText('ui-select:alpha'))
+ await user.click(screen.getByRole('combobox'))
+ const selectOptions = await screen.findAllByRole('option')
+ await user.click(selectOptions[2]!)
expect(selectProps.payloadChangeHandlers.options).toHaveBeenCalledWith(['alpha', 'beta'])
expect(selectProps.payloadChangeHandlers.default).toHaveBeenCalledWith('beta')
})
@@ -348,7 +315,8 @@ describe('ConfigModalFormFields', () => {
expect(textProps.payloadChangeHandlers.default).toHaveBeenCalledWith(undefined)
})
- it('should clear select defaults and apply uploader fallback values', () => {
+ it('should clear select defaults and apply uploader fallback values', async () => {
+ const user = userEvent.setup()
const selectProps = createBaseProps()
selectProps.tempPayload = {
...selectProps.tempPayload,
@@ -356,10 +324,13 @@ describe('ConfigModalFormFields', () => {
default: 'alpha',
}
selectProps.options = ['alpha', ' ', 'beta']
- render(<ConfigModalFormFields {...selectProps} />)
+ const selectView = render(<ConfigModalFormFields {...selectProps} />)
- fireEvent.click(screen.getByText('ui-select-empty'))
+ await user.click(screen.getByRole('combobox'))
+ const selectOptions = await screen.findAllByRole('option')
+ await user.click(selectOptions[0]!)
expect(selectProps.payloadChangeHandlers.default).toHaveBeenCalledWith(undefined)
+ selectView.unmount()
const singleFallbackProps = createBaseProps()
singleFallbackProps.tempPayload = {
@@ -416,21 +387,10 @@ describe('ConfigModalFormFields', () => {
render(<ConfigModalFormFields {...selectWithoutOptionsProps} />)
expect(screen.getAllByText('config-select')).toHaveLength(1)
- expect(screen.queryByText('ui-select:__empty__')).not.toBeInTheDocument()
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
})
- it('should preserve existing select and file defaults when present', () => {
- const selectProps = createBaseProps()
- selectProps.tempPayload = {
- ...selectProps.tempPayload,
- type: InputVarType.select,
- default: undefined,
- }
- selectProps.options = ['alpha', 'beta']
- render(<ConfigModalFormFields {...selectProps} />)
-
- expect(screen.getByText('ui-select:__empty__')).toBeInTheDocument()
-
+ it('should preserve existing file defaults when present', () => {
const existingFile = {
fileId: 'existing-file',
type: 'local_file',
diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
index 148f5872647..4aad4aadd31 100644
--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/type-select.spec.tsx
@@ -3,8 +3,6 @@ import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import TypeSelector from '../type-select'
-vi.mock('@langgenius/dify-ui/select', () => import('@/__mocks__/base-ui-select'))
-
vi.mock('@/app/components/workflow/nodes/_base/components/input-var-type-icon', () => ({
default: ({ type }: { type: string }) => <span>{type}</span>,
}))
diff --git a/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx b/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
index e05d0af638f..287fbbc49bf 100644
--- a/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-setting/__tests__/index.spec.tsx
@@ -3,25 +3,6 @@ import { act, fireEvent, render, screen } from '@testing-library/react'
import { MAX_ITERATIONS_NUM } from '@/config'
import { AgentSetting } from '../index'
-vi.mock('@langgenius/dify-ui/slider', () => ({
- Slider: (props: {
- className?: string
- min?: number
- max?: number
- value: number
- onValueChange: (value: number) => void
- }) => (
- <input
- type="range"
- className={`slider ${props.className ?? ''}`}
- min={props.min}
- max={props.max}
- value={props.value}
- onChange={(e) => props.onValueChange(Number(e.target.value))}
- />
- ),
-}))
-
const basePayload = {
enabled: true,
strategy: 'react',
diff --git a/web/app/components/app/configuration/dataset-config/context-var/__tests__/var-picker.spec.tsx b/web/app/components/app/configuration/dataset-config/context-var/__tests__/var-picker.spec.tsx
index 0b3c1a63886..5babe06c125 100644
--- a/web/app/components/app/configuration/dataset-config/context-var/__tests__/var-picker.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/context-var/__tests__/var-picker.spec.tsx
@@ -1,45 +1,8 @@
-import type { ReactNode } from 'react'
import type { Props } from '../var-picker'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import * as React from 'react'
import VarPicker from '../var-picker'
-vi.mock('@langgenius/dify-ui/popover', () => {
- const PopoverContext = React.createContext({
- open: false,
- onOpenChange: undefined as ((open: boolean) => void) | undefined,
- })
-
- return {
- Popover: ({
- children,
- open,
- onOpenChange,
- }: {
- children: ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) => <PopoverContext value={{ open: !!open, onOpenChange }}>{children}</PopoverContext>,
- PopoverTrigger: ({ render }: { render?: ReactNode }) => {
- const { open, onOpenChange } = React.use(PopoverContext)
- return (
- <button type="button" aria-label="choose variable" onClick={() => onOpenChange?.(!open)}>
- {render}
- </button>
- )
- },
- PopoverContent: ({ children }: { children: ReactNode }) => {
- const { open } = React.use(PopoverContext)
- return open ? (
- <div role="dialog" aria-label="variable options">
- {children}
- </div>
- ) : null
- },
- }
-})
-
const options: Props['options'] = [
{ name: 'Variable 1', value: 'var1', type: 'string' },
{ name: 'Variable 2', value: 'var2', type: 'number' },
@@ -48,7 +11,7 @@ const options: Props['options'] = [
describe('VarPicker', () => {
it('shows the selected variable', () => {
render(<VarPicker value="var1" options={options} onChange={vi.fn()} />)
- expect(screen.getByRole('button', { name: 'choose variable' })).toHaveTextContent('var1')
+ expect(screen.getByRole('button')).toHaveTextContent('var1')
})
it('shows the configured empty-selection message', () => {
@@ -64,19 +27,21 @@ describe('VarPicker', () => {
})
it('selects a variable and closes the options', async () => {
+ const user = userEvent.setup()
const onChange = vi.fn()
render(<VarPicker value="var1" options={options} onChange={onChange} />)
- await userEvent.click(screen.getByRole('button', { name: 'choose variable' }))
- await userEvent.click(screen.getByText('var2'))
+ await user.click(screen.getByRole('button'))
+ await user.click(screen.getByText('var2'))
expect(onChange).toHaveBeenCalledWith('var2')
- expect(screen.queryByRole('dialog', { name: 'variable options' })).not.toBeInTheDocument()
+ expect(screen.queryByText('var2')).not.toBeInTheDocument()
})
it('shows the empty state when no variables are available', async () => {
+ const user = userEvent.setup()
render(<VarPicker value={undefined} options={[]} onChange={vi.fn()} />)
- await userEvent.click(screen.getByRole('button', { name: 'choose variable' }))
+ await user.click(screen.getByRole('button'))
expect(screen.getByText('appDebug.feature.dataSet.queryVariable.noVar')).toBeInTheDocument()
})
})
diff --git a/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx b/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx
index b4506f33dcb..636d64fcd4d 100644
--- a/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx
+++ b/web/app/components/app/configuration/debug/__tests__/chat-user-input.spec.tsx
@@ -1,6 +1,7 @@
import type { Inputs, ModelConfig } from '@/models/debug'
import type { PromptVariable } from '@/types/app'
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import ChatUserInput from '../chat-user-input'
const mockSetInputs = vi.fn()
@@ -41,75 +42,6 @@ vi.mock('@/app/components/base/input', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
- const SelectContext = React.createContext<{
- disabled?: boolean
- onValueChange?: (value: string) => void
- value?: string | null
- }>({})
-
- return {
- Select: ({
- children,
- disabled,
- onValueChange,
- value,
- }: {
- children: React.ReactNode
- disabled?: boolean
- onValueChange?: (value: string) => void
- value?: string | null
- }) => (
- <SelectContext.Provider value={{ disabled, onValueChange, value }}>
- <div>{children}</div>
- </SelectContext.Provider>
- ),
- SelectValue: ({ placeholder }: { placeholder?: React.ReactNode }) => {
- const context = React.use(SelectContext)
- return <>{context.value || placeholder}</>
- },
- SelectTrigger: ({ children, className }: { children: React.ReactNode; className?: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <div>
- <button
- data-testid="select-input"
- type="button"
- disabled={context.disabled}
- className={className}
- >
- {children}
- </button>
- <button
- data-testid="select-empty"
- type="button"
- onClick={() => context.onValueChange?.('')}
- >
- empty select value
- </button>
- </div>
- )
- },
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <button
- data-testid={`select-${value}`}
- type="button"
- role="option"
- onClick={() => context.onValueChange?.(value)}
- >
- {children}
- </button>
- )
- },
- SelectItemText: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SelectItemIndicator: () => null,
- }
-})
-
vi.mock('@/app/components/workflow/nodes/_base/components/before-run-form/bool-input', () => ({
default: ({
name,
@@ -256,7 +188,8 @@ describe('ChatUserInput', () => {
expect(screen.getByRole('textbox', { name: 'Description' })).toBeInTheDocument()
})
- it('should render select input type', () => {
+ it('should render select input type', async () => {
+ const user = userEvent.setup()
mockUseContext.mockReturnValue(
createContextValue({
modelConfig: createModelConfig([
@@ -271,10 +204,11 @@ describe('ChatUserInput', () => {
)
render(<ChatUserInput inputs={{}} />)
- expect(screen.getByTestId('select-input')).toBeInTheDocument()
- expect(screen.getByText('A')).toBeInTheDocument()
- expect(screen.getByText('B')).toBeInTheDocument()
- expect(screen.getByText('C')).toBeInTheDocument()
+ const select = screen.getByRole('combobox')
+ await user.click(select)
+ expect(await screen.findByRole('option', { name: 'A' })).toBeInTheDocument()
+ expect(screen.getByRole('option', { name: 'B' })).toBeInTheDocument()
+ expect(screen.getByRole('option', { name: 'C' })).toBeInTheDocument()
})
it('should render number input type', () => {
@@ -324,7 +258,7 @@ describe('ChatUserInput', () => {
render(<ChatUserInput inputs={{}} />)
expect(screen.getByTestId('input-Name')).toBeInTheDocument()
expect(screen.getByRole('textbox', { name: 'Description' })).toBeInTheDocument()
- expect(screen.getByTestId('select-input')).toBeInTheDocument()
+ expect(screen.getByRole('combobox')).toBeInTheDocument()
})
it('should show optional label for non-required fields', () => {
@@ -497,7 +431,8 @@ describe('ChatUserInput', () => {
expect(mockSetInputs).toHaveBeenCalledWith({ desc: 'New Description' })
})
- it('should call setInputs when select input changes', () => {
+ it('should call setInputs when select input changes', async () => {
+ const user = userEvent.setup()
mockUseContext.mockReturnValue(
createContextValue({
modelConfig: createModelConfig([
@@ -512,31 +447,12 @@ describe('ChatUserInput', () => {
)
render(<ChatUserInput inputs={{ choice: 'A' }} />)
- fireEvent.click(screen.getByTestId('select-B'))
+ await user.click(screen.getByRole('combobox'))
+ await user.click(await screen.findByRole('option', { name: 'B' }))
expect(mockSetInputs).toHaveBeenCalledWith({ choice: 'B' })
})
- it('should ignore empty select updates', () => {
- mockUseContext.mockReturnValue(
- createContextValue({
- modelConfig: createModelConfig([
- createPromptVariable({
- key: 'choice',
- name: 'Choice',
- type: 'select',
- options: ['A', 'B', 'C'],
- }),
- ]),
- }),
- )
-
- render(<ChatUserInput inputs={{}} />)
- fireEvent.click(screen.getByTestId('select-empty'))
-
- expect(mockSetInputs).not.toHaveBeenCalled()
- })
-
it('should call setInputs when number input changes', () => {
mockUseContext.mockReturnValue(
createContextValue({
@@ -676,7 +592,7 @@ describe('ChatUserInput', () => {
)
render(<ChatUserInput inputs={{}} />)
- expect(screen.getByTestId('select-input')).toBeDisabled()
+ expect(screen.getByRole('combobox')).toBeDisabled()
})
it('should disable checkbox when configuration is readonly and test/run is denied', () => {
@@ -862,7 +778,8 @@ describe('ChatUserInput', () => {
})
describe('Edge Cases', () => {
- it('should handle select with empty options', () => {
+ it('should show no options when a select has no configured choices', async () => {
+ const user = userEvent.setup()
mockUseContext.mockReturnValue(
createContextValue({
modelConfig: createModelConfig([
@@ -872,25 +789,11 @@ describe('ChatUserInput', () => {
)
render(<ChatUserInput inputs={{}} />)
- const select = screen.getByTestId('select-input')
- expect(select).toBeInTheDocument()
+ const select = screen.getByRole('combobox')
+ await user.click(select)
expect(screen.queryAllByRole('option')).toHaveLength(0)
})
- it('should handle select with undefined options', () => {
- mockUseContext.mockReturnValue(
- createContextValue({
- modelConfig: createModelConfig([
- createPromptVariable({ key: 'choice', name: 'Choice', type: 'select' }),
- ]),
- }),
- )
-
- render(<ChatUserInput inputs={{}} />)
- const select = screen.getByTestId('select-input')
- expect(select).toBeInTheDocument()
- })
-
it('should preserve other input values when updating one field', () => {
mockUseContext.mockReturnValue(
createContextValue({
diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx
index 8d88c235a5d..1779b60ec58 100644
--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx
+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/chat-item.spec.tsx
@@ -102,10 +102,6 @@ vi.mock('@/app/components/base/chat/chat', () => ({
},
}))
-vi.mock('@langgenius/dify-ui/avatar', () => ({
- Avatar: ({ name }: { name: string }) => <div data-testid="avatar">{name}</div>,
-}))
-
const createModelAndParameter = (
overrides: Partial<ModelAndParameter> = {},
): ModelAndParameter => ({
diff --git a/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx
index 4fcb36ba44a..303781a233d 100644
--- a/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
/* oxlint-disable typescript/no-explicit-any */
import type { IPromptValuePanelProps } from '../index'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import ConfigContext from '@/context/debug-configuration'
@@ -9,29 +10,6 @@ import PromptValuePanel from '../index'
const mockSetShowAppConfigureFeaturesModal = vi.fn()
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- disabled,
- className,
- }: {
- children: React.ReactNode
- onClick?: () => void
- disabled?: boolean
- className?: string
- }) => (
- <button
- type="button"
- data-disabled={disabled ? 'true' : 'false'}
- className={className}
- onClick={() => onClick?.()}
- >
- {children}
- </button>
- ),
-}))
-
vi.mock('@/app/components/app/store', () => ({
useStore: (
selector: (state: {
@@ -65,60 +43,6 @@ vi.mock('@/app/components/base/features/new-feature-panel/feature-bar', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
- const SelectContext = React.createContext<{
- onValueChange?: (value: string) => void
- value?: string | null
- }>({})
-
- return {
- Select: ({
- children,
- onValueChange,
- value,
- }: {
- children: React.ReactNode
- onValueChange?: (value: string) => void
- value?: string | null
- }) => (
- <SelectContext.Provider value={{ onValueChange, value }}>
- <div>{children}</div>
- </SelectContext.Provider>
- ),
- SelectValue: ({ placeholder }: { placeholder?: React.ReactNode }) => {
- const context = React.use(SelectContext)
- return <>{context.value || placeholder}</>
- },
- SelectTrigger: ({ children }: { children: React.ReactNode }) => {
- const context = React.useContext(SelectContext)
- return (
- <div>
- <button type="button">{children}</button>
- <button
- data-testid="select-empty"
- type="button"
- onClick={() => context.onValueChange?.('')}
- >
- empty select value
- </button>
- </div>
- )
- },
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <button type="button" onClick={() => context.onValueChange?.(value)}>
- {children}
- </button>
- )
- },
- SelectItemText: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SelectItemIndicator: () => null,
- }
-})
-
vi.mock('@/app/components/workflow/nodes/_base/components/before-run-form/bool-input', () => ({
default: ({ name, onChange }: { name: string; onChange: (value: boolean) => void }) => (
<button type="button" data-testid={`bool-input-${name}`} onClick={() => onChange(true)}>
@@ -221,7 +145,7 @@ describe('PromptValuePanel', () => {
})
const runButton = screen.getByRole('button', { name: 'appDebug.inputs.run' })
- expect(runButton).toHaveAttribute('data-disabled', 'false')
+ expect(runButton).toBeEnabled()
fireEvent.click(runButton)
await waitFor(() => expect(mockOnSend).toHaveBeenCalledTimes(1))
})
@@ -237,22 +161,7 @@ describe('PromptValuePanel', () => {
})
const runButton = screen.getByRole('button', { name: 'appDebug.inputs.run' })
- expect(runButton).toHaveAttribute('data-disabled', 'true')
- })
-
- it('invokes the tooltip-branch run handler when the click callback is triggered', () => {
- renderPanel({
- context: {
- mode: AppModeEnum.CHAT,
- },
- props: {
- appType: AppModeEnum.CHAT,
- },
- })
-
- fireEvent.click(screen.getByRole('button', { name: 'appDebug.inputs.run' }))
-
- expect(mockOnSend).toHaveBeenCalledTimes(1)
+ expect(runButton).toBeDisabled()
})
it('hydrates default values, supports advanced prompt gating, and toggles the feature panel', () => {
@@ -282,10 +191,7 @@ describe('PromptValuePanel', () => {
})
expect(mockSetInputs).toHaveBeenCalledWith({ textVar: 'default text' })
- expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toHaveAttribute(
- 'data-disabled',
- 'true',
- )
+ expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toBeDisabled()
fireEvent.click(screen.getByText('feature bar'))
expect(mockSetShowAppConfigureFeaturesModal).toHaveBeenCalled()
@@ -309,13 +215,11 @@ describe('PromptValuePanel', () => {
},
})
- expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toHaveAttribute(
- 'data-disabled',
- 'true',
- )
+ expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toBeDisabled()
})
- it('renders paragraph, select, number, checkbox, and vision inputs', () => {
+ it('renders paragraph, select, number, checkbox, and vision inputs', async () => {
+ const user = userEvent.setup()
const onVisionFilesChange = vi.fn()
renderPanel({
context: {
@@ -357,7 +261,8 @@ describe('PromptValuePanel', () => {
fireEvent.change(screen.getByPlaceholderText('Paragraph Var'), {
target: { value: 'updated paragraph' },
})
- fireEvent.click(screen.getByText('b'))
+ await user.click(screen.getByRole('combobox'))
+ await user.click(await screen.findByRole('option', { name: 'b' }))
fireEvent.change(screen.getByDisplayValue('1'), { target: { value: '2' } })
fireEvent.click(screen.getByText('bool-input'))
fireEvent.click(screen.getByText('image-uploader'))
@@ -378,36 +283,6 @@ describe('PromptValuePanel', () => {
])
})
- it('ignores empty select values when choosing prompt options', () => {
- renderPanel({
- context: {
- modelConfig: {
- configs: {
- prompt_template: 'prompt template',
- prompt_variables: [
- {
- key: 'selectVar',
- name: 'Select Var',
- type: 'select',
- options: ['a', 'b'],
- required: false,
- },
- ],
- },
- },
- },
- props: {
- inputs: {
- selectVar: 'a',
- },
- },
- })
-
- fireEvent.click(screen.getByTestId('select-empty'))
-
- expect(mockSetInputs).not.toHaveBeenCalled()
- })
-
it('ignores updates when the rendered field is not tracked in the prompt variable lookup', () => {
const filteredPromptVariables = {
length: 1,
@@ -508,14 +383,8 @@ describe('PromptValuePanel', () => {
},
})
- expect(screen.getByRole('button', { name: 'common.operation.clear' })).toHaveAttribute(
- 'data-disabled',
- 'false',
- )
- expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toHaveAttribute(
- 'data-disabled',
- 'false',
- )
+ expect(screen.getByRole('button', { name: 'common.operation.clear' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toBeEnabled()
expect(screen.getByRole('button', { name: 'feature bar' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'feature bar' })).toHaveAttribute(
'data-hide-edit-entrance',
@@ -532,14 +401,8 @@ describe('PromptValuePanel', () => {
})
expect(screen.getByPlaceholderText('Text Var')).toHaveAttribute('readonly')
- expect(screen.getByRole('button', { name: 'common.operation.clear' })).toHaveAttribute(
- 'data-disabled',
- 'true',
- )
- expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toHaveAttribute(
- 'data-disabled',
- 'true',
- )
+ expect(screen.getByRole('button', { name: 'common.operation.clear' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toBeDisabled()
})
it('marks debug inputs and actions as disabled when configuration is readonly and test/run permission is missing', () => {
@@ -551,14 +414,8 @@ describe('PromptValuePanel', () => {
})
expect(screen.getByPlaceholderText('Text Var')).toHaveAttribute('readonly')
- expect(screen.getByRole('button', { name: 'common.operation.clear' })).toHaveAttribute(
- 'data-disabled',
- 'true',
- )
- expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toHaveAttribute(
- 'data-disabled',
- 'true',
- )
+ expect(screen.getByRole('button', { name: 'common.operation.clear' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'appDebug.inputs.run' })).toBeDisabled()
})
it('collapses the user input panel and hides the clear and run actions', () => {
diff --git a/web/app/components/app/log/__tests__/index.spec.tsx b/web/app/components/app/log/__tests__/index.spec.tsx
index 65330f27358..cd7bffd2a74 100644
--- a/web/app/components/app/log/__tests__/index.spec.tsx
+++ b/web/app/components/app/log/__tests__/index.spec.tsx
@@ -87,14 +87,6 @@ vi.mock('@/app/components/base/loading', () => ({
default: () => <div>loading-logs</div>,
}))
-vi.mock('@langgenius/dify-ui/pagination', () => ({
- Pagination: ({ onPageChange }: { onPageChange: (page: number) => void }) => (
- <div>
- <button onClick={() => onPageChange(2)}>go-to-page-2</button>
- </div>
- ),
-}))
-
describe('Logs', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -179,7 +171,7 @@ describe('Logs', () => {
/>,
)
- fireEvent.click(screen.getByText('go-to-page-2'))
+ fireEvent.click(screen.getByRole('button', { name: 'Go to page 2' }))
expect(mockReplace).toHaveBeenCalledWith('/apps/app-1/logs?page=2', { scroll: false })
})
diff --git a/web/app/components/app/log/__tests__/model-info.spec.tsx b/web/app/components/app/log/__tests__/model-info.spec.tsx
index b3b20187579..c759f13125e 100644
--- a/web/app/components/app/log/__tests__/model-info.spec.tsx
+++ b/web/app/components/app/log/__tests__/model-info.spec.tsx
@@ -1,4 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import ModelInfo from '../model-info'
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
@@ -30,62 +31,6 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/model-name'
),
}))
-vi.mock('@langgenius/dify-ui/popover', async () => {
- const React = await import('react')
- const PopoverContext = React.createContext<{
- open: boolean
- onOpenChange?: (open: boolean) => void
- } | null>(null)
-
- return {
- Popover: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <PopoverContext.Provider value={{ open, onOpenChange }}>
- <div data-testid="popover-root" data-open={open ? 'true' : 'false'}>
- {children}
- </div>
- </PopoverContext.Provider>
- ),
- PopoverTrigger: ({
- children,
- render,
- }: {
- children?: React.ReactNode
- render?: React.ReactNode
- }) => {
- const context = React.useContext(PopoverContext)
- const content = render ?? children
- const handleClick = () => {
- context?.onOpenChange?.(!context.open)
- }
-
- if (React.isValidElement(content)) {
- const element = content as React.ReactElement<{ onClick?: () => void }>
- return React.cloneElement(element, { onClick: handleClick })
- }
-
- return (
- <button type="button" data-testid="popover-trigger" onClick={handleClick}>
- {content}
- </button>
- )
- },
- PopoverContent: ({ children }: { children: React.ReactNode }) => {
- const context = React.useContext(PopoverContext)
- if (!context?.open) return null
-
- return <div data-testid="popover-content">{children}</div>
- },
- }
-})
-
describe('ModelInfo', () => {
const defaultModel = {
name: 'gpt-4',
@@ -132,32 +77,32 @@ describe('ModelInfo', () => {
it('should be closed by default', () => {
render(<ModelInfo model={defaultModel} />)
- expect(screen.getByTestId('popover-root')).toHaveAttribute('data-open', 'false')
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
+ expect(screen.queryByText(/(?:^|\.)detail\.modelParams(?=$|:)/)).not.toBeInTheDocument()
})
- it('should open when info button is clicked', () => {
+ it('should open when info button is clicked', async () => {
+ const user = userEvent.setup()
render(<ModelInfo model={defaultModel} />)
const trigger = screen.getByRole('button')
- fireEvent.click(trigger)
+ await user.click(trigger)
- expect(screen.getByTestId('popover-root')).toHaveAttribute('data-open', 'true')
- expect(screen.getByTestId('popover-content')).toBeInTheDocument()
+ expect(screen.getByText(/(?:^|\.)detail\.modelParams(?=$|:)/)).toBeInTheDocument()
+ expect(trigger).toHaveAttribute('aria-expanded', 'true')
})
- it('should close when info button is clicked again', () => {
+ it('should close when info button is clicked again', async () => {
+ const user = userEvent.setup()
render(<ModelInfo model={defaultModel} />)
const trigger = screen.getByRole('button')
- // Open
- fireEvent.click(trigger)
- expect(screen.getByTestId('popover-root')).toHaveAttribute('data-open', 'true')
+ await user.click(trigger)
+ expect(screen.getByText(/(?:^|\.)detail\.modelParams(?=$|:)/)).toBeInTheDocument()
- // Close
- fireEvent.click(trigger)
- expect(screen.getByTestId('popover-root')).toHaveAttribute('data-open', 'false')
+ await user.click(trigger)
+ expect(screen.queryByText(/(?:^|\.)detail\.modelParams(?=$|:)/)).not.toBeInTheDocument()
+ expect(trigger).toHaveAttribute('aria-expanded', 'false')
})
})
diff --git a/web/app/components/app/overview/__tests__/trigger-card.spec.tsx b/web/app/components/app/overview/__tests__/trigger-card.spec.tsx
index 3e0d268af7a..7a66e4a479b 100644
--- a/web/app/components/app/overview/__tests__/trigger-card.spec.tsx
+++ b/web/app/components/app/overview/__tests__/trigger-card.spec.tsx
@@ -48,9 +48,23 @@ vi.mock('@/service/use-triggers', () => ({
}))
vi.mock('@/utils', () => ({
+ asyncRunSafe: async <T,>(promise: Promise<T>) => {
+ try {
+ return [null, await promise]
+ } catch (error) {
+ return [error]
+ }
+ },
canFindTool: () => false,
}))
+vi.mock('@/context/permission-state', async () => {
+ const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
+ return createPermissionStateModuleMock(() => ({
+ workspacePermissionKeys: ['app.create_and_management'],
+ }))
+})
+
vi.mock('@/app/components/workflow/block-icon', () => ({
default: ({ type }: { type: string }) => (
<div data-testid="block-icon" data-type={type}>
@@ -59,28 +73,6 @@ vi.mock('@/app/components/workflow/block-icon', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/switch', () => ({
- Switch: ({
- checked,
- onCheckedChange,
- disabled,
- }: {
- checked: boolean
- onCheckedChange: (v: boolean) => void
- disabled: boolean
- }) => (
- <button
- data-testid="switch"
- data-checked={checked ? 'true' : 'false'}
- data-disabled={disabled ? 'true' : 'false'}
- disabled={disabled}
- onClick={() => !disabled && onCheckedChange(!checked)}
- >
- Switch
- </button>
- ),
-}))
-
describe('TriggerCard', () => {
const mockAppInfo = {
id: 'test-app-id',
@@ -210,7 +202,7 @@ describe('TriggerCard', () => {
it('should render switches for each trigger', () => {
render(<TriggerCard appInfo={mockAppInfo} onToggleResult={mockOnToggleResult} />)
- const switches = screen.getAllByTestId('switch')
+ const switches = screen.getAllByRole('switch')
expect(switches.length).toBe(2)
})
})
@@ -231,7 +223,7 @@ describe('TriggerCard', () => {
it('should call updateTriggerStatus when toggle is clicked', async () => {
render(<TriggerCard appInfo={mockAppInfo} onToggleResult={mockOnToggleResult} />)
- const switchBtn = screen.getByTestId('switch')
+ const switchBtn = screen.getByRole('switch')
fireEvent.click(switchBtn)
await waitFor(() => {
@@ -246,7 +238,7 @@ describe('TriggerCard', () => {
it('should update trigger status in store optimistically', async () => {
render(<TriggerCard appInfo={mockAppInfo} onToggleResult={mockOnToggleResult} />)
- const switchBtn = screen.getByTestId('switch')
+ const switchBtn = screen.getByRole('switch')
fireEvent.click(switchBtn)
await waitFor(() => {
@@ -257,7 +249,7 @@ describe('TriggerCard', () => {
it('should invalidate app triggers after successful update', async () => {
render(<TriggerCard appInfo={mockAppInfo} onToggleResult={mockOnToggleResult} />)
- const switchBtn = screen.getByTestId('switch')
+ const switchBtn = screen.getByRole('switch')
fireEvent.click(switchBtn)
await waitFor(() => {
@@ -268,7 +260,7 @@ describe('TriggerCard', () => {
it('should call onToggleResult with null on success', async () => {
render(<TriggerCard appInfo={mockAppInfo} onToggleResult={mockOnToggleResult} />)
- const switchBtn = screen.getByTestId('switch')
+ const switchBtn = screen.getByRole('switch')
fireEvent.click(switchBtn)
await waitFor(() => {
@@ -282,7 +274,7 @@ describe('TriggerCard', () => {
render(<TriggerCard appInfo={mockAppInfo} onToggleResult={mockOnToggleResult} />)
- const switchBtn = screen.getByTestId('switch')
+ const switchBtn = screen.getByRole('switch')
fireEvent.click(switchBtn)
await waitFor(() => {
@@ -360,7 +352,7 @@ describe('TriggerCard', () => {
render(<TriggerCard appInfo={mockAppInfo} onToggleResult={mockOnToggleResult} />)
- const switchBtn = screen.getByTestId('switch')
+ const switchBtn = screen.getByRole('switch')
expect(switchBtn).toBeInTheDocument()
})
@@ -383,8 +375,8 @@ describe('TriggerCard', () => {
<TriggerCard appInfo={appInfoWithoutEditPermission} onToggleResult={mockOnToggleResult} />,
)
- const switchBtn = screen.getByTestId('switch')
- expect(switchBtn).toHaveAttribute('data-disabled', 'true')
+ const switchBtn = screen.getByRole('switch')
+ expect(switchBtn).toHaveAttribute('aria-disabled', 'true')
fireEvent.click(switchBtn)
diff --git a/web/app/components/apps/__tests__/app-card.spec.tsx b/web/app/components/apps/__tests__/app-card.spec.tsx
index 421b09fa9b4..4f4a9dcca9c 100644
--- a/web/app/components/apps/__tests__/app-card.spec.tsx
+++ b/web/app/components/apps/__tests__/app-card.spec.tsx
@@ -41,6 +41,9 @@ const render = (ui: React.ReactElement) =>
},
})
+const getOperationsTrigger = () =>
+ screen.getByRole('button', { name: /common\.operation\.moreActionsFor/ })
+
// Mock next/navigation
const mockPush = vi.fn()
vi.mock('@/next/navigation', () => ({
@@ -358,123 +361,6 @@ vi.mock('@/next/dynamic', () => ({
},
}))
-vi.mock('@langgenius/dify-ui/dropdown-menu', () => {
- type DropdownMenuContextValue = {
- isOpen: boolean
- setOpen: (open: boolean) => void
- }
- const DropdownMenuContext = React.createContext<DropdownMenuContextValue | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open = false,
- modal,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- modal?: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ isOpen: open, setOpen: onOpenChange ?? vi.fn() }}>
- <div data-testid="dropdown-menu" data-open={open} data-modal={modal}>
- {children}
- </div>
- </DropdownMenuContext>
- ),
- DropdownMenuTrigger: ({
- children,
- className,
- onClick,
- ...props
- }: React.ButtonHTMLAttributes<HTMLButtonElement>) => {
- const { isOpen, setOpen } = useDropdownMenuContext()
- return (
- <button
- data-testid="dropdown-menu-trigger"
- type="button"
- className={className}
- onClick={(e) => {
- onClick?.(e)
- setOpen(!isOpen)
- }}
- {...props}
- >
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({
- children,
- className,
- popupClassName,
- popupProps,
- positionerProps,
- }: {
- children: React.ReactNode
- className?: string
- popupClassName?: string
- popupProps?: React.HTMLAttributes<HTMLDivElement>
- positionerProps?: React.HTMLAttributes<HTMLDivElement>
- }) => {
- const { isOpen } = useDropdownMenuContext()
- if (!isOpen) return null
-
- return (
- <div data-testid="dropdown-menu-positioner" {...positionerProps}>
- <div
- data-testid="dropdown-menu-content"
- role="menu"
- className={[className, popupClassName].filter(Boolean).join(' ')}
- {...popupProps}
- >
- {children}
- </div>
- </div>
- )
- },
- DropdownMenuItem: ({
- children,
- className,
- onClick,
- destructive,
- disabled,
- }: {
- children: React.ReactNode
- className?: string
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- destructive?: boolean
- disabled?: boolean
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- data-testid="dropdown-menu-item"
- role="menuitem"
- type="button"
- className={className}
- data-destructive={destructive}
- disabled={disabled}
- onClick={(e) => {
- onClick?.(e)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- DropdownMenuSeparator: () => <hr data-testid="dropdown-menu-separator" />,
- }
-})
-
// AppCardTags has tag API dependencies - mock for isolated testing
vi.mock('@/features/tag-management/components/app-card-tags', () => ({
AppCardTags: ({
@@ -839,37 +725,24 @@ describe('AppCard', () => {
})
describe('Operations Menu', () => {
- it('should render operations dropdown menu', () => {
- render(<AppCard app={mockApp} />)
- expect(screen.getByTestId('dropdown-menu')).toBeInTheDocument()
- })
-
- it('should render dropdown menu as non-modal', () => {
- render(<AppCard app={mockApp} />)
- expect(screen.getByTestId('dropdown-menu')).toHaveAttribute('data-modal', 'false')
- })
-
it('should reveal operations trigger when card receives keyboard focus', () => {
render(<AppCard app={mockApp} />)
- const operationsTriggerWrapper = screen
- .getByTestId('dropdown-menu-trigger')
- .closest('.absolute')
+ const operationsTrigger = getOperationsTrigger()
+ const operationsTriggerWrapper = operationsTrigger.closest('.absolute')
expect(operationsTriggerWrapper).toHaveClass('top-2')
expect(operationsTriggerWrapper).toHaveClass('right-2')
expect(operationsTriggerWrapper).toHaveClass('group-focus-within:pointer-events-auto')
expect(operationsTriggerWrapper).toHaveClass('group-focus-within:opacity-100')
expect(operationsTriggerWrapper).not.toHaveClass('w-[120px]')
- expect(screen.getByTestId('dropdown-menu-trigger')).toHaveClass('focus-visible:ring-2')
- expect(screen.getByTestId('dropdown-menu-trigger')).toHaveClass(
- 'focus-visible:ring-state-accent-solid',
- )
+ expect(operationsTrigger).toHaveClass('focus-visible:ring-2')
+ expect(operationsTrigger).toHaveClass('focus-visible:ring-state-accent-solid')
})
it('should show edit option when dropdown menu is opened', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.editApp')).toBeInTheDocument()
@@ -879,7 +752,7 @@ describe('AppCard', () => {
it('should show duplicate option when dropdown menu is opened', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.duplicate')).toBeInTheDocument()
@@ -894,7 +767,7 @@ describe('AppCard', () => {
})
render(<AppCard app={appWithoutImportExportPermission} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.duplicate')).toBeInTheDocument()
@@ -910,7 +783,7 @@ describe('AppCard', () => {
})
render(<StarredAppCard app={appWithoutImportExportPermission} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.duplicate')).toBeInTheDocument()
@@ -921,7 +794,7 @@ describe('AppCard', () => {
it('should show export option when dropdown menu is opened', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.export')).toBeInTheDocument()
@@ -931,7 +804,7 @@ describe('AppCard', () => {
it('should show delete option when dropdown menu is opened', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('common.operation.delete')).toBeInTheDocument()
@@ -942,7 +815,7 @@ describe('AppCard', () => {
const chatApp = { ...mockApp, mode: AppModeEnum.CHAT }
render(<AppCard app={chatApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText(/switch/i)).toBeInTheDocument()
@@ -959,7 +832,7 @@ describe('AppCard', () => {
})
render(<AppCard app={editableChatApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText(/switch/i)).toBeInTheDocument()
@@ -971,7 +844,7 @@ describe('AppCard', () => {
const completionApp = { ...mockApp, mode: AppModeEnum.COMPLETION }
render(<AppCard app={completionApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText(/switch/i)).toBeInTheDocument()
@@ -982,7 +855,7 @@ describe('AppCard', () => {
const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }
render(<AppCard app={workflowApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.queryByText(/switch/i)).not.toBeInTheDocument()
@@ -994,7 +867,7 @@ describe('AppCard', () => {
it('should open edit modal when edit button is clicked', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
const editButton = screen.getByText('app.editApp')
@@ -1009,7 +882,7 @@ describe('AppCard', () => {
it('should open duplicate modal when duplicate button is clicked', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
const duplicateButton = screen.getByText('app.duplicate')
@@ -1024,7 +897,7 @@ describe('AppCard', () => {
it('should open confirm dialog when delete button is clicked', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
})
@@ -1032,7 +905,7 @@ describe('AppCard', () => {
it('should close confirm dialog when cancel is clicked', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
@@ -1044,7 +917,7 @@ describe('AppCard', () => {
it('should not submit delete when confirmation text does not match', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
const form = (await screen.findByRole('alertdialog')).querySelector('form')
@@ -1057,7 +930,7 @@ describe('AppCard', () => {
it('should close edit modal when onHide is called', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.editApp'))
})
@@ -1077,7 +950,7 @@ describe('AppCard', () => {
it('should close duplicate modal when onHide is called', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.duplicate'))
})
@@ -1097,7 +970,7 @@ describe('AppCard', () => {
it('should clear delete confirmation input after closing the dialog', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
const deleteInput = await screen.findByRole('textbox')
@@ -1108,7 +981,7 @@ describe('AppCard', () => {
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
})
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
await waitFor(() => {
@@ -1122,7 +995,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
// Open dropdown menu and click delete
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
@@ -1140,7 +1013,7 @@ describe('AppCard', () => {
it('should not call onRefresh after successful delete', async () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
@@ -1161,7 +1034,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
@@ -1185,7 +1058,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
@@ -1204,7 +1077,7 @@ describe('AppCard', () => {
it('should call updateAppInfo API when editing app', async () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.editApp'))
})
@@ -1223,7 +1096,7 @@ describe('AppCard', () => {
it('should edit successfully without onRefresh callback', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.editApp'))
})
@@ -1243,7 +1116,7 @@ describe('AppCard', () => {
it('should call copyApp API when duplicating app', async () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.duplicate'))
})
@@ -1262,7 +1135,7 @@ describe('AppCard', () => {
it('should call onPlanInfoChanged after successful duplication', async () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.duplicate'))
})
@@ -1281,7 +1154,7 @@ describe('AppCard', () => {
it('should duplicate successfully without onRefresh callback', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.duplicate'))
})
@@ -1304,7 +1177,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.duplicate'))
})
@@ -1327,7 +1200,7 @@ describe('AppCard', () => {
it('should export the app DSL when exporting', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.export'))
})
@@ -1352,7 +1225,7 @@ describe('AppCard', () => {
const chatApp = { ...mockApp, mode: AppModeEnum.CHAT }
render(<AppCard app={chatApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.switch'))
})
@@ -1366,7 +1239,7 @@ describe('AppCard', () => {
const chatApp = { ...mockApp, mode: AppModeEnum.CHAT }
render(<AppCard app={chatApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.switch'))
})
@@ -1386,7 +1259,7 @@ describe('AppCard', () => {
const chatApp = { ...mockApp, mode: AppModeEnum.CHAT }
render(<AppCard app={chatApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.switch'))
})
@@ -1406,7 +1279,7 @@ describe('AppCard', () => {
const chatApp = { ...mockApp, mode: AppModeEnum.CHAT }
render(<AppCard app={chatApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.switch'))
})
@@ -1426,7 +1299,7 @@ describe('AppCard', () => {
const completionApp = { ...mockApp, mode: AppModeEnum.COMPLETION }
render(<AppCard app={completionApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.switch'))
})
@@ -1441,7 +1314,7 @@ describe('AppCard', () => {
it('should show open in explore option when dropdown menu is opened', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.openInExplore')).toBeInTheDocument()
@@ -1454,7 +1327,7 @@ describe('AppCard', () => {
const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }
render(<AppCard app={workflowApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.export'))
})
@@ -1477,7 +1350,7 @@ describe('AppCard', () => {
const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }
render(<AppCard app={workflowApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.export'))
})
@@ -1491,7 +1364,7 @@ describe('AppCard', () => {
const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }
render(<AppCard app={workflowApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.export'))
})
@@ -1510,7 +1383,7 @@ describe('AppCard', () => {
const advancedChatApp = { ...mockApp, mode: AppModeEnum.ADVANCED_CHAT }
render(<AppCard app={advancedChatApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.export'))
})
@@ -1532,7 +1405,7 @@ describe('AppCard', () => {
const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }
render(<AppCard app={workflowApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.export'))
})
@@ -1623,7 +1496,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.editApp'))
})
@@ -1648,7 +1521,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.editApp'))
})
@@ -1668,7 +1541,7 @@ describe('AppCard', () => {
it('should close edit modal after successful edit', async () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.editApp'))
})
@@ -1710,7 +1583,7 @@ describe('AppCard', () => {
const chatApp = createMockApp({ mode: AppModeEnum.CHAT })
render(<AppCard app={chatApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.switch'))
})
@@ -1732,7 +1605,7 @@ describe('AppCard', () => {
const completionApp = createMockApp({ mode: AppModeEnum.COMPLETION })
const { unmount } = render(<AppCard app={completionApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.editApp')).toBeInTheDocument()
})
@@ -1743,7 +1616,7 @@ describe('AppCard', () => {
const workflowApp = createMockApp({ mode: AppModeEnum.WORKFLOW })
render(<AppCard app={workflowApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.editApp')).toBeInTheDocument()
})
@@ -1767,15 +1640,11 @@ describe('AppCard', () => {
it('should close operations menu after selecting an item', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
- await waitFor(() => {
- expect(screen.getByTestId('dropdown-menu-content')).toBeInTheDocument()
- })
-
- fireEvent.click(screen.getByText('app.editApp'))
+ fireEvent.click(getOperationsTrigger())
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'app.editApp' }))
await waitFor(() => {
- expect(screen.queryByTestId('dropdown-menu-content')).not.toBeInTheDocument()
+ expect(getOperationsTrigger()).toHaveAttribute('aria-expanded', 'false')
expect(screen.getByTestId('edit-app-modal')).toBeInTheDocument()
})
})
@@ -1783,7 +1652,7 @@ describe('AppCard', () => {
it('should click open in explore button', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
const openInExploreBtn = screen.getByText('app.openInExplore')
fireEvent.click(openInExploreBtn)
@@ -1807,7 +1676,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
const openInExploreBtn = screen.getByText('app.openInExplore')
fireEvent.click(openInExploreBtn)
@@ -1835,7 +1704,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
const openInExploreBtn = screen.getByText('app.openInExplore')
fireEvent.click(openInExploreBtn)
@@ -1858,7 +1727,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.openInExplore'))
})
@@ -1873,7 +1742,7 @@ describe('AppCard', () => {
it('should render operations menu correctly', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.editApp')).toBeInTheDocument()
expect(screen.getByText('app.duplicate')).toBeInTheDocument()
@@ -1897,12 +1766,16 @@ describe('AppCard', () => {
expect(
screen.getByRole('menuitem', { name: 'app.editApp', hidden: true }),
).toBeInTheDocument()
- expect(screen.getByTestId('dropdown-menu-positioner')).toHaveAttribute(
+ expect(
+ document.querySelector(
+ `[data-step-by-step-tour-highlight-part="${STEP_BY_STEP_TOUR_TARGETS.studioWithAppsFirstAppCardActionsMenu}"]`,
+ ),
+ ).toHaveAttribute(
'data-step-by-step-tour-highlight-part',
STEP_BY_STEP_TOUR_TARGETS.studioWithAppsFirstAppCardActionsMenu,
)
- expect(screen.getByTestId('dropdown-menu-content')).toHaveAttribute('aria-hidden', 'true')
- expect(screen.getByTestId('dropdown-menu-content')).toHaveClass('pointer-events-none')
+ expect(screen.getByRole('menu', { hidden: true })).toHaveAttribute('aria-hidden', 'true')
+ expect(screen.getByRole('menu', { hidden: true })).toHaveClass('pointer-events-none')
})
})
@@ -1914,7 +1787,7 @@ describe('AppCard', () => {
})
render(<AppCard app={workflowApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.openInExplore')).toBeInTheDocument()
})
@@ -1945,7 +1818,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
const openInExploreBtn = screen.getByText('app.openInExplore')
fireEvent.click(openInExploreBtn)
@@ -1972,7 +1845,7 @@ describe('AppCard', () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
const openInExploreBtn = screen.getByText('app.openInExplore')
fireEvent.click(openInExploreBtn)
@@ -1989,7 +1862,7 @@ describe('AppCard', () => {
const draftTriggerApp = createMockApp({ has_draft_trigger: true })
render(<AppCard app={draftTriggerApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.editApp')).toBeInTheDocument()
// openInExplore should not be shown for draft trigger apps
@@ -2014,7 +1887,7 @@ describe('AppCard', () => {
it('should show access control option when webapp_auth is enabled', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.accessControl')).toBeInTheDocument()
})
@@ -2028,7 +1901,7 @@ describe('AppCard', () => {
})
render(<AppCard app={appWithReleasePermission} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.accessControl')).toBeInTheDocument()
@@ -2043,7 +1916,7 @@ describe('AppCard', () => {
})
render(<AppCard app={appWithAccessConfigPermission} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('common.operation.delete')).toBeInTheDocument()
@@ -2061,7 +1934,7 @@ describe('AppCard', () => {
})
render(<AppCard app={appWithAccessConfigPermission} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('common.operation.delete')).toBeInTheDocument()
@@ -2077,7 +1950,7 @@ describe('AppCard', () => {
})
render(<AppCard app={appWithAccessConfigPermission} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('common.settings.resourceAccess'))
})
@@ -2088,7 +1961,7 @@ describe('AppCard', () => {
it('should click access control button', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
const accessControlBtn = screen.getByText('app.accessControl')
fireEvent.click(accessControlBtn)
@@ -2102,7 +1975,7 @@ describe('AppCard', () => {
it('should close access control modal and call onRefresh', async () => {
render(<AppCard app={mockApp} onRefresh={mockOnRefresh} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.accessControl'))
})
@@ -2122,7 +1995,7 @@ describe('AppCard', () => {
it('should close access control modal after confirm without onRefresh callback', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.accessControl'))
})
@@ -2141,7 +2014,7 @@ describe('AppCard', () => {
it('should show open in explore when userCanAccessApp is true', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.openInExplore')).toBeInTheDocument()
})
@@ -2157,7 +2030,7 @@ describe('AppCard', () => {
render(<AppCard app={workflowApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
expect(screen.getByText('app.openInExplore')).toBeInTheDocument()
})
@@ -2175,7 +2048,7 @@ describe('AppCard', () => {
it('should close access control modal when onClose is called', async () => {
render(<AppCard app={mockApp} />)
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
+ fireEvent.click(getOperationsTrigger())
await waitFor(() => {
fireEvent.click(screen.getByText('app.accessControl'))
})
@@ -2192,120 +2065,4 @@ describe('AppCard', () => {
})
})
})
-
- describe('Delete dialog guards', () => {
- const createMockAlertDialogModule = () => ({
- AlertDialog: ({
- open,
- onOpenChange,
- children,
- }: {
- open: boolean
- onOpenChange?: (open: boolean) => void
- children: React.ReactNode
- }) =>
- open ? (
- <div role="alertdialog">
- <button
- type="button"
- data-testid="keep-open-dialog"
- onClick={() => onOpenChange?.(true)}
- >
- Keep open
- </button>
- <button
- type="button"
- data-testid="force-close-dialog"
- onClick={() => onOpenChange?.(false)}
- >
- Force close
- </button>
- {children}
- </div>
- ) : null,
- AlertDialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- AlertDialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- AlertDialogDescription: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- AlertDialogActions: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- AlertDialogCancelButton: ({
- children,
- ...props
- }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button type="button" {...props}>
- {children}
- </button>
- ),
- AlertDialogConfirmButton: ({
- children,
- ...props
- }: React.ButtonHTMLAttributes<HTMLButtonElement> & { loading?: boolean }) => (
- <button type="button" {...props}>
- {children}
- </button>
- ),
- })
-
- it('should reset delete input when dialog closes', async () => {
- vi.resetModules()
- vi.doMock('@langgenius/dify-ui/alert-dialog', createMockAlertDialogModule)
-
- const { AppCard: IsolatedAppCard } = await import('../app-card')
- render(<IsolatedAppCard app={mockApp} />)
-
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
- fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
- fireEvent.change(await screen.findByRole('textbox'), { target: { value: 'partial name' } })
-
- fireEvent.click(screen.getByTestId('force-close-dialog'))
- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
-
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
- fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
-
- expect(await screen.findByRole('textbox')).toHaveValue('')
-
- vi.doUnmock('@langgenius/dify-ui/alert-dialog')
- })
-
- it('should keep delete input when dialog remains open', async () => {
- vi.resetModules()
- vi.doMock('@langgenius/dify-ui/alert-dialog', createMockAlertDialogModule)
-
- const { AppCard: IsolatedAppCard } = await import('../app-card')
- render(<IsolatedAppCard app={mockApp} />)
-
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
- fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
- fireEvent.change(await screen.findByRole('textbox'), { target: { value: 'partial name' } })
-
- fireEvent.click(screen.getByTestId('keep-open-dialog'))
-
- expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
- expect(await screen.findByRole('textbox')).toHaveValue('partial name')
-
- vi.doUnmock('@langgenius/dify-ui/alert-dialog')
- })
-
- it('should keep delete dialog open when close is requested during deletion', async () => {
- vi.resetModules()
- mockDeleteMutationPending = true
- vi.doMock('@langgenius/dify-ui/alert-dialog', createMockAlertDialogModule)
-
- const { AppCard: IsolatedAppCard } = await import('../app-card')
- render(<IsolatedAppCard app={mockApp} />)
-
- fireEvent.click(screen.getByTestId('dropdown-menu-trigger'))
- fireEvent.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
- expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
-
- fireEvent.click(screen.getByTestId('force-close-dialog'))
-
- expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
-
- vi.doUnmock('@langgenius/dify-ui/alert-dialog')
- mockDeleteMutationPending = false
- })
- })
})
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/header-in-mobile.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/header-in-mobile.spec.tsx
index 843adb7f5d7..d0f33161106 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/header-in-mobile.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/header-in-mobile.spec.tsx
@@ -37,23 +37,6 @@ vi.mock('@/next/navigation', () => ({
useParams: vi.fn(() => ({})),
}))
-vi.mock('@langgenius/dify-ui/dropdown-menu', () => import('@/__mocks__/base-ui-dropdown-menu'))
-vi.mock('@langgenius/dify-ui/tooltip', () => import('@/__mocks__/base-ui-tooltip'))
-
-// Mock Dialog to avoid Base UI focus/portal behavior in tests
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, open }: { children: React.ReactNode; open?: boolean }) => {
- if (!open) return null
- return <div data-testid="modal">{children}</div>
- },
- DialogContent: ({ children }: { children: React.ReactNode }) => (
- <div role="dialog" data-testid="modal-content">
- {children}
- </div>
- ),
- DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
// Sidebar mock removed to use real component
const mockAppData: AppData = {
diff --git a/web/app/components/base/chat/chat-with-history/header/__tests__/index.spec.tsx b/web/app/components/base/chat/chat-with-history/header/__tests__/index.spec.tsx
index b1335a13981..9756de3530e 100644
--- a/web/app/components/base/chat/chat-with-history/header/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/header/__tests__/index.spec.tsx
@@ -16,23 +16,6 @@ vi.mock('@/app/components/base/chat/chat-with-history/inputs-form/content', () =
default: () => <div data-testid="inputs-form-content">InputsFormContent</div>,
}))
-vi.mock('@langgenius/dify-ui/dropdown-menu', () => import('@/__mocks__/base-ui-dropdown-menu'))
-vi.mock('@langgenius/dify-ui/tooltip', () => import('@/__mocks__/base-ui-tooltip'))
-
-// Mock Dialog to avoid Base UI focus/portal behavior in tests
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, open }: { children: React.ReactNode; open?: boolean }) => {
- if (!open) return null
- return <div data-testid="modal">{children}</div>
- },
- DialogContent: ({ children }: { children: React.ReactNode }) => (
- <div role="dialog" data-testid="modal-content">
- {children}
- </div>
- ),
- DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
const mockAppData: AppData = {
app_id: 'app-1',
site: {
diff --git a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
index d4f909963e1..23e7430dcf2 100644
--- a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
@@ -85,17 +85,6 @@ vi.mock('@/next/navigation', () => ({
usePathname: () => '/test',
}))
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, open }: { children: React.ReactNode; open?: boolean }) =>
- open === false ? null : <>{children}</>,
- DialogContent: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="modal">{children}</div>
- ),
- DialogTitle: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="modal-title">{children}</div>
- ),
-}))
-
describe('Sidebar Index', () => {
const mockContextValue = {
isInstalledApp: false,
diff --git a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/rename-modal.spec.tsx b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/rename-modal.spec.tsx
index 3a9c3c97e67..aff1a1bc7bc 100644
--- a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/rename-modal.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/rename-modal.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as ReactI18next from 'react-i18next'
@@ -6,13 +5,6 @@ import { expectLoadingButton } from '@/test/button'
import { withSelectorKey } from '@/test/i18n-mock'
import RenameModal from '../rename-modal'
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, open }: { children: ReactNode; open?: boolean }) =>
- open === false ? null : <>{children}</>,
- DialogContent: ({ children }: { children: ReactNode }) => <div role="dialog">{children}</div>,
- DialogTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>,
-}))
-
describe('RenameModal', () => {
const defaultProps = {
isShow: true,
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/field-renderer.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/field-renderer.spec.tsx
index b450277debf..5e7a12920c2 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/field-renderer.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/field-renderer.spec.tsx
@@ -5,80 +5,6 @@ import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/
import { TransferMethod } from '@/types/app'
import HumanInputFieldRenderer from '../field-renderer'
-function MockTextarea({
- value,
- onChange,
- onValueChange,
- ...props
-}: {
- value: string
- onChange?: (event: { target: { value: string } }) => void
- onValueChange?: (value: string) => void
-} & React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
- return (
- <textarea
- data-testid="content-item-textarea"
- value={value}
- onChange={(event) => {
- onChange?.({ target: { value: event.target.value } })
- onValueChange?.(event.target.value)
- }}
- {...props}
- />
- )
-}
-
-vi.mock('@langgenius/dify-ui/textarea', () => ({
- Textarea: MockTextarea,
-}))
-
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
- const SelectValueContext = React.createContext<string | null>(null)
-
- return {
- Select: ({
- children,
- onValueChange,
- value,
- }: {
- children: React.ReactNode
- onValueChange: (value: string | null) => void
- value: string | null
- }) => (
- <SelectValueContext value={value}>
- <div>
- <button
- type="button"
- data-testid="content-item-select-root"
- onClick={() => onValueChange('alice')}
- >
- select alice
- </button>
- <button
- type="button"
- data-testid="content-item-select-null"
- onClick={() => onValueChange(null)}
- >
- select null
- </button>
- {children}
- </div>
- </SelectValueContext>
- ),
- SelectValue: () => <>{React.use(SelectValueContext)}</>,
- SelectTrigger: ({ children }: { children: React.ReactNode }) => (
- <button type="button" data-testid="content-item-select">
- {children}
- </button>
- ),
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItemText: ({ children }: { children: React.ReactNode }) => <span>{children}</span>,
- SelectItemIndicator: () => <span>selected</span>,
- }
-})
-
vi.mock('@/app/components/base/file-uploader', () => ({
FileUploaderInAttachmentWrapper: ({
value,
@@ -191,34 +117,12 @@ describe('HumanInputFieldRenderer', () => {
/>,
)
- await user.click(screen.getByTestId('content-item-select-root'))
+ await user.click(screen.getByRole('combobox', { name: 'reviewer' }))
+ await user.click(await screen.findByRole('option', { name: 'alice' }))
expect(onChange).toHaveBeenCalledWith('alice')
})
- it('ignores null select values', async () => {
- const user = userEvent.setup()
- const onChange = vi.fn()
-
- render(
- <HumanInputFieldRenderer
- field={{
- type: InputVarType.select,
- output_variable_name: 'reviewer',
- option_source: { type: 'constant', selector: [], value: ['alice', 'bob'] },
- }}
- value={null}
- onChange={onChange}
- />,
- )
-
- expect(screen.getByTestId('content-item-select')).toHaveTextContent('')
-
- await user.click(screen.getByTestId('content-item-select-null'))
-
- expect(onChange).not.toHaveBeenCalled()
- })
-
it('renders single-file input and emits one file', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
diff --git a/web/app/components/base/chat/chat/citation/__tests__/popup.spec.tsx b/web/app/components/base/chat/chat/citation/__tests__/popup.spec.tsx
index fb7954d1934..dd18d2073dc 100644
--- a/web/app/components/base/chat/chat/citation/__tests__/popup.spec.tsx
+++ b/web/app/components/base/chat/chat/citation/__tests__/popup.spec.tsx
@@ -1,12 +1,10 @@
import type { Resources } from '../index'
-import { render, screen, waitFor } from '@testing-library/react'
+import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useDocumentDownload } from '@/service/knowledge/use-document'
import { downloadUrl } from '@/utils/download'
import Popup from '../popup'
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-
vi.mock('@/service/knowledge/use-document', () => ({
useDocumentDownload: vi.fn(),
}))
@@ -65,8 +63,12 @@ const makeData = (overrides: Partial<Resources> = {}): Resources => ({
const openPopup = async (user: ReturnType<typeof userEvent.setup>) => {
await user.click(screen.getByTestId('popup-trigger'))
}
-const getDownloadButton = (name = 'report.pdf') => screen.getByRole('button', { name })
-const queryDownloadButton = (name = 'report.pdf') => screen.queryByRole('button', { name })
+const getDownloadButton = (name = 'report.pdf') =>
+ within(screen.getByTestId('popup-content')).getByRole('button', { name })
+const queryDownloadButton = (name = 'report.pdf') =>
+ screen.queryByTestId('popup-content')
+ ? within(screen.getByTestId('popup-content')).queryByRole('button', { name })
+ : null
describe('Popup', () => {
beforeEach(() => {
diff --git a/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.spec.tsx b/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.spec.tsx
index 0a530b716b1..5f7b5fc1233 100644
--- a/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.spec.tsx
+++ b/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.spec.tsx
@@ -1,31 +1,9 @@
import type { DatePickerProps } from '../../types'
-import { act, fireEvent, render, screen, within } from '@testing-library/react'
+import { fireEvent, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import dayjs from '../../utils/dayjs'
import DatePicker from '../index'
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- disabled,
- className,
- }: {
- children?: React.ReactNode
- onClick?: () => void
- disabled?: boolean
- className?: string
- }) => (
- <button
- onClick={onClick as (() => void) | undefined}
- disabled={disabled as boolean | undefined}
- className={className as string | undefined}
- >
- {children}
- </button>
- ),
-}))
-
// Mock scrollIntoView
beforeAll(() => {
Element.prototype.scrollIntoView = vi.fn()
@@ -131,19 +109,18 @@ describe('DatePicker', () => {
expect(screen.getByText(/2024/))!.toBeInTheDocument()
})
- it('should close when clicking outside the container', () => {
+ it('should close when clicking outside the container', async () => {
+ const user = userEvent.setup()
const props = createDatePickerProps()
render(<DatePicker {...props} />)
openPicker()
- expect(screen.getByTestId('popover')).toHaveAttribute('data-open', 'true')
+ expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)
- act(() => {
- document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }))
- })
+ await user.click(document.body)
- expect(screen.getByTestId('popover')).toHaveAttribute('data-open', 'false')
- expect(screen.getByRole('textbox'))!.toBeInTheDocument()
+ expect(screen.queryAllByText(/daysInWeek/)).toHaveLength(0)
+ expect(screen.getByRole('textbox')).toBeInTheDocument()
})
})
diff --git a/web/app/components/base/date-and-time-picker/time-picker/__tests__/index.spec.tsx b/web/app/components/base/date-and-time-picker/time-picker/__tests__/index.spec.tsx
index 17c9cdfce21..3e7ef7a4d61 100644
--- a/web/app/components/base/date-and-time-picker/time-picker/__tests__/index.spec.tsx
+++ b/web/app/components/base/date-and-time-picker/time-picker/__tests__/index.spec.tsx
@@ -1,31 +1,9 @@
import type { TimePickerProps } from '../../types'
import { fireEvent, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import dayjs, { isDayjsObject } from '../../utils/dayjs'
import TimePicker from '../index'
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- disabled,
- className,
- }: {
- children?: React.ReactNode
- onClick?: () => void
- disabled?: boolean
- className?: string
- }) => (
- <button
- onClick={onClick as (() => void) | undefined}
- disabled={disabled as boolean | undefined}
- className={className as string | undefined}
- >
- {children}
- </button>
- ),
-}))
-
// Mock scrollIntoView since the test DOM runtime doesn't implement it
beforeAll(() => {
Element.prototype.scrollIntoView = vi.fn()
@@ -103,15 +81,16 @@ describe('TimePicker', () => {
expect(input)!.toHaveValue('10:00 AM')
})
- it('should handle document mousedown listener while picker is open', () => {
+ it('should close when clicking outside while the picker is open', async () => {
+ const user = userEvent.setup()
render(<TimePicker {...baseProps} value="10:00 AM" timezone="UTC" />)
const input = screen.getByRole('textbox')
fireEvent.click(input)
expect(input)!.toHaveValue('')
- fireEvent.mouseDown(document.body)
- expect(input)!.toHaveValue('10:00 AM')
+ await user.click(document.body)
+ expect(input).toHaveValue('10:00 AM')
})
it('should call onClear when clear is clicked while picker is closed', () => {
diff --git a/web/app/components/base/features/new-feature-panel/text-to-speech/__tests__/voice-settings.spec.tsx b/web/app/components/base/features/new-feature-panel/text-to-speech/__tests__/voice-settings.spec.tsx
index 5f7c2eb9274..5101c5345f3 100644
--- a/web/app/components/base/features/new-feature-panel/text-to-speech/__tests__/voice-settings.spec.tsx
+++ b/web/app/components/base/features/new-feature-panel/text-to-speech/__tests__/voice-settings.spec.tsx
@@ -3,8 +3,6 @@ import type { Features } from '../../../types'
import { fireEvent, render, screen } from '@testing-library/react'
import { FeaturesProvider } from '../../../context'
import VoiceSettings from '../voice-settings'
-
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
vi.mock('@langgenius/dify-ui/toast', () => ({
toast: {
success: vi.fn(),
@@ -25,25 +23,6 @@ vi.mock('@/service/use-apps', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/switch', () => ({
- Switch: ({
- checked,
- onCheckedChange,
- ...props
- }: {
- checked?: boolean
- onCheckedChange?: (checked: boolean) => void
- }) => (
- <button
- type="button"
- data-testid="switch"
- data-checked={String(checked)}
- onClick={() => onCheckedChange?.(!checked)}
- {...props}
- />
- ),
-}))
-
const defaultFeatures: Features = {
moreLikeThis: { enabled: false },
opening: { enabled: false },
@@ -123,16 +102,4 @@ describe('VoiceSettings', () => {
expect(onOpen).toHaveBeenCalledWith(false)
})
-
- it('should use top placement and mainAxis 4 when placementLeft is false', () => {
- renderWithProvider(
- <VoiceSettings open={true} onOpen={vi.fn()} placementLeft={false}>
- <button>Settings</button>
- </VoiceSettings>,
- )
-
- const content = screen.getByTestId('popover-content')
- expect(content).toHaveAttribute('data-placement', 'top')
- expect(content).toHaveAttribute('data-side-offset', '4')
- })
})
diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx
index 3d236c5a2bb..6173b23ff88 100644
--- a/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx
@@ -1,57 +1,29 @@
import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'
-import type { ButtonHTMLAttributes, ReactNode } from 'react'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { $getNodeByKey } from 'lexical'
import AgentOutputBlockComponent from '../component'
-const { mockEditorFocus, mockEditorUpdate, mockGetRootText, mockSelectNext, mockSetOutput } =
- vi.hoisted(() => ({
- mockEditorFocus: vi.fn(),
- mockEditorUpdate: vi.fn((callback: () => void) => callback()),
- mockGetRootText: {
- value: '[§output:summary:summary§]',
- },
- mockSelectNext: vi.fn(),
- mockSetOutput: vi.fn(),
- }))
+const {
+ mockEditorFocus,
+ mockEditorUpdate,
+ mockGetRootText,
+ mockSelectNext,
+ mockSetOpenTypeSelectOnEdit,
+ mockSetOutput,
+} = vi.hoisted(() => ({
+ mockEditorFocus: vi.fn(),
+ mockEditorUpdate: vi.fn((callback: () => void) => callback()),
+ mockGetRootText: {
+ value: '[§output:summary:summary§]',
+ },
+ mockSelectNext: vi.fn(),
+ mockSetOpenTypeSelectOnEdit: vi.fn(),
+ mockSetOutput: vi.fn(),
+}))
vi.mock('@lexical/react/LexicalComposerContext')
-vi.mock('@langgenius/dify-ui/select', () => ({
- Select: ({
- children,
- onValueChange,
- open,
- }: {
- children: ReactNode
- onValueChange: (value: string) => void
- open?: boolean
- }) => (
- <div>
- <span data-testid="type-select-state">{open ? 'open' : 'closed'}</span>
- {children}
- <button type="button" onClick={() => onValueChange('file')}>
- Select file
- </button>
- </div>
- ),
- SelectContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- SelectItemIndicator: () => <span />,
- SelectItemText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- SelectLabel: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- SelectTrigger: ({
- children,
- onClick,
- onMouseDown,
- ...props
- }: ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button type="button" onClick={onClick} onMouseDown={onMouseDown} {...props}>
- {children}
- </button>
- ),
-}))
vi.mock('lexical', async (importOriginal) => {
const actual = await importOriginal<typeof import('lexical')>()
@@ -69,7 +41,7 @@ vi.mock('lexical', async (importOriginal) => {
})
vi.mock('../node', () => ({
- $isAgentOutputBlockNode: () => true,
+ $isAgentOutputBlockNode: (node: unknown) => Boolean(node),
}))
const outputs: DeclaredOutputConfig[] = [
@@ -93,6 +65,7 @@ describe('AgentOutputBlockComponent', () => {
] as unknown as ReturnType<typeof useLexicalComposerContext>)
vi.mocked($getNodeByKey).mockReturnValue({
selectNext: mockSelectNext,
+ setOpenTypeSelectOnEdit: mockSetOpenTypeSelectOnEdit,
setOutput: mockSetOutput,
} as never)
})
@@ -151,7 +124,9 @@ describe('AgentOutputBlockComponent', () => {
/>,
)
- expect(screen.getByTestId('type-select-state')).toHaveTextContent('open')
+ expect(
+ screen.getByRole('combobox', { name: 'workflow.nodes.agent.outputVars.typeLabel' }),
+ ).toHaveAttribute('aria-expanded', 'true')
})
it('does not update the Lexical node while typing an output name and commits on blur', async () => {
@@ -248,7 +223,9 @@ describe('AgentOutputBlockComponent', () => {
false,
)
expect(mockSelectNext).toHaveBeenCalledTimes(1)
- expect(screen.getByTestId('type-select-state')).toHaveTextContent('closed')
+ expect(
+ screen.getByRole('combobox', { name: 'workflow.nodes.agent.outputVars.typeLabel' }),
+ ).toHaveAttribute('aria-expanded', 'false')
expect(onChange).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
@@ -300,7 +277,9 @@ describe('AgentOutputBlockComponent', () => {
true,
)
expect(mockSelectNext).not.toHaveBeenCalled()
- expect(screen.getByTestId('type-select-state')).toHaveTextContent('open')
+ expect(
+ screen.getByRole('combobox', { name: 'workflow.nodes.agent.outputVars.typeLabel' }),
+ ).toHaveAttribute('aria-expanded', 'true')
expect(input).not.toHaveFocus()
expect((input as HTMLInputElement).selectionStart).toBe('summary'.length)
expect((input as HTMLInputElement).selectionEnd).toBe('summary'.length)
@@ -374,7 +353,8 @@ describe('AgentOutputBlockComponent', () => {
expect(onChange).not.toHaveBeenCalled()
})
- it('does not commit the name blur before selecting an output type', () => {
+ it('does not commit the name blur before selecting an output type', async () => {
+ const user = userEvent.setup()
const onChange = vi.fn()
mockGetRootText.value = '[§output:summary:summary§]'
@@ -390,17 +370,16 @@ describe('AgentOutputBlockComponent', () => {
)
const input = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })
- const typeTrigger = screen.getByRole('button', {
+ const typeTrigger = screen.getByRole('combobox', {
name: 'workflow.nodes.agent.outputVars.typeLabel',
})
fireEvent.change(input, { target: { value: 'summary' } })
- fireEvent.mouseDown(typeTrigger)
- fireEvent.blur(input)
+ await user.click(typeTrigger)
expect(onChange).not.toHaveBeenCalled()
- fireEvent.click(screen.getByRole('button', { name: 'Select file' }))
+ await user.click(await screen.findByRole('option', { name: 'file' }))
expect(mockSetOutput).toHaveBeenCalledWith(
'summary',
@@ -461,7 +440,7 @@ describe('AgentOutputBlockComponent', () => {
screen.queryByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' }),
).not.toBeInTheDocument()
expect(
- screen.queryByRole('button', { name: 'workflow.nodes.agent.outputVars.typeLabel' }),
+ screen.queryByRole('combobox', { name: 'workflow.nodes.agent.outputVars.typeLabel' }),
).not.toBeInTheDocument()
expect(screen.getByText('qna_report_pdf')).toBeInTheDocument()
expect(screen.getByText('file')).toBeInTheDocument()
diff --git a/web/app/components/base/prompt-editor/plugins/context-block/__tests__/component.spec.tsx b/web/app/components/base/prompt-editor/plugins/context-block/__tests__/component.spec.tsx
index 6c2a0b12374..3b97586a3b8 100644
--- a/web/app/components/base/prompt-editor/plugins/context-block/__tests__/component.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/context-block/__tests__/component.spec.tsx
@@ -3,8 +3,6 @@ import userEvent from '@testing-library/user-event'
import { UPDATE_DATASETS_EVENT_EMITTER } from '../../../constants'
import ContextBlockComponent from '../component'
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-
// Mock the hooks used by ContextBlockComponent
const mockUseSelectOrDelete = vi.fn()
const mockUseTrigger = vi.fn()
@@ -148,17 +146,6 @@ describe('ContextBlockComponent', () => {
})
describe('User Interactions', () => {
- it('should keep the popover closed when the trigger prevents the default click', async () => {
- const user = userEvent.setup()
- const { triggerSetOpen } = defaultSetup()
- render(<ContextBlockComponent nodeKey="test-key" onAddContext={vi.fn()} />)
-
- await user.click(screen.getByTestId('popover-trigger'))
-
- expect(triggerSetOpen).not.toHaveBeenCalled()
- expect(screen.queryByText('common.promptEditor.context.modal.add')).not.toBeInTheDocument()
- })
-
it('should call onAddContext when add button is clicked', async () => {
defaultSetup({ open: true })
const handleAddContext = vi.fn()
diff --git a/web/app/components/base/prompt-editor/plugins/history-block/__tests__/component.spec.tsx b/web/app/components/base/prompt-editor/plugins/history-block/__tests__/component.spec.tsx
index 184112633b1..894758c0b05 100644
--- a/web/app/components/base/prompt-editor/plugins/history-block/__tests__/component.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/history-block/__tests__/component.spec.tsx
@@ -6,8 +6,6 @@ import { UPDATE_HISTORY_EVENT_EMITTER } from '../../../constants'
import HistoryBlockComponent from '../component'
import { DELETE_HISTORY_BLOCK_COMMAND } from '../index'
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-
type HistoryEventPayload = {
type?: string
payload?: RoleName
@@ -99,19 +97,6 @@ describe('HistoryBlockComponent', () => {
expect(screen.getByText('common.promptEditor.history.modal.assistant')).toBeInTheDocument()
})
- it('should keep the popover closed when the trigger prevents the default click', async () => {
- const user = userEvent.setup()
- const setOpen = vi.fn() as unknown as Dispatch<SetStateAction<boolean>>
- mockUseTrigger.mockReturnValue(createTriggerHookReturn(false, setOpen))
-
- render(<HistoryBlockComponent nodeKey="history-node-trigger" onEditRole={vi.fn()} />)
-
- await user.click(screen.getByTestId('popover-trigger'))
-
- expect(setOpen).not.toHaveBeenCalled()
- expect(screen.queryByText('common.promptEditor.history.modal.edit')).not.toBeInTheDocument()
- })
-
it('should call onEditRole when edit action is clicked', async () => {
const user = userEvent.setup()
const onEditRole = vi.fn()
diff --git a/web/app/components/billing/pricing/__tests__/dialog.spec.tsx b/web/app/components/billing/pricing/__tests__/dialog.spec.tsx
index 8a73976e8db..e7387d05022 100644
--- a/web/app/components/billing/pricing/__tests__/dialog.spec.tsx
+++ b/web/app/components/billing/pricing/__tests__/dialog.spec.tsx
@@ -1,31 +1,15 @@
-import type { ReactNode } from 'react'
import type { Mock } from 'vitest'
import type { UsagePlanInfo } from '../../type'
+import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { useGetPricingPageLanguage } from '@/context/i18n'
import { useProviderContext } from '@/context/provider-context'
import { render } from '@/test/console/render'
import { Plan } from '../../type'
import Pricing from '../index'
-type DialogProps = {
- children: ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
-}
-
-let latestOnOpenChange: DialogProps['onOpenChange']
let mockConsoleState: Record<string, unknown> = {}
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, onOpenChange }: DialogProps) => {
- latestOnOpenChange = onOpenChange
- return <div>{children}</div>
- },
- DialogContent: ({ children, className }: { children: ReactNode; className?: string }) => (
- <div className={className}>{children}</div>
- ),
-}))
-
vi.mock('../header', () => ({
default: ({ onClose }: { onClose: () => void }) => (
<button type="button" onClick={onClose}>
@@ -72,7 +56,6 @@ const buildUsage = (): UsagePlanInfo => ({
describe('Pricing dialog lifecycle', () => {
beforeEach(() => {
vi.clearAllMocks()
- latestOnOpenChange = undefined
mockConsoleState = {
isCurrentWorkspaceManager: true,
}
@@ -86,12 +69,12 @@ describe('Pricing dialog lifecycle', () => {
;(useGetPricingPageLanguage as Mock).mockReturnValue('en')
})
- it('should only call onCancel when the dialog requests closing', () => {
+ it('should call onCancel when the pricing dialog is closed', async () => {
+ const user = userEvent.setup()
const onCancel = vi.fn()
render(<Pricing onCancel={onCancel} />)
- latestOnOpenChange?.(true)
- latestOnOpenChange?.(false)
+ await user.click(screen.getByRole('button', { name: 'close' }))
expect(onCancel).toHaveBeenCalledTimes(1)
})
diff --git a/web/app/components/datasets/common/document-picker/__tests__/preview-document-picker.spec.tsx b/web/app/components/datasets/common/document-picker/__tests__/preview-document-picker.spec.tsx
index 353ce77eed3..e14398f4f45 100644
--- a/web/app/components/datasets/common/document-picker/__tests__/preview-document-picker.spec.tsx
+++ b/web/app/components/datasets/common/document-picker/__tests__/preview-document-picker.spec.tsx
@@ -1,515 +1,47 @@
import type { DocumentItem } from '@/models/datasets'
import { fireEvent, render, screen } from '@testing-library/react'
-import * as React from 'react'
import PreviewDocumentPicker from '../preview-document-picker'
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
-// Factory function to create mock DocumentItem
-const createMockDocumentItem = (overrides: Partial<DocumentItem> = {}): DocumentItem => ({
- id: `doc-${Math.random().toString(36).substr(2, 9)}`,
- name: 'Test Document',
- extension: 'txt',
- ...overrides,
-})
-
-// Factory function to create multiple document items
-const createMockDocumentList = (count: number): DocumentItem[] => {
- return Array.from({ length: count }, (_, index) =>
- createMockDocumentItem({
- id: `doc-${index + 1}`,
- name: `Document ${index + 1}`,
- extension: index % 2 === 0 ? 'pdf' : 'txt',
- }),
- )
-}
-
-// Factory function to create default props
-const createDefaultProps = (
- overrides: Partial<React.ComponentProps<typeof PreviewDocumentPicker>> = {},
-) => ({
- value: createMockDocumentItem({ id: 'selected-doc', name: 'Selected Document' }),
- files: createMockDocumentList(3),
- onChange: vi.fn(),
- ...overrides,
-})
-
-// Helper to render component with default props
-const renderComponent = (
- props: Partial<React.ComponentProps<typeof PreviewDocumentPicker>> = {},
-) => {
- const defaultProps = createDefaultProps(props)
- return {
- ...render(<PreviewDocumentPicker {...defaultProps} />),
- props: defaultProps,
- }
-}
-
-const openPopover = () => {
- fireEvent.click(screen.getByTestId('popover-trigger'))
-}
+const documents: DocumentItem[] = [
+ { id: 'document-1', name: 'First document', extension: 'pdf' } as DocumentItem,
+ { id: 'document-2', name: 'Second document', extension: 'txt' } as DocumentItem,
+]
describe('PreviewDocumentPicker', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- // Tests for basic rendering
- describe('Rendering', () => {
- it('should render document name from value prop', () => {
- renderComponent({
- value: createMockDocumentItem({ name: 'My Document' }),
- })
-
- expect(screen.getByText('My Document')).toBeInTheDocument()
- })
-
- it('should render placeholder when name is empty', () => {
- renderComponent({
- value: createMockDocumentItem({ name: '' }),
- })
-
- expect(screen.getByText('--')).toBeInTheDocument()
- })
-
- it('should render placeholder when name is undefined', () => {
- renderComponent({
- value: { id: 'doc-1', extension: 'txt' } as DocumentItem,
- })
-
- expect(screen.getByText('--')).toBeInTheDocument()
- })
-
- it('should render file icon', () => {
- renderComponent({
- value: createMockDocumentItem({ extension: 'txt' }),
- files: [], // Use empty files to avoid duplicate icons
- })
-
- const trigger = screen.getByTestId('popover-trigger')
- expect(trigger.querySelector('svg')).toBeInTheDocument()
- })
-
- it('should render pdf icon for pdf extension', () => {
- renderComponent({
- value: createMockDocumentItem({ extension: 'pdf' }),
- files: [], // Use empty files to avoid duplicate icons
- })
-
- const trigger = screen.getByTestId('popover-trigger')
- expect(trigger.querySelector('svg')).toBeInTheDocument()
- })
- })
-
- // Tests for props handling
- describe('Props', () => {
- it('should accept required props', () => {
- const props = createDefaultProps()
- render(<PreviewDocumentPicker {...props} />)
-
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
-
- it('should handle single file', () => {
- // Component should accept single file
- renderComponent({
- files: [createMockDocumentItem({ id: 'single-doc', name: 'Single File' })],
- })
-
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
-
- it('should handle multiple files', () => {
- // Component should accept multiple files
- renderComponent({
- files: createMockDocumentList(5),
- })
-
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
-
- it('should use value.extension for file icon', () => {
- renderComponent({
- value: createMockDocumentItem({ name: 'test.docx', extension: 'docx' }),
- })
+ it('renders the selected document name', () => {
+ render(<PreviewDocumentPicker value={documents[0]} files={documents} onChange={vi.fn()} />)
- const trigger = screen.getByTestId('popover-trigger')
- expect(trigger.querySelector('svg')).toBeInTheDocument()
- })
+ expect(screen.getByRole('button', { name: /First document/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ )
})
- // Tests for state management
- describe('State Management', () => {
- it('should initialize with popup closed', () => {
- renderComponent()
+ it('opens the document list and selects a document', async () => {
+ const onChange = vi.fn()
+ render(<PreviewDocumentPicker value={documents[0]} files={documents} onChange={onChange} />)
- expect(screen.getByTestId('popover')).toHaveAttribute('data-open', 'false')
- })
+ fireEvent.click(screen.getByRole('button', { name: /First document/ }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Second document' }))
- it('should toggle popup when trigger is clicked', () => {
- renderComponent()
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- expect(trigger).toBeInTheDocument()
- })
-
- it('should render portal content for document selection', () => {
- renderComponent()
- openPopover()
-
- // Popover content is rendered after opening the trigger in our mock
- expect(screen.getByTestId('popover-content')).toBeInTheDocument()
- })
- })
-
- // Tests for callback stability and memoization
- describe('Callback Stability', () => {
- it('should maintain stable onChange callback when value changes', () => {
- const onChange = vi.fn()
- const value1 = createMockDocumentItem({ id: 'doc-1', name: 'Doc 1' })
- const value2 = createMockDocumentItem({ id: 'doc-2', name: 'Doc 2' })
-
- const { rerender } = render(
- <PreviewDocumentPicker
- value={value1}
- files={createMockDocumentList(3)}
- onChange={onChange}
- />,
- )
-
- rerender(
- <PreviewDocumentPicker
- value={value2}
- files={createMockDocumentList(3)}
- onChange={onChange}
- />,
- )
-
- expect(screen.getByText('Doc 2')).toBeInTheDocument()
- })
-
- it('should use updated onChange callback after rerender', () => {
- const onChange1 = vi.fn()
- const onChange2 = vi.fn()
- const value = createMockDocumentItem()
- const files = createMockDocumentList(3)
-
- const { rerender } = render(
- <PreviewDocumentPicker value={value} files={files} onChange={onChange1} />,
- )
-
- rerender(<PreviewDocumentPicker value={value} files={files} onChange={onChange2} />)
-
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
+ expect(onChange).toHaveBeenCalledWith(documents[1])
+ expect(screen.getByRole('button', { name: /First document/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ )
})
- // Tests for component memoization
- describe('Component Memoization', () => {
- it('should not re-render when props are the same', () => {
- const onChange = vi.fn()
- const value = createMockDocumentItem()
- const files = createMockDocumentList(3)
+ it('renders a placeholder without a selected document', () => {
+ render(<PreviewDocumentPicker files={documents} onChange={vi.fn()} />)
- const { rerender } = render(
- <PreviewDocumentPicker value={value} files={files} onChange={onChange} />,
- )
-
- rerender(<PreviewDocumentPicker value={value} files={files} onChange={onChange} />)
-
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
+ expect(screen.getByRole('button', { name: /--/ })).toBeInTheDocument()
})
- // Tests for user interactions
- describe('User Interactions', () => {
- it('should toggle popup when trigger is clicked', () => {
- renderComponent()
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- expect(trigger).toBeInTheDocument()
- })
-
- it('should render document list with files', () => {
- const files = createMockDocumentList(3)
- renderComponent({ files })
- openPopover()
-
- // Documents should be visible in the list
- expect(screen.getByText('Document 1')).toBeInTheDocument()
- expect(screen.getByText('Document 2')).toBeInTheDocument()
- expect(screen.getByText('Document 3')).toBeInTheDocument()
- })
-
- it('should call onChange when document is selected', () => {
- const onChange = vi.fn()
- const files = createMockDocumentList(3)
-
- renderComponent({ files, onChange })
- openPopover()
-
- fireEvent.click(screen.getByText('Document 2'))
-
- // handleChange should call onChange with the selected item
- expect(onChange).toHaveBeenCalledTimes(1)
- expect(onChange).toHaveBeenCalledWith(files[1])
- })
-
- it('should handle rapid toggle clicks', () => {
- renderComponent()
-
- const trigger = screen.getByTestId('popover-trigger')
-
- // Rapid clicks
- fireEvent.click(trigger)
- fireEvent.click(trigger)
- fireEvent.click(trigger)
- fireEvent.click(trigger)
-
- expect(trigger).toBeInTheDocument()
- })
- })
-
- // Tests for edge cases
- describe('Edge Cases', () => {
- it('should handle null value properties gracefully', () => {
- renderComponent({
- value: { id: 'doc-1', name: '', extension: '' },
- })
-
- expect(screen.getByText('--')).toBeInTheDocument()
- })
-
- it('should render when value prop is omitted (optional)', () => {
- const files = createMockDocumentList(2)
- const onChange = vi.fn()
- // Do not pass `value` at all to verify optional behavior
- render(<PreviewDocumentPicker files={files} onChange={onChange} />)
-
- // Renders placeholder for missing name
- expect(screen.getByText('--')).toBeInTheDocument()
- // Portal wrapper renders
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
-
- it('should handle very long document names', () => {
- const longName = 'A'.repeat(500)
- renderComponent({
- value: createMockDocumentItem({ name: longName }),
- })
-
- expect(screen.getByText(longName)).toBeInTheDocument()
- })
-
- it('should handle special characters in document name', () => {
- const specialName = '<script>alert("xss")</script>'
- renderComponent({
- value: createMockDocumentItem({ name: specialName }),
- })
-
- expect(screen.getByText(specialName)).toBeInTheDocument()
- })
-
- it('should handle large number of files', () => {
- const manyFiles = createMockDocumentList(100)
- renderComponent({ files: manyFiles })
-
- // Component should accept large files array
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
-
- it('should handle files with same name but different extensions', () => {
- const files = [
- createMockDocumentItem({ id: 'doc-1', name: 'document', extension: 'pdf' }),
- createMockDocumentItem({ id: 'doc-2', name: 'document', extension: 'txt' }),
- ]
- renderComponent({ files })
-
- // Component should handle duplicate names
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
- })
-
- // Tests for prop variations
- describe('Prop Variations', () => {
- describe('value variations', () => {
- it('should handle value with all fields', () => {
- renderComponent({
- value: {
- id: 'full-doc',
- name: 'Full Document',
- extension: 'pdf',
- },
- })
-
- expect(screen.getByText('Full Document')).toBeInTheDocument()
- })
-
- it('should handle value with minimal fields', () => {
- renderComponent({
- value: { id: 'minimal', name: '', extension: '' },
- })
-
- expect(screen.getByText('--')).toBeInTheDocument()
- })
- })
-
- describe('files variations', () => {
- it('should handle single file', () => {
- renderComponent({
- files: [createMockDocumentItem({ name: 'Single' })],
- })
-
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
-
- it('should handle two files', () => {
- renderComponent({
- files: createMockDocumentList(2),
- })
-
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
-
- it('should handle many files', () => {
- renderComponent({
- files: createMockDocumentList(50),
- })
-
- expect(screen.getByTestId('popover')).toBeInTheDocument()
- })
- })
-
- describe('extension variations', () => {
- const extensions = ['txt', 'pdf', 'docx', 'xlsx', 'md']
-
- it.each(extensions)('should render icon for %s extension', (ext) => {
- renderComponent({
- value: createMockDocumentItem({ extension: ext }),
- files: [], // Use empty files to avoid duplicate icons
- })
-
- const trigger = screen.getByTestId('popover-trigger')
- expect(trigger.querySelector('svg')).toBeInTheDocument()
- })
- })
- })
-
- // Tests for document list rendering
- describe('Document List Rendering', () => {
- it('should render all documents in the list', () => {
- const files = createMockDocumentList(5)
- renderComponent({ files })
- openPopover()
-
- // All documents should be visible
- files.forEach((file) => {
- expect(screen.getByText(file.name)).toBeInTheDocument()
- })
- })
-
- it('should pass onChange handler to DocumentList', () => {
- const onChange = vi.fn()
- const files = createMockDocumentList(3)
-
- renderComponent({ files, onChange })
- openPopover()
-
- fireEvent.click(screen.getByText('Document 1'))
-
- expect(onChange).toHaveBeenCalledWith(files[0])
- })
-
- it('should show count header only for multiple files', () => {
- // Single file - no header
- const { rerender } = render(
- <PreviewDocumentPicker
- value={createMockDocumentItem()}
- files={[createMockDocumentItem({ name: 'Single File' })]}
- onChange={vi.fn()}
- />,
- )
- expect(screen.queryByText(/files/)).not.toBeInTheDocument()
-
- // Multiple files - show header
- rerender(
- <PreviewDocumentPicker
- value={createMockDocumentItem()}
- files={createMockDocumentList(3)}
- onChange={vi.fn()}
- />,
- )
- openPopover()
- expect(screen.getByText(/dataset\.preprocessDocument/)).toBeInTheDocument()
- })
- })
-
- // Tests for visual states
- describe('Visual States', () => {
- it('should have max-width on name element', () => {
- renderComponent({
- value: createMockDocumentItem({ name: 'Test' }),
- })
-
- const nameElement = screen.getByText('Test')
- expect(nameElement).toHaveClass('max-w-50')
- })
- })
-
- // Tests for handleChange callback
- describe('handleChange Callback', () => {
- it('should call onChange with selected document item', () => {
- const onChange = vi.fn()
- const files = createMockDocumentList(3)
-
- renderComponent({ files, onChange })
- openPopover()
-
- fireEvent.click(screen.getByText('Document 1'))
-
- expect(onChange).toHaveBeenCalledWith(files[0])
- })
-
- it('should handle different document items in files', () => {
- const onChange = vi.fn()
- const customFiles = [
- { id: 'custom-1', name: 'Custom File 1', extension: 'pdf' },
- { id: 'custom-2', name: 'Custom File 2', extension: 'txt' },
- ]
-
- renderComponent({ files: customFiles, onChange })
- openPopover()
-
- fireEvent.click(screen.getByText('Custom File 1'))
- expect(onChange).toHaveBeenCalledWith(customFiles[0])
-
- openPopover()
- fireEvent.click(screen.getByText('Custom File 2'))
- expect(onChange).toHaveBeenCalledWith(customFiles[1])
- })
-
- it('should work with multiple sequential selections', () => {
- const onChange = vi.fn()
- const files = createMockDocumentList(3)
-
- renderComponent({ files, onChange })
+ it('shows loading content when the file list is empty', async () => {
+ render(<PreviewDocumentPicker value={documents[0]} files={[]} onChange={vi.fn()} />)
- // Select multiple documents sequentially
- openPopover()
- fireEvent.click(screen.getByText('Document 1'))
- openPopover()
- fireEvent.click(screen.getByText('Document 3'))
- openPopover()
- fireEvent.click(screen.getByText('Document 2'))
+ fireEvent.click(screen.getByRole('button', { name: /First document/ }))
- expect(onChange).toHaveBeenCalledTimes(3)
- expect(onChange).toHaveBeenNthCalledWith(1, files[0])
- expect(onChange).toHaveBeenNthCalledWith(2, files[2])
- expect(onChange).toHaveBeenNthCalledWith(3, files[1])
- })
+ expect(await screen.findByRole('dialog')).toBeInTheDocument()
})
})
diff --git a/web/app/components/datasets/common/retrieval-param-config/__tests__/index.spec.tsx b/web/app/components/datasets/common/retrieval-param-config/__tests__/index.spec.tsx
index 023472d6280..f29f5db525a 100644
--- a/web/app/components/datasets/common/retrieval-param-config/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/common/retrieval-param-config/__tests__/index.spec.tsx
@@ -115,24 +115,6 @@ vi.mock('@/app/components/base/param-item/score-threshold-item', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/switch', () => ({
- Switch: ({
- checked,
- onCheckedChange,
- }: {
- checked: boolean
- onCheckedChange?: (v: boolean) => void
- }) => (
- <button
- data-testid="rerank-switch"
- data-checked={checked}
- onClick={() => onCheckedChange?.(!checked)}
- >
- Switch
- </button>
- ),
-}))
-
describe('RetrievalParamConfig', () => {
const createDefaultConfig = (overrides?: Partial<RetrievalConfig>): RetrievalConfig => ({
search_method: RETRIEVE_METHOD.semantic,
@@ -166,7 +148,7 @@ describe('RetrievalParamConfig', () => {
/>,
)
- expect(screen.getByTestId('rerank-switch'))!.toBeInTheDocument()
+ expect(screen.getByRole('switch')).toBeChecked()
})
it('should render model selector when reranking is enabled', () => {
@@ -232,7 +214,7 @@ describe('RetrievalParamConfig', () => {
/>,
)
- fireEvent.click(screen.getByTestId('rerank-switch'))
+ fireEvent.click(screen.getByRole('switch'))
expect(mockOnChange).toHaveBeenCalledWith({
...config,
@@ -251,7 +233,7 @@ describe('RetrievalParamConfig', () => {
/>,
)
- fireEvent.click(screen.getByTestId('rerank-switch'))
+ fireEvent.click(screen.getByRole('switch'))
expect(mockNotify).toHaveBeenCalledWith('workflow.errorMsg.rerankModelRequired')
})
@@ -375,7 +357,7 @@ describe('RetrievalParamConfig', () => {
/>,
)
- expect(screen.getByTestId('rerank-switch'))!.toBeInTheDocument()
+ expect(screen.getByRole('switch')).toBeChecked()
})
it('should hide score threshold when reranking is disabled for full text search', () => {
@@ -422,7 +404,7 @@ describe('RetrievalParamConfig', () => {
/>,
)
- expect(screen.queryByTestId('rerank-switch')).not.toBeInTheDocument()
+ expect(screen.queryByRole('switch')).not.toBeInTheDocument()
})
it('should not render model selector for keyword search', () => {
@@ -762,7 +744,7 @@ describe('RetrievalParamConfig', () => {
/>,
)
- expect(screen.queryByTestId('rerank-switch')).not.toBeInTheDocument()
+ expect(screen.queryByRole('switch')).not.toBeInTheDocument()
})
it('should update model selection for hybrid search', () => {
diff --git a/web/app/components/datasets/create/step-two/language-select/__tests__/index.spec.tsx b/web/app/components/datasets/create/step-two/language-select/__tests__/index.spec.tsx
index 5f2407986b6..64553d139df 100644
--- a/web/app/components/datasets/create/step-two/language-select/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/create/step-two/language-select/__tests__/index.spec.tsx
@@ -110,30 +110,6 @@ describe('LanguageSelect', () => {
it('should ignore null values emitted by the select control', async () => {
vi.resetModules()
- vi.doMock('@langgenius/dify-ui/select', () => ({
- Select: ({
- onValueChange,
- children,
- }: {
- onValueChange?: (value: string | null) => void
- children: React.ReactNode
- }) => {
- React.useEffect(() => {
- onValueChange?.(null)
- }, [onValueChange])
- return <div>{children}</div>
- },
- SelectTrigger: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button type="button" {...props}>
- {children}
- </button>
- ),
- SelectValue: ({ placeholder }: { placeholder?: React.ReactNode }) => <>{placeholder}</>,
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItemText: ({ children }: { children: React.ReactNode }) => <span>{children}</span>,
- SelectItemIndicator: () => null,
- }))
const { default: IsolatedLanguageSelect } = await import('../index')
const onSelect = vi.fn()
diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx
index 48bb5cdd385..7f91576f1a6 100644
--- a/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx
@@ -1,830 +1,106 @@
-import type { CredentialSelectorProps } from '../index'
import type { DataSourceCredential } from '@/types/pipeline'
-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
-import * as React from 'react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import CredentialSelector from '../index'
-// Mock CredentialTypeEnum to avoid deep import chain issues
-const MockCredentialTypeEnum = {
- OAUTH2: 'oauth2',
- API_KEY: 'api_key',
-} as const
-
-// Mock plugin-auth module to avoid deep import chain issues
vi.mock('@/app/components/plugins/plugin-auth', () => ({
- CredentialTypeEnum: {
- OAUTH2: 'oauth2',
- API_KEY: 'api_key',
- },
+ CredentialTypeEnum: { OAUTH2: 'oauth2', API_KEY: 'api_key' },
}))
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
-// CredentialIcon - imported directly (not mocked)
-// This is a simple UI component with no external dependencies
-
-const createMockCredential = (overrides?: Partial<DataSourceCredential>): DataSourceCredential => ({
- id: 'cred-1',
- name: 'Test Credential',
- avatar_url: 'https://example.com/avatar.png',
- credential: { key: 'value' },
- is_default: false,
- type: MockCredentialTypeEnum.OAUTH2 as unknown as DataSourceCredential['type'],
- ...overrides,
-})
-
-const createMockCredentials = (count: number = 3): DataSourceCredential[] =>
- Array.from({ length: count }, (_, i) =>
- createMockCredential({
- id: `cred-${i + 1}`,
- name: `Credential ${i + 1}`,
- avatar_url: `https://example.com/avatar-${i + 1}.png`,
- is_default: i === 0,
- }),
- )
-
-const createDefaultProps = (
- overrides?: Partial<CredentialSelectorProps>,
-): CredentialSelectorProps => ({
- currentCredentialId: 'cred-1',
- onCredentialChange: vi.fn(),
- credentials: createMockCredentials(),
- ...overrides,
-})
+const credentials = [
+ {
+ id: 'credential-1',
+ name: 'First credential',
+ avatar_url: 'https://example.com/first.png',
+ type: 'oauth2',
+ },
+ {
+ id: 'credential-2',
+ name: 'Second credential',
+ avatar_url: 'https://example.com/second.png',
+ type: 'oauth2',
+ },
+] as DataSourceCredential[]
describe('CredentialSelector', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- // Rendering Tests - Verify component renders correctly
- describe('Rendering', () => {
- it('should render current credential name in trigger', () => {
- const props = createDefaultProps()
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('Credential 1'))!.toBeInTheDocument()
- })
-
- it('should render credential icon with correct props', () => {
- const props = createDefaultProps()
-
- const { container } = render(<CredentialSelector {...props} />)
-
- // Assert - CredentialIcon renders an img when avatarUrl is provided
- const iconImg = container.querySelector('img')
- expect(iconImg)!.toBeInTheDocument()
- expect(iconImg)!.toHaveAttribute('src', 'https://example.com/avatar-1.png')
- })
-
- it('should render dropdown arrow icon', () => {
- const props = createDefaultProps()
-
- const { container } = render(<CredentialSelector {...props} />)
-
- const svgIcon = container.querySelector('svg')
- expect(svgIcon)!.toBeInTheDocument()
- })
-
- it('should not render dropdown content initially', () => {
- const props = createDefaultProps()
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
- })
-
- it('should render all credentials in dropdown when opened', () => {
- const props = createDefaultProps()
- render(<CredentialSelector {...props} />)
-
- // Act - Click trigger to open dropdown
- const trigger = screen.getByTestId('popover-trigger')
- expect(trigger).not.toHaveAttribute('data-popup-open')
- fireEvent.click(trigger)
-
- expect(trigger).toHaveAttribute('data-popup-open', '')
- expect(trigger.firstElementChild).toHaveClass('bg-state-base-hover')
- // Assert - All credentials should be visible (current credential appears in both trigger and list)
- // Assert - All credentials should be visible (current credential appears in both trigger and list)
- expect(screen.getByTestId('popover-content'))!.toBeInTheDocument()
- // 3 in dropdown list + 1 in trigger (current) = 4 total
- expect(screen.getAllByText(/Credential \d/)).toHaveLength(4)
- })
- })
-
- // Props Testing - Verify all prop variations
- describe('Props', () => {
- describe('currentCredentialId prop', () => {
- it('should display first credential when currentCredentialId matches first', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-1' })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('Credential 1'))!.toBeInTheDocument()
- })
-
- it('should display second credential when currentCredentialId matches second', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-2' })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('Credential 2'))!.toBeInTheDocument()
- })
-
- it('should display third credential when currentCredentialId matches third', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-3' })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('Credential 3'))!.toBeInTheDocument()
- })
-
- it.each([
- ['cred-1', 'Credential 1'],
- ['cred-2', 'Credential 2'],
- ['cred-3', 'Credential 3'],
- ])(
- 'should display %s credential name when currentCredentialId is %s',
- (credId, expectedName) => {
- const props = createDefaultProps({ currentCredentialId: credId })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText(expectedName))!.toBeInTheDocument()
- },
- )
- })
-
- describe('credentials prop', () => {
- it('should render single credential correctly', () => {
- const props = createDefaultProps({
- credentials: [createMockCredential()],
- currentCredentialId: 'cred-1',
- })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('Test Credential'))!.toBeInTheDocument()
- })
-
- it('should render multiple credentials in dropdown', () => {
- const props = createDefaultProps({
- credentials: createMockCredentials(5),
- currentCredentialId: 'cred-1',
- })
- render(<CredentialSelector {...props} />)
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- // Assert - 5 in dropdown + 1 in trigger (current credential appears twice)
- expect(screen.getAllByText(/Credential \d/).length).toBe(6)
- })
-
- it('should handle credentials with special characters in name', () => {
- const props = createDefaultProps({
- credentials: [
- createMockCredential({ id: 'cred-special', name: 'Test & Credential <special>' }),
- ],
- currentCredentialId: 'cred-special',
- })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('Test & Credential <special>'))!.toBeInTheDocument()
- })
- })
-
- describe('onCredentialChange prop', () => {
- it('should be called when selecting a credential', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
- render(<CredentialSelector {...props} />)
-
- // Act - Open dropdown
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- const credential2 = screen.getByText('Credential 2')
- fireEvent.click(credential2)
-
- expect(mockOnChange).toHaveBeenCalledWith('cred-2')
- })
-
- it.each([
- ['cred-2', 'Credential 2'],
- ['cred-3', 'Credential 3'],
- ])('should call onCredentialChange with %s when selecting %s', (credId, credentialName) => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
- render(<CredentialSelector {...props} />)
-
- // Act - Open dropdown and select credential
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- // Get the dropdown item using within() to scope query to portal content
- const portalContent = screen.getByTestId('popover-content')
- const credentialOption = within(portalContent).getByText(credentialName)
- fireEvent.click(credentialOption)
-
- expect(mockOnChange).toHaveBeenCalledWith(credId)
- })
-
- it('should call onCredentialChange with cred-1 when selecting Credential 1 in dropdown', () => {
- // Arrange - Start with cred-2 selected so cred-1 is only in dropdown
- const mockOnChange = vi.fn()
- const props = createDefaultProps({
- onCredentialChange: mockOnChange,
- currentCredentialId: 'cred-2',
- })
- render(<CredentialSelector {...props} />)
-
- // Act - Open dropdown and select Credential 1
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- const credential1 = screen.getByText('Credential 1')
- fireEvent.click(credential1)
-
- expect(mockOnChange).toHaveBeenCalledWith('cred-1')
- })
- })
- })
-
- // User Interactions - Test event handlers
- describe('User Interactions', () => {
- it('should toggle dropdown open when trigger is clicked', () => {
- const props = createDefaultProps()
- render(<CredentialSelector {...props} />)
-
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- // Assert - Initially closed
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
-
- // Act - Click trigger
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- // Assert - Now open
- // Assert - Now open
- expect(screen.getByTestId('popover-content'))!.toBeInTheDocument()
- })
-
- it('should call onCredentialChange when clicking a credential item', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
- render(<CredentialSelector {...props} />)
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
- const credential2 = screen.getByText('Credential 2')
- fireEvent.click(credential2)
-
- expect(mockOnChange).toHaveBeenCalledTimes(1)
- expect(mockOnChange).toHaveBeenCalledWith('cred-2')
- })
-
- it('should close dropdown after selecting a credential', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
- render(<CredentialSelector {...props} />)
-
- // Act - Open and select
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- expect(screen.getByTestId('popover-content'))!.toBeInTheDocument()
-
- const credential2 = screen.getByText('Credential 2')
- fireEvent.click(credential2)
-
- // Assert - The handleCredentialChange calls toggle(), which should change the open state
- expect(mockOnChange).toHaveBeenCalled()
- })
-
- it('should allow selecting credentials multiple times', () => {
- // Arrange - Start with cred-2 selected so we can select other credentials
- const mockOnChange = vi.fn()
- const props = createDefaultProps({
- onCredentialChange: mockOnChange,
- currentCredentialId: 'cred-2',
- })
-
- render(<CredentialSelector {...props} />)
-
- // Act & Assert - Select Credential 1 (different from current)
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- const credential1 = screen.getByText('Credential 1')
- fireEvent.click(credential1)
-
- expect(mockOnChange).toHaveBeenCalledWith('cred-1')
- })
- })
-
- // Side Effects and Cleanup - Test useEffect behavior
- describe('Side Effects and Cleanup', () => {
- it('should auto-select first credential when currentCredential is not found and credentials exist', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({
- currentCredentialId: 'non-existent-id',
- onCredentialChange: mockOnChange,
- })
-
- render(<CredentialSelector {...props} />)
-
- // Assert - Should auto-select first credential
- expect(mockOnChange).toHaveBeenCalledWith('cred-1')
- })
-
- it('should not call onCredentialChange when currentCredential is found', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({
- currentCredentialId: 'cred-2',
- onCredentialChange: mockOnChange,
- })
-
- render(<CredentialSelector {...props} />)
-
- // Assert - Should not auto-select
- expect(mockOnChange).not.toHaveBeenCalled()
- })
-
- it('should not call onCredentialChange when credentials array is empty', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({
- currentCredentialId: 'cred-1',
- credentials: [],
- onCredentialChange: mockOnChange,
- })
-
- render(<CredentialSelector {...props} />)
-
- // Assert - Should not call since no credentials to select
- expect(mockOnChange).not.toHaveBeenCalled()
- })
-
- it('should auto-select when credentials change and currentCredential becomes invalid', async () => {
- const mockOnChange = vi.fn()
- const initialCredentials = createMockCredentials(3)
- const props = createDefaultProps({
- currentCredentialId: 'cred-1',
- credentials: initialCredentials,
- onCredentialChange: mockOnChange,
- })
-
- const { rerender } = render(<CredentialSelector {...props} />)
- expect(mockOnChange).not.toHaveBeenCalled()
-
- // Act - Change credentials to not include current
- const newCredentials = [
- createMockCredential({ id: 'cred-4', name: 'New Credential 4' }),
- createMockCredential({ id: 'cred-5', name: 'New Credential 5' }),
- ]
- rerender(<CredentialSelector {...props} credentials={newCredentials} />)
-
- // Assert - Should auto-select first of new credentials
- await waitFor(() => {
- expect(mockOnChange).toHaveBeenCalledWith('cred-4')
- })
- })
-
- it('should not trigger auto-select effect on every render with same props', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
-
- // Act - Render and rerender with same props
- const { rerender } = render(<CredentialSelector {...props} />)
- rerender(<CredentialSelector {...props} />)
- rerender(<CredentialSelector {...props} />)
-
- // Assert - onCredentialChange should not be called for auto-selection
- expect(mockOnChange).not.toHaveBeenCalled()
- })
+ it('renders the current credential as an accessible trigger', () => {
+ render(
+ <CredentialSelector
+ currentCredentialId="credential-1"
+ credentials={credentials}
+ onCredentialChange={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: /First credential/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ )
+ expect(screen.getByRole('img')).toHaveAttribute('src', 'https://example.com/first.png')
})
- // Callback Stability and Memoization - Test useCallback behavior
- describe('Callback Stability and Memoization', () => {
- it('should have stable handleCredentialChange callback', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
- render(<CredentialSelector {...props} />)
-
- // Act - Open dropdown and select
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
- const credential = screen.getByText('Credential 2')
- fireEvent.click(credential)
-
- // Assert - Callback should work correctly
- expect(mockOnChange).toHaveBeenCalledWith('cred-2')
- })
-
- it('should update handleCredentialChange when onCredentialChange changes', () => {
- const mockOnChange1 = vi.fn()
- const mockOnChange2 = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange1 })
-
- const { rerender } = render(<CredentialSelector {...props} />)
-
- // Act - Update onCredentialChange prop
- rerender(<CredentialSelector {...props} onCredentialChange={mockOnChange2} />)
-
- // Open and select
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
- const credential = screen.getByText('Credential 2')
- fireEvent.click(credential)
-
- // Assert - New callback should be used
- expect(mockOnChange1).not.toHaveBeenCalled()
- expect(mockOnChange2).toHaveBeenCalledWith('cred-2')
- })
+ it('selects the first credential when the current id is invalid', async () => {
+ const onCredentialChange = vi.fn()
+ render(
+ <CredentialSelector
+ currentCredentialId="missing"
+ credentials={credentials}
+ onCredentialChange={onCredentialChange}
+ />,
+ )
+
+ await waitFor(() => expect(onCredentialChange).toHaveBeenCalledWith('credential-1'))
})
- // Memoization Logic and Dependencies - Test useMemo behavior
- describe('Memoization Logic and Dependencies', () => {
- it('should find currentCredential by id', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-2' })
-
- render(<CredentialSelector {...props} />)
-
- // Assert - Should display credential 2
- // Assert - Should display credential 2
- expect(screen.getByText('Credential 2'))!.toBeInTheDocument()
- })
-
- it('should update currentCredential when currentCredentialId changes', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-1' })
- const { rerender } = render(<CredentialSelector {...props} />)
-
- // Assert initial
- // Assert initial
- expect(screen.getByText('Credential 1'))!.toBeInTheDocument()
-
- // Act - Change currentCredentialId
- rerender(<CredentialSelector {...props} currentCredentialId="cred-3" />)
-
- // Assert - Should now display credential 3
- // Assert - Should now display credential 3
- expect(screen.getByText('Credential 3'))!.toBeInTheDocument()
- })
-
- it('should update currentCredential when credentials array changes', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-1' })
- const { rerender } = render(<CredentialSelector {...props} />)
-
- // Assert initial
- // Assert initial
- expect(screen.getByText('Credential 1'))!.toBeInTheDocument()
-
- // Act - Change credentials
- const newCredentials = [createMockCredential({ id: 'cred-1', name: 'Updated Credential 1' })]
- rerender(<CredentialSelector {...props} credentials={newCredentials} />)
-
- // Assert - Should display updated name
- // Assert - Should display updated name
- expect(screen.getByText('Updated Credential 1'))!.toBeInTheDocument()
- })
-
- it('should return undefined currentCredential when id not found', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({
- currentCredentialId: 'non-existent',
- onCredentialChange: mockOnChange,
- })
-
- render(<CredentialSelector {...props} />)
-
- // Assert - Should trigger auto-select effect
- expect(mockOnChange).toHaveBeenCalledWith('cred-1')
- })
+ it('does not select a fallback for an empty credential list', () => {
+ const onCredentialChange = vi.fn()
+ render(
+ <CredentialSelector
+ currentCredentialId="missing"
+ credentials={[]}
+ onCredentialChange={onCredentialChange}
+ />,
+ )
+
+ expect(onCredentialChange).not.toHaveBeenCalled()
})
- // Component Memoization - Test React.memo behavior
- describe('Component Memoization', () => {
- it('should not re-render when props remain the same', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
- const renderSpy = vi.fn()
-
- const TrackedCredentialSelector: React.FC<CredentialSelectorProps> = (trackedProps) => {
- renderSpy()
- return <CredentialSelector {...trackedProps} />
- }
- const MemoizedTracked = React.memo(TrackedCredentialSelector)
-
- const { rerender } = render(<MemoizedTracked {...props} />)
- rerender(<MemoizedTracked {...props} />)
-
- // Assert - Should only render once due to same props
- expect(renderSpy).toHaveBeenCalledTimes(1)
- })
-
- it('should re-render when currentCredentialId changes', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-1' })
- const { rerender } = render(<CredentialSelector {...props} />)
-
- // Assert initial
- // Assert initial
- expect(screen.getByText('Credential 1'))!.toBeInTheDocument()
-
- rerender(<CredentialSelector {...props} currentCredentialId="cred-2" />)
-
- expect(screen.getByText('Credential 2'))!.toBeInTheDocument()
- })
-
- it('should re-render when credentials array reference changes', () => {
- const props = createDefaultProps()
- const { rerender } = render(<CredentialSelector {...props} />)
-
- // Act - Create new credentials array with different data
- const newCredentials = [createMockCredential({ id: 'cred-1', name: 'New Name 1' })]
- rerender(<CredentialSelector {...props} credentials={newCredentials} />)
-
- expect(screen.getByText('New Name 1'))!.toBeInTheDocument()
- })
-
- it('should re-render when onCredentialChange reference changes', () => {
- const mockOnChange1 = vi.fn()
- const mockOnChange2 = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange1 })
- const { rerender } = render(<CredentialSelector {...props} />)
-
- // Act - Change callback reference
- rerender(<CredentialSelector {...props} onCredentialChange={mockOnChange2} />)
-
- // Open and select
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
- const credential = screen.getByText('Credential 2')
- fireEvent.click(credential)
-
- // Assert - New callback should be used
- expect(mockOnChange2).toHaveBeenCalledWith('cred-2')
- })
+ it('opens the real popover and selects a credential', async () => {
+ const onCredentialChange = vi.fn()
+ render(
+ <CredentialSelector
+ currentCredentialId="credential-1"
+ credentials={credentials}
+ onCredentialChange={onCredentialChange}
+ />,
+ )
+ const trigger = screen.getByRole('button', { name: /First credential/ })
+
+ fireEvent.click(trigger)
+ expect(trigger).toHaveAttribute('aria-expanded', 'true')
+ fireEvent.click(await screen.findByText('Second credential'))
+
+ expect(onCredentialChange).toHaveBeenCalledWith('credential-2')
+ expect(trigger).toHaveAttribute('aria-expanded', 'false')
})
- describe('Edge Cases and Error Handling', () => {
- it('should handle undefined avatar_url in credential', () => {
- const credentialWithoutAvatar = createMockCredential({
- id: 'cred-no-avatar',
- name: 'No Avatar Credential',
- avatar_url: undefined,
- })
- const props = createDefaultProps({
- credentials: [credentialWithoutAvatar],
- currentCredentialId: 'cred-no-avatar',
- })
-
- const { container } = render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('No Avatar Credential'))!.toBeInTheDocument()
- const iconImg = container.querySelector('img')
- expect(iconImg).not.toBeInTheDocument()
- expect(screen.getByText('N'))!.toBeInTheDocument()
- })
-
- it('should handle very long credential name', () => {
- const longName = 'A'.repeat(200)
- const credentialWithLongName = createMockCredential({
- id: 'cred-long-name',
- name: longName,
- })
- const props = createDefaultProps({
- credentials: [credentialWithLongName],
- currentCredentialId: 'cred-long-name',
- })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText(longName))!.toBeInTheDocument()
- })
-
- it('should handle special characters in credential name', () => {
- const specialName = '测试 Credential <script>alert("xss")</script> & "quoted"'
- const credentialWithSpecialName = createMockCredential({
- id: 'cred-special',
- name: specialName,
- })
- const props = createDefaultProps({
- credentials: [credentialWithSpecialName],
- currentCredentialId: 'cred-special',
- })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText(specialName))!.toBeInTheDocument()
- })
-
- it('should handle numeric id as string', () => {
- const credentialWithNumericId = createMockCredential({
- id: '123456',
- name: 'Numeric ID Credential',
- })
- const props = createDefaultProps({
- credentials: [credentialWithNumericId],
- currentCredentialId: '123456',
- })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('Numeric ID Credential'))!.toBeInTheDocument()
- })
-
- it('should handle large number of credentials', () => {
- const manyCredentials = createMockCredentials(100)
- const props = createDefaultProps({
- credentials: manyCredentials,
- currentCredentialId: 'cred-50',
- })
-
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByText('Credential 50'))!.toBeInTheDocument()
- })
-
- it('should handle credential selection with duplicate names', () => {
- const mockOnChange = vi.fn()
- const duplicateCredentials = [
- createMockCredential({ id: 'cred-1', name: 'Same Name' }),
- createMockCredential({ id: 'cred-2', name: 'Same Name' }),
- ]
- const props = createDefaultProps({
- credentials: duplicateCredentials,
- currentCredentialId: 'cred-1',
- onCredentialChange: mockOnChange,
- })
-
- render(<CredentialSelector {...props} />)
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- // Get all "Same Name" elements
- // 1 in trigger (current) + 2 in dropdown (both credentials) = 3 total
- const sameNameElements = screen.getAllByText('Same Name')
- expect(sameNameElements.length).toBe(3)
-
- fireEvent.click(sameNameElements[2]!)
-
- // Assert - Should call with the correct id even with duplicate names
- expect(mockOnChange).toHaveBeenCalledWith('cred-2')
- })
-
- it('ignores credential clicks after unmount', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
- const { unmount } = render(<CredentialSelector {...props} />)
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- unmount()
-
- // Assert - Should not throw
- expect(() => {
- // Any cleanup should have happened
- }).not.toThrow()
- })
- })
-
- // Styling and CSS Classes
- describe('Styling', () => {
- it('should configure dropdown placement through popover props', () => {
- const props = createDefaultProps()
- render(<CredentialSelector {...props} />)
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- const content = screen.getByTestId('popover-content')
- expect(content)!.toHaveAttribute('data-placement', 'bottom-start')
- expect(content)!.toHaveAttribute('data-side-offset', '4')
- expect(content)!.not.toHaveClass('z-10')
- })
- })
-
- // Integration with Child Components
- describe('Integration with Child Components', () => {
- it('should pass currentCredential to Trigger component', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-2' })
-
- render(<CredentialSelector {...props} />)
-
- // Assert - Trigger should display the correct credential
- // Assert - Trigger should display the correct credential
- expect(screen.getByText('Credential 2'))!.toBeInTheDocument()
- })
-
- it('should pass isOpen state to Trigger component', () => {
- const props = createDefaultProps()
- render(<CredentialSelector {...props} />)
-
- // Assert - Initially closed
- const portalRoot = screen.getByTestId('popover')
- expect(portalRoot)!.toHaveAttribute('data-open', 'false')
-
- // Act - Open
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- // Assert - Now open
- // Assert - Now open
- expect(portalRoot)!.toHaveAttribute('data-open', 'true')
- })
-
- it('should pass credentials to List component', () => {
- const props = createDefaultProps()
- render(<CredentialSelector {...props} />)
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- // Assert - All credentials should be rendered in list
- // 3 in dropdown + 1 in trigger (current credential appears twice) = 4 total
- const credentialNames = screen.getAllByText(/Credential \d/)
- expect(credentialNames.length).toBe(4)
- })
-
- it('should pass currentCredentialId to List component', () => {
- const props = createDefaultProps({ currentCredentialId: 'cred-2' })
- render(<CredentialSelector {...props} />)
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
-
- // Assert - Current credential (Credential 2) appears twice:
- // once in trigger and once in dropdown list
- const credential2Elements = screen.getAllByText('Credential 2')
- expect(credential2Elements.length).toBe(2)
- })
-
- it('should pass handleCredentialChange to List component', () => {
- const mockOnChange = vi.fn()
- const props = createDefaultProps({ onCredentialChange: mockOnChange })
- render(<CredentialSelector {...props} />)
-
- const trigger = screen.getByTestId('popover-trigger')
- fireEvent.click(trigger)
- const credential3 = screen.getByText('Credential 3')
- fireEvent.click(credential3)
-
- // Assert - handleCredentialChange should propagate the call
- expect(mockOnChange).toHaveBeenCalledWith('cred-3')
- })
- })
-
- // Popover Configuration
- describe('Popover Configuration', () => {
- it('should configure Popover with placement bottom-start', () => {
- // This test verifies the portal is configured correctly
- // The actual placement is handled by the mock, but we verify the component renders
- const props = createDefaultProps()
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByTestId('popover'))!.toBeInTheDocument()
- })
-
- it('should configure Popover with offset mainAxis 4', () => {
- // This test verifies the offset configuration doesn't break rendering
- const props = createDefaultProps()
- render(<CredentialSelector {...props} />)
-
- expect(screen.getByTestId('popover'))!.toBeInTheDocument()
- })
+ it('reflects an updated controlled credential', () => {
+ const onCredentialChange = vi.fn()
+ const { rerender } = render(
+ <CredentialSelector
+ currentCredentialId="credential-1"
+ credentials={credentials}
+ onCredentialChange={onCredentialChange}
+ />,
+ )
+
+ rerender(
+ <CredentialSelector
+ currentCredentialId="credential-2"
+ credentials={credentials}
+ onCredentialChange={onCredentialChange}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: /Second credential/ })).toBeInTheDocument()
})
})
diff --git a/web/app/components/datasets/documents/create-from-pipeline/process-documents/__tests__/header.spec.tsx b/web/app/components/datasets/documents/create-from-pipeline/process-documents/__tests__/header.spec.tsx
index 62a7ca53263..1b567c760e6 100644
--- a/web/app/components/datasets/documents/create-from-pipeline/process-documents/__tests__/header.spec.tsx
+++ b/web/app/components/datasets/documents/create-from-pipeline/process-documents/__tests__/header.spec.tsx
@@ -2,24 +2,6 @@ import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import Header from '../header'
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- disabled,
- variant,
- }: {
- children: React.ReactNode
- onClick: () => void
- disabled?: boolean
- variant: string
- }) => (
- <button data-testid={`btn-${variant}`} onClick={onClick} disabled={disabled}>
- {children}
- </button>
- ),
-}))
-
describe('Header', () => {
const defaultProps = {
onReset: vi.fn(),
@@ -41,29 +23,35 @@ describe('Header', () => {
it('should render reset and preview buttons', () => {
render(<Header {...defaultProps} />)
- expect(screen.getByTestId('btn-ghost')).toBeInTheDocument()
- expect(screen.getByTestId('btn-secondary-accent')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common.operation.reset' })).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'datasetPipeline.addDocuments.stepTwo.previewChunks' }),
+ ).toBeInTheDocument()
})
it('should call onReset when reset clicked', () => {
render(<Header {...defaultProps} />)
- fireEvent.click(screen.getByTestId('btn-ghost'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.reset' }))
expect(defaultProps.onReset).toHaveBeenCalled()
})
it('should call onPreview when preview clicked', () => {
render(<Header {...defaultProps} />)
- fireEvent.click(screen.getByTestId('btn-secondary-accent'))
+ fireEvent.click(
+ screen.getByRole('button', { name: 'datasetPipeline.addDocuments.stepTwo.previewChunks' }),
+ )
expect(defaultProps.onPreview).toHaveBeenCalled()
})
it('should disable reset button when resetDisabled is true', () => {
render(<Header {...defaultProps} resetDisabled={true} />)
- expect(screen.getByTestId('btn-ghost')).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'common.operation.reset' })).toBeDisabled()
})
it('should disable preview button when previewDisabled is true', () => {
render(<Header {...defaultProps} previewDisabled={true} />)
- expect(screen.getByTestId('btn-secondary-accent')).toBeDisabled()
+ expect(
+ screen.getByRole('button', { name: 'datasetPipeline.addDocuments.stepTwo.previewChunks' }),
+ ).toBeDisabled()
})
})
diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/index.spec.tsx
index e05f829d75a..88ef64d8b25 100644
--- a/web/app/components/datasets/documents/detail/completed/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/documents/detail/completed/__tests__/index.spec.tsx
@@ -248,35 +248,6 @@ vi.mock('@/app/components/base/divider', () => ({
default: () => <hr data-testid="divider" />,
}))
-vi.mock('@langgenius/dify-ui/pagination', () => ({
- Pagination: ({
- page,
- totalPages,
- onPageChange,
- pageSize,
- }: {
- page: number
- totalPages: number
- onPageChange: (page: number) => void
- pageSize?: {
- onValueChange: (limit: number) => void
- }
- }) => (
- <div data-testid="pagination">
- <span data-testid="current-page">{page - 1}</span>
- <span data-testid="total-pages">{totalPages}</span>
- <button data-testid="next-page" onClick={() => onPageChange(page + 1)}>
- Next
- </button>
- {pageSize && (
- <button data-testid="change-limit" onClick={() => pageSize.onValueChange(20)}>
- Change Limit
- </button>
- )}
- </div>
- ),
-}))
-
const createMockSegmentDetail = (
overrides: Partial<SegmentDetailModel> = {},
): SegmentDetailModel => ({
@@ -500,7 +471,7 @@ describe('Completed Component', () => {
it('should render Pagination component', () => {
render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- expect(screen.getByTestId('pagination'))!.toBeInTheDocument()
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toBeInTheDocument()
})
it('should render Divider component', () => {
@@ -525,32 +496,35 @@ describe('Completed Component', () => {
})
describe('Pagination', () => {
- it('should start with page 0 (current - 1)', () => {
+ it('should start on the first page', () => {
render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- expect(screen.getByTestId('current-page'))!.toHaveTextContent('0')
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toHaveAttribute(
+ 'data-page',
+ '1',
+ )
})
it('should update page when pagination changes', async () => {
+ mockSegmentListData.total = 30
render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- const nextPageButton = screen.getByTestId('next-page')
+ const nextPageButton = screen.getByRole('button', { name: 'common.pagination.next' })
fireEvent.click(nextPageButton)
await waitFor(() => {
- expect(screen.getByTestId('current-page'))!.toHaveTextContent('1')
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toHaveAttribute(
+ 'data-page',
+ '2',
+ )
})
})
- it('should update limit when limit changes', async () => {
+ it('should expose page-size controls', () => {
render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- const changeLimitButton = screen.getByTestId('change-limit')
- fireEvent.click(changeLimitButton)
-
- // Limit change is handled internally
- // Limit change is handled internally
- expect(changeLimitButton)!.toBeInTheDocument()
+ expect(screen.getByRole('group', { name: 'common.pagination.perPage' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: '10' })).toHaveAttribute('aria-pressed', 'true')
})
})
@@ -651,7 +625,7 @@ describe('Edge Cases', () => {
const { unmount } = render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- expect(screen.getByTestId('pagination'))!.toBeInTheDocument()
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toBeInTheDocument()
unmount()
})
@@ -667,7 +641,7 @@ describe('Edge Cases', () => {
const { unmount } = render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- expect(screen.getByTestId('pagination'))!.toBeInTheDocument()
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toBeInTheDocument()
unmount()
})
@@ -696,7 +670,7 @@ describe('Integration Tests', () => {
// All components should render without errors
expect(screen.getByTestId('menu-bar'))!.toBeInTheDocument()
expect(screen.getByTestId('general-mode-content'))!.toBeInTheDocument()
- expect(screen.getByTestId('pagination'))!.toBeInTheDocument()
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toBeInTheDocument()
expect(screen.getByTestId('drawer-group'))!.toBeInTheDocument()
})
@@ -1103,17 +1077,24 @@ describe('Inline callback and hook initialization coverage', () => {
// Covers lines 56-58: useSearchFilter({ onPageChange: setCurrentPage })
it('should reset current page when status filter changes', async () => {
+ mockSegmentListData.total = 30
render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- fireEvent.click(screen.getByTestId('next-page'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.pagination.next' }))
await waitFor(() => {
- expect(screen.getByTestId('current-page'))!.toHaveTextContent('1')
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toHaveAttribute(
+ 'data-page',
+ '2',
+ )
})
fireEvent.click(screen.getByTestId('status-enabled'))
await waitFor(() => {
- expect(screen.getByTestId('current-page'))!.toHaveTextContent('0')
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toHaveAttribute(
+ 'data-page',
+ '1',
+ )
})
})
@@ -1228,16 +1209,23 @@ describe('Inline callback and hook initialization coverage', () => {
// Covers line 133-135: handlePageChange
it('should handle multiple page changes', async () => {
+ mockSegmentListData.total = 30
render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- fireEvent.click(screen.getByTestId('next-page'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.pagination.next' }))
await waitFor(() => {
- expect(screen.getByTestId('current-page'))!.toHaveTextContent('1')
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toHaveAttribute(
+ 'data-page',
+ '2',
+ )
})
- fireEvent.click(screen.getByTestId('next-page'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.pagination.next' }))
await waitFor(() => {
- expect(screen.getByTestId('current-page'))!.toHaveTextContent('2')
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toHaveAttribute(
+ 'data-page',
+ '3',
+ )
})
})
@@ -1248,7 +1236,10 @@ describe('Inline callback and hook initialization coverage', () => {
render(<Completed {...defaultProps} />, { wrapper: createWrapper() })
- expect(screen.getByTestId('total-pages'))!.toHaveTextContent('5')
+ expect(screen.getByRole('navigation', { name: 'Pagination' })).toHaveAttribute(
+ 'data-totalpages',
+ '5',
+ )
})
// Covers search input change
diff --git a/web/app/components/datasets/extra-info/service-api/__tests__/card.spec.tsx b/web/app/components/datasets/extra-info/service-api/__tests__/card.spec.tsx
index 9bcf0416495..a609c25c80c 100644
--- a/web/app/components/datasets/extra-info/service-api/__tests__/card.spec.tsx
+++ b/web/app/components/datasets/extra-info/service-api/__tests__/card.spec.tsx
@@ -1,25 +1,27 @@
+import { Popover } from '@langgenius/dify-ui/popover'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Card from '../card'
-vi.mock('@langgenius/dify-ui/popover', () => ({
- PopoverClose: ({ render }: { render: React.ReactNode }) => render,
-}))
-
vi.mock('@/hooks/use-api-access-url', () => ({
useDatasetApiAccessUrl: () => 'https://docs.dify.ai/api-reference/datasets',
}))
describe('Service API card', () => {
- it('shows the service endpoint and API reference', () => {
+ const renderCard = (props: React.ComponentProps<typeof Card>) =>
render(
- <Card
- apiBaseUrl="https://api.example.com"
- canManageSecretKey
- onOpenSecretKeyModal={vi.fn()}
- />,
+ <Popover>
+ <Card {...props} />
+ </Popover>,
)
+ it('shows the service endpoint and API reference', () => {
+ renderCard({
+ apiBaseUrl: 'https://api.example.com',
+ canManageSecretKey: true,
+ onOpenSecretKeyModal: vi.fn(),
+ })
+
expect(screen.getByText('https://api.example.com')).toBeInTheDocument()
expect(
screen.getByRole('link', { name: 'dataset.serviceApi.card.apiReference' }),
@@ -29,13 +31,11 @@ describe('Service API card', () => {
it('opens secret-key management when allowed', async () => {
const user = userEvent.setup()
const onOpenSecretKeyModal = vi.fn()
- render(
- <Card
- apiBaseUrl="https://api.example.com"
- canManageSecretKey
- onOpenSecretKeyModal={onOpenSecretKeyModal}
- />,
- )
+ renderCard({
+ apiBaseUrl: 'https://api.example.com',
+ canManageSecretKey: true,
+ onOpenSecretKeyModal,
+ })
await user.click(screen.getByRole('button', { name: 'dataset.serviceApi.card.apiKey' }))
@@ -43,7 +43,7 @@ describe('Service API card', () => {
})
it('disables secret-key management when it is not allowed', () => {
- render(<Card apiBaseUrl="https://api.example.com" onOpenSecretKeyModal={vi.fn()} />)
+ renderCard({ apiBaseUrl: 'https://api.example.com', onOpenSecretKeyModal: vi.fn() })
expect(screen.getByRole('button', { name: 'dataset.serviceApi.card.apiKey' })).toBeDisabled()
})
diff --git a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx
index e8871e3c330..38765e44fb2 100644
--- a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx
@@ -9,29 +9,6 @@ import { render } from '@/test/console/render'
import { RETRIEVE_METHOD } from '@/types/app'
import HitTestingPage from '../index'
-vi.mock('@langgenius/dify-ui/pagination', () => ({
- Pagination: ({
- page,
- totalPages,
- onPageChange,
- labels,
- }: {
- page: number
- totalPages: number
- onPageChange: (page: number) => void
- labels: { next: string }
- }) => (
- <button
- type="button"
- aria-label={labels.next}
- disabled={page >= totalPages}
- onClick={() => onPageChange(page + 1)}
- >
- {page}/{totalPages}
- </button>
- ),
-}))
-
vi.mock('@/app/components/datasets/common/retrieval-method-config', () => ({
default: ({
value,
diff --git a/web/app/components/datasets/hit-testing/__tests__/modify-external-retrieval-modal.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/modify-external-retrieval-modal.spec.tsx
index 8b7f380d804..6fb5bad0b87 100644
--- a/web/app/components/datasets/hit-testing/__tests__/modify-external-retrieval-modal.spec.tsx
+++ b/web/app/components/datasets/hit-testing/__tests__/modify-external-retrieval-modal.spec.tsx
@@ -10,22 +10,6 @@ vi.mock('@/app/components/base/action-button', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- variant,
- }: {
- children: React.ReactNode
- onClick: () => void
- variant?: string
- }) => (
- <button data-testid={variant === 'primary' ? 'save-button' : 'cancel-button'} onClick={onClick}>
- {children}
- </button>
- ),
-}))
-
vi.mock('../../external-knowledge-base/create/RetrievalSettings', () => ({
default: ({
topK,
@@ -89,13 +73,13 @@ describe('ModifyExternalRetrievalModal', () => {
it('should call onClose when cancel button clicked', () => {
render(<ModifyExternalRetrievalModal {...defaultProps} />)
- fireEvent.click(screen.getByTestId('cancel-button'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
expect(defaultProps.onClose).toHaveBeenCalled()
})
it('should call onSave with current values and close when save clicked', () => {
render(<ModifyExternalRetrievalModal {...defaultProps} />)
- fireEvent.click(screen.getByTestId('save-button'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(defaultProps.onSave).toHaveBeenCalledWith({
top_k: 4,
score_threshold: 0.5,
@@ -107,14 +91,14 @@ describe('ModifyExternalRetrievalModal', () => {
it('should save updated values after settings change', () => {
render(<ModifyExternalRetrievalModal {...defaultProps} />)
fireEvent.click(screen.getByTestId('change-top-k'))
- fireEvent.click(screen.getByTestId('save-button'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(defaultProps.onSave).toHaveBeenCalledWith(expect.objectContaining({ top_k: 10 }))
})
it('should save updated score threshold', () => {
render(<ModifyExternalRetrievalModal {...defaultProps} />)
fireEvent.click(screen.getByTestId('change-score'))
- fireEvent.click(screen.getByTestId('save-button'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(defaultProps.onSave).toHaveBeenCalledWith(
expect.objectContaining({ score_threshold: 0.9 }),
)
@@ -123,7 +107,7 @@ describe('ModifyExternalRetrievalModal', () => {
it('should save updated score threshold enabled', () => {
render(<ModifyExternalRetrievalModal {...defaultProps} />)
fireEvent.click(screen.getByTestId('change-enabled'))
- fireEvent.click(screen.getByTestId('save-button'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(defaultProps.onSave).toHaveBeenCalledWith(
expect.objectContaining({ score_threshold_enabled: true }),
)
@@ -133,7 +117,7 @@ describe('ModifyExternalRetrievalModal', () => {
render(<ModifyExternalRetrievalModal {...defaultProps} />)
fireEvent.click(screen.getByTestId('change-top-k'))
fireEvent.click(screen.getByTestId('change-score'))
- fireEvent.click(screen.getByTestId('save-button'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(defaultProps.onSave).toHaveBeenCalledWith(
expect.objectContaining({ top_k: 10, score_threshold: 0.9 }),
)
diff --git a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx
index 59ed9296bf2..11430c98a01 100644
--- a/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx
+++ b/web/app/components/datasets/hit-testing/__tests__/modify-retrieval-modal.spec.tsx
@@ -22,17 +22,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
toast: mockToast,
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- }: {
- children: React.ReactNode
- onClick: () => void
- variant?: string
- }) => <button onClick={onClick}>{children}</button>,
-}))
-
vi.mock('@/app/components/datasets/common/check-rerank-model', () => ({
isReRankModelSelected: vi.fn(() => true),
}))
diff --git a/web/app/components/datasets/list/__tests__/header.spec.tsx b/web/app/components/datasets/list/__tests__/header.spec.tsx
index 663221b76f0..f95ad7441d8 100644
--- a/web/app/components/datasets/list/__tests__/header.spec.tsx
+++ b/web/app/components/datasets/list/__tests__/header.spec.tsx
@@ -1,49 +1,8 @@
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
import DatasetListHeader from '../header'
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children, className, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button type="button" className={className} {...props}>
- {children}
- </button>
- ),
-}))
-
-vi.mock('@langgenius/dify-ui/dropdown-menu', () => ({
- DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DropdownMenuContent: ({
- children,
- popupProps,
- positionerProps,
- }: {
- children: React.ReactNode
- popupProps?: React.HTMLAttributes<HTMLDivElement>
- positionerProps?: React.HTMLAttributes<HTMLDivElement>
- }) => (
- <div {...positionerProps}>
- <div role="menu" {...popupProps}>
- {children}
- </div>
- </div>
- ),
- DropdownMenuItem: ({
- children,
- className,
- onClick,
- }: {
- children: React.ReactNode
- className?: string
- onClick?: () => void
- }) => (
- <button type="button" role="menuitem" className={className} onClick={onClick}>
- {children}
- </button>
- ),
- DropdownMenuSeparator: () => <hr />,
- DropdownMenuTrigger: ({ render }: { render: React.ReactNode }) => render,
-}))
-
vi.mock('@/features/tag-management/components/tag-filter', () => ({
TagFilter: () => <div />,
}))
@@ -79,21 +38,26 @@ describe('DatasetListHeader', () => {
vi.clearAllMocks()
})
- it('uses the updated create menu labels and pipeline icon', () => {
+ it('shows dataset and pipeline creation actions in the create menu', async () => {
+ const user = userEvent.setup()
render(<DatasetListHeader {...defaultProps} />)
+ await user.click(screen.getByRole('button', { name: /common\.operation\.create/ }))
+
expect(
screen.getByRole('menuitem', { name: /dataset\.firstEmpty\.createTitle/ }),
).toBeInTheDocument()
-
- const menuItem = screen.getByRole('menuitem', { name: /dataset\.firstEmpty\.pipelineTitle/ })
-
- expect(menuItem.querySelector('.i-custom-vender-pipeline-pipeline-line')).toBeInTheDocument()
+ expect(
+ screen.getByRole('menuitem', { name: /dataset\.firstEmpty\.pipelineTitle/ }),
+ ).toBeInTheDocument()
})
- it('hides dataset creation actions without create permission', () => {
+ it('only shows external dataset connection without create permission', async () => {
+ const user = userEvent.setup()
render(<DatasetListHeader {...defaultProps} canCreateDataset={false} />)
+ await user.click(screen.getByRole('button', { name: /common\.operation\.create/ }))
+
expect(
screen.queryByRole('menuitem', { name: /dataset\.firstEmpty\.createTitle/ }),
).not.toBeInTheDocument()
diff --git a/web/app/components/explore/item-operation/__tests__/index.spec.tsx b/web/app/components/explore/item-operation/__tests__/index.spec.tsx
index c031e465c68..e25e7db8afe 100644
--- a/web/app/components/explore/item-operation/__tests__/index.spec.tsx
+++ b/web/app/components/explore/item-operation/__tests__/index.spec.tsx
@@ -2,91 +2,6 @@ import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
import ItemOperation from '../index'
-vi.mock('@langgenius/dify-ui/dropdown-menu', () => {
- const DropdownMenuContext = React.createContext<{
- isOpen: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({ children, modal }: { children: React.ReactNode; modal?: boolean }) => {
- const [isOpen, setIsOpen] = React.useState(false)
-
- return (
- <DropdownMenuContext value={{ isOpen, setOpen: setIsOpen }}>
- <div data-modal={modal} data-open={isOpen} data-testid="dropdown-menu">
- {children}
- </div>
- </DropdownMenuContext>
- )
- },
- DropdownMenuTrigger: ({
- children,
- onClick,
- ...props
- }: React.ButtonHTMLAttributes<HTMLButtonElement>) => {
- const { isOpen, setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- onClick={(e) => {
- onClick?.(e)
- setOpen(!isOpen)
- }}
- {...props}
- >
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({
- children,
- popupProps,
- }: {
- children: React.ReactNode
- popupProps?: React.HTMLAttributes<HTMLDivElement>
- }) => {
- const { isOpen } = useDropdownMenuContext()
- if (!isOpen) return null
-
- return (
- <div data-testid="dropdown-content" {...popupProps}>
- {children}
- </div>
- )
- },
- DropdownMenuItem: ({
- children,
- onClick,
- className,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- className?: string
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- className={className}
- onClick={(e) => {
- onClick?.(e)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- }
-})
-
describe('ItemOperation', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -179,12 +94,6 @@ describe('ItemOperation', () => {
expect(screen.getByText('explore.sidebar.action.pin')).toBeInTheDocument()
})
- it('should render a non-modal menu', () => {
- renderComponent()
-
- expect(screen.getByTestId('dropdown-menu')).toHaveAttribute('data-modal', 'false')
- })
-
it('should stop propagation when clicking menu actions', async () => {
const onParentClick = vi.fn()
const togglePin = vi.fn()
diff --git a/web/app/components/header/account-setting/__tests__/menu-dialog.dialog.spec.tsx b/web/app/components/header/account-setting/__tests__/menu-dialog.dialog.spec.tsx
deleted file mode 100644
index cf0e66a7572..00000000000
--- a/web/app/components/header/account-setting/__tests__/menu-dialog.dialog.spec.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { ReactNode } from 'react'
-import { render } from '@testing-library/react'
-import MenuDialog from '../menu-dialog'
-
-type DialogProps = {
- children: ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
-}
-
-let latestOnOpenChange: DialogProps['onOpenChange']
-
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, onOpenChange }: DialogProps) => {
- latestOnOpenChange = onOpenChange
- return <div data-testid="dialog">{children}</div>
- },
- DialogContent: ({ children, className }: { children: ReactNode; className?: string }) => (
- <div className={className}>{children}</div>
- ),
-}))
-
-describe('MenuDialog dialog lifecycle', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- latestOnOpenChange = undefined
- })
-
- it('should only call onClose when the dialog requests closing', () => {
- const onClose = vi.fn()
- render(
- <MenuDialog show={true} onClose={onClose}>
- <div>Content</div>
- </MenuDialog>,
- )
-
- latestOnOpenChange?.(true)
- latestOnOpenChange?.(false)
-
- expect(onClose).toHaveBeenCalledTimes(1)
- })
-})
diff --git a/web/app/components/header/account-setting/__tests__/update-setting-dialog-form.spec.tsx b/web/app/components/header/account-setting/__tests__/update-setting-dialog-form.spec.tsx
index 9fd44622fe3..374f2f37973 100644
--- a/web/app/components/header/account-setting/__tests__/update-setting-dialog-form.spec.tsx
+++ b/web/app/components/header/account-setting/__tests__/update-setting-dialog-form.spec.tsx
@@ -48,10 +48,6 @@ vi.mock('react-i18next', async () => {
}
})
-vi.mock('@/app/components/base/date-and-time-picker/time-picker', () => ({
- default: () => <div data-testid="time-picker" />,
-}))
-
vi.mock(
'@/app/components/plugins/reference-setting-modal/auto-update-setting/plugins-picker',
() => ({
diff --git a/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx b/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx
index 78d91d333cf..9f5663708af 100644
--- a/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx
+++ b/web/app/components/header/account-setting/api-based-extension-page/__tests__/selector.spec.tsx
@@ -50,8 +50,6 @@ vi.mock('@tanstack/react-query', () => ({
})),
}))
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-
describe('ApiBasedExtensionSelector', () => {
const mockOnChange = vi.fn()
@@ -93,18 +91,12 @@ describe('ApiBasedExtensionSelector', () => {
it('should open dropdown when clicked', async () => {
// Act
render(<ApiBasedExtensionSelector value="" onChange={mockOnChange} />)
- const popoverTrigger = screen.getByTestId('popover-trigger')
const trigger = screen.getByText('common.apiBasedExtension.selector.placeholder')
- const arrow = trigger.parentElement?.querySelector('[aria-hidden="true"]')
- expect(popoverTrigger).not.toHaveAttribute('data-popup-open')
- expect(arrow).toHaveClass('opacity-60')
fireEvent.click(trigger)
// Assert
// Assert
- expect(popoverTrigger).toHaveAttribute('data-popup-open', '')
- expect(arrow).not.toHaveClass('opacity-60')
expect(
await screen.findByText('common.apiBasedExtension.selector.title'),
)!.toBeInTheDocument()
diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/configure.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/configure.spec.tsx
index 6cb39efdb97..6109ce80e1b 100644
--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/configure.spec.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/configure.spec.tsx
@@ -1,4 +1,3 @@
-import type { ButtonHTMLAttributes, ReactNode } from 'react'
import type { DataSourceAuth } from '../types'
import type { FormSchema } from '@/app/components/base/form/types'
import type {
@@ -11,16 +10,6 @@ import { FormTypeEnum } from '@/app/components/base/form/types'
import { AuthCategory } from '@/app/components/plugins/plugin-auth/types'
import Configure from '../configure'
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- ...props
- }: ButtonHTMLAttributes<HTMLButtonElement> & { children?: ReactNode }) => (
- <button {...props}>{children}</button>
- ),
-}))
-
/**
* Configure Component Tests
* Using Unit approach to ensure 100% coverage and stable tests.
diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/plugin-actions.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/plugin-actions.spec.tsx
index 452b1046cdf..1b1bbf6bcee 100644
--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/plugin-actions.spec.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/plugin-actions.spec.tsx
@@ -26,6 +26,10 @@ vi.mock('@/app/components/plugins/readme-panel/store', () => ({
}),
}))
+vi.mock('@/service/use-plugins', () => ({
+ useVersionListOfPlugin: () => ({ data: { data: { versions: [] } } }),
+}))
+
vi.mock('@/app/components/plugins/plugin-detail-panel/detail-header/hooks', () => ({
useDetailHeaderState: () => ({
modalStates: {
@@ -60,24 +64,6 @@ vi.mock('@/app/components/base/badge', () => ({
default: ({ text }: { text: ReactNode }) => <div data-testid="badge">{text}</div>,
}))
-vi.mock('@/app/components/plugins/update-plugin/plugin-version-picker', () => ({
- __esModule: true,
- default: ({ trigger }: { trigger: ReactNode }) => <div>{trigger}</div>,
-}))
-
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
-}))
-
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- TooltipTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,
- TooltipContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
vi.mock('@/hooks/use-theme', () => ({
default: () => ({ theme: 'light' }),
}))
diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx
index 1c11ae83740..14e94d69d18 100644
--- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import type { PluginDeclaration, PluginDetail } from '@/app/components/plugins/types'
import { act, fireEvent, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
@@ -90,6 +89,10 @@ const saveUpdateSettings = () => {
fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
}
+const openUpdateSettings = () => {
+ fireEvent.click(screen.getByRole('button', { name: /plugin\.autoUpdate\.autoUpdate/ }))
+}
+
const createPluginDeclaration = (
overrides: Partial<PluginDeclaration> = {},
): PluginDeclaration => ({
@@ -279,66 +282,11 @@ vi.mock('@/service/use-plugins', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- DialogTrigger: ({ render }: { render: ReactNode }) => render,
- DialogContent: ({ children }: { children: ReactNode }) => (
- <div data-testid="update-setting-dialog">{children}</div>
- ),
- DialogTitle: () => null,
- DialogCloseButton: () => <button type="button" aria-label="close" />,
-}))
-
vi.mock('nuqs', async (importOriginal) => {
const actual = await importOriginal<typeof import('nuqs')>()
return { ...actual, useQueryState: () => [null, mockSetSettingsDestination] }
})
-vi.mock('@/app/components/base/date-and-time-picker/time-picker', () => ({
- default: ({
- value,
- onChange,
- renderTrigger,
- }: {
- value?: string | { format: (format: string) => string }
- onChange: (value: { hour: () => number; minute: () => number }) => void
- renderTrigger: (
- props: Record<string, never>,
- state: { open: boolean },
- params: {
- inputElem: ReactNode
- onClick: () => void
- },
- ) => ReactNode
- }) => {
- const displayValue = typeof value === 'string' ? value : value?.format('HH:mm')
-
- return (
- <div data-testid="update-time-picker">
- {renderTrigger(
- {},
- { open: false },
- {
- inputElem: <span data-testid="update-time-value">{displayValue}</span>,
- onClick: vi.fn(),
- },
- )}
- <button
- type="button"
- onClick={() =>
- onChange({
- hour: () => 1,
- minute: () => 15,
- })
- }
- >
- set update time
- </button>
- </div>
- )
- },
-}))
-
vi.mock('@/service/client', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/client')>()
const originalWorkspaces = actual.consoleQuery.workspaces
@@ -485,13 +433,12 @@ describe('ModelProviderPage', () => {
renderModelProviderPage()
expect(screen.getAllByText('plugin.autoUpdate.strategy.latest.name')[0]).toBeInTheDocument()
- expect(screen.getAllByTestId('update-setting-dialog')[0]).toBeInTheDocument()
+ openUpdateSettings()
expect(
screen.getByRole('radiogroup', { name: 'plugin.autoUpdate.autoUpdate' }),
).toBeInTheDocument()
expect(screen.getByText('plugin.autoUpdate.scope')).toBeInTheDocument()
expect(screen.getByText('plugin.autoUpdate.updateTime')).toBeInTheDocument()
- expect(screen.getByTestId('update-time-picker')).toBeInTheDocument()
expect(screen.getByText('plugin.autoUpdate.changeTimezone')).toBeInTheDocument()
expect(
screen.getByRole('radio', { name: 'plugin.autoUpdate.strategy.fixOnly.name' }),
@@ -506,10 +453,10 @@ describe('ModelProviderPage', () => {
const updateSettingButton = screen.getByText('plugin.autoUpdate.autoUpdate').closest('button')
expect(updateSettingButton).not.toBeDisabled()
expect(screen.queryByText('plugin.autoUpdate.strategy.latest.name')).not.toBeInTheDocument()
+ openUpdateSettings()
expect(screen.getByRole('status')).toHaveTextContent('common.loading')
expect(screen.queryByRole('button', { name: 'common.operation.save' })).not.toBeInTheDocument()
expect(mockSaveAutoUpgrade).not.toHaveBeenCalled()
- expect(screen.getByTestId('update-setting-dialog')).toBeInTheDocument()
})
it('should render a failure state when backend auto-upgrade data fails', () => {
@@ -518,6 +465,7 @@ describe('ModelProviderPage', () => {
renderModelProviderPage()
+ openUpdateSettings()
expect(screen.getByText('common.api.actionFailed')).toBeInTheDocument()
expect(
screen.queryByRole('radiogroup', { name: 'plugin.autoUpdate.autoUpdate' }),
@@ -529,6 +477,7 @@ describe('ModelProviderPage', () => {
it('should update scope from the dialog while keeping the backend returned strategy', () => {
renderModelProviderPage()
+ openUpdateSettings()
fireEvent.click(screen.getByRole('radio', { name: 'plugin.autoUpdate.upgradeMode.partial' }))
saveUpdateSettings()
@@ -544,11 +493,13 @@ describe('ModelProviderPage', () => {
it('should update time from the popover while keeping the model provider default strategy as latest', () => {
renderModelProviderPage()
- expect(screen.getByTestId('update-time-value')).toHaveTextContent('00:00')
-
- fireEvent.click(screen.getByRole('button', { name: 'set update time' }))
+ openUpdateSettings()
+ fireEvent.click(screen.getByDisplayValue('12:00 AM'))
+ fireEvent.click(screen.getByRole('button', { name: '01' }))
+ fireEvent.click(screen.getByRole('button', { name: '15' }))
+ fireEvent.click(screen.getByRole('button', { name: 'time.operation.ok' }))
- expect(screen.getByTestId('update-time-value')).toHaveTextContent('01:15')
+ expect(screen.getByDisplayValue('01:15 AM')).toBeInTheDocument()
saveUpdateSettings()
diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx
index 141fa24cd53..4dbf2eac649 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/__tests__/add-custom-model.spec.tsx
@@ -1,5 +1,6 @@
import type { ModelProvider } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { fireEvent, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { ConfigurationMethodEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { render } from '@/test/console/render'
import AddCustomModel from '../add-custom-model'
@@ -51,17 +52,13 @@ vi.mock('@remixicon/react', () => ({
RiAddLine: () => <div data-testid="add-line-icon" />,
}))
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="tooltip-mock">{children}</div>
- ),
- TooltipTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,
- TooltipContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-
describe('AddCustomModel', () => {
+ const getAddModelTrigger = () =>
+ screen
+ .getAllByRole('button', { name: /modelProvider.addModel/i })
+ .find((element) => element.getAttribute('aria-haspopup') === 'dialog') ??
+ screen.getAllByRole('button', { name: /modelProvider.addModel/i })[0]!
+
const mockProvider = {
provider: 'openai',
allow_custom_token: true,
@@ -97,7 +94,8 @@ describe('AddCustomModel', () => {
expect(mockHandleOpenModalForAddNewCustomModel).toHaveBeenCalled()
})
- it('should show models list when models are available', () => {
+ it('should show models list when models are available', async () => {
+ const user = userEvent.setup()
mockCanAddedModels = [{ model: 'gpt-4', model_type: 'llm' }]
render(
<AddCustomModel
@@ -106,19 +104,14 @@ describe('AddCustomModel', () => {
/>,
)
- const trigger = screen.getByTestId('popover-trigger')
- expect(trigger).not.toHaveAttribute('data-popup-open')
-
- fireEvent.click(trigger)
+ await user.click(getAddModelTrigger())
- // The portal should be "open"
- expect(trigger).toHaveAttribute('data-popup-open', '')
- expect(screen.getByTestId('popover')).toHaveAttribute('data-open', 'true')
- expect(screen.getByText('gpt-4')).toBeInTheDocument()
+ expect(await screen.findByText('gpt-4')).toBeInTheDocument()
expect(screen.getByTestId('model-icon')).toBeInTheDocument()
})
- it('should call handleOpenModalForAddCustomModelToModelList when clicking a model', () => {
+ it('should call handleOpenModalForAddCustomModelToModelList when clicking a model', async () => {
+ const user = userEvent.setup()
const model = { model: 'gpt-4', model_type: 'llm' }
mockCanAddedModels = [model]
render(
@@ -128,13 +121,14 @@ describe('AddCustomModel', () => {
/>,
)
- fireEvent.click(screen.getByTestId('popover-trigger'))
- fireEvent.click(screen.getByText('gpt-4'))
+ await user.click(getAddModelTrigger())
+ await user.click(await screen.findByText('gpt-4'))
expect(mockHandleOpenModalForAddCustomModelToModelList).toHaveBeenCalledWith(undefined, model)
})
- it('should show existing model rows as disabled for create-only users', () => {
+ it('should show existing model rows as disabled for create-only users', async () => {
+ const user = userEvent.setup()
const model = { model: 'gpt-4', model_type: 'llm' }
mockWorkspacePermissionKeys.value = ['credential.create']
mockCanAddedModels = [model]
@@ -146,20 +140,20 @@ describe('AddCustomModel', () => {
/>,
)
- fireEvent.click(screen.getByTestId('popover-trigger'))
+ await user.click(getAddModelTrigger())
- const modelRow = screen.getByText('gpt-4').closest('[aria-disabled]')
+ const modelRow = (await screen.findByText('gpt-4')).closest('[aria-disabled]')
expect(modelRow).toHaveAttribute('aria-disabled', 'true')
- expect(modelRow).toHaveClass('cursor-not-allowed')
- fireEvent.click(screen.getByText('gpt-4'))
+ await user.click(modelRow!)
expect(mockHandleOpenModalForAddCustomModelToModelList).not.toHaveBeenCalled()
- fireEvent.click(screen.getByText(/modelProvider.auth.addNewModel/))
+ await user.click(screen.getByText(/modelProvider.auth.addNewModel/))
expect(mockHandleOpenModalForAddNewCustomModel).toHaveBeenCalled()
})
- it('should call handleOpenModalForAddNewCustomModel when clicking "Add New Model" in list', () => {
+ it('should call handleOpenModalForAddNewCustomModel when clicking "Add New Model" in list', async () => {
+ const user = userEvent.setup()
mockCanAddedModels = [{ model: 'gpt-4', model_type: 'llm' }]
render(
<AddCustomModel
@@ -168,13 +162,14 @@ describe('AddCustomModel', () => {
/>,
)
- fireEvent.click(screen.getByTestId('popover-trigger'))
- fireEvent.click(screen.getByText(/modelProvider.auth.addNewModel/))
+ await user.click(getAddModelTrigger())
+ await user.click(await screen.findByText(/modelProvider.auth.addNewModel/))
expect(mockHandleOpenModalForAddNewCustomModel).toHaveBeenCalled()
})
- it('should show tooltip when no models and custom tokens not allowed', () => {
+ it('should show tooltip when no models and custom tokens not allowed', async () => {
+ const user = userEvent.setup()
const restrictedProvider = { ...mockProvider, allow_custom_token: false }
mockCanAddedModels = []
render(
@@ -184,10 +179,11 @@ describe('AddCustomModel', () => {
/>,
)
- expect(screen.getByTestId('tooltip-mock')).toBeInTheDocument()
- expect(screen.getByText('plugin.auth.credentialUnavailable')).toBeInTheDocument()
+ const trigger = getAddModelTrigger()
+ await user.hover(trigger)
+ expect(await screen.findByText('plugin.auth.credentialUnavailable')).toBeInTheDocument()
- fireEvent.click(screen.getByRole('button', { name: /modelProvider.addModel/i }))
+ await user.click(trigger)
expect(mockHandleOpenModalForAddNewCustomModel).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx
index 1fd6c530d0a..b9af1564cd7 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/index.spec.tsx
@@ -72,8 +72,6 @@ vi.mock('../authorized-item', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-
describe('Authorized', () => {
const mockProvider: ModelProvider = {
provider: 'openai',
@@ -102,6 +100,8 @@ describe('Authorized', () => {
</button>
)
+ const getTrigger = () => screen.getAllByRole('button', { name: /trigger\s*(open|closed)/i })[0]!
+
beforeEach(() => {
vi.clearAllMocks()
mockDeleteCredentialId = null
@@ -119,13 +119,13 @@ describe('Authorized', () => {
/>,
)
- const trigger = screen.getByTestId('popover-trigger')
+ const trigger = getTrigger()
expect(trigger).not.toHaveAttribute('data-popup-open')
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(trigger)
expect(trigger).toHaveAttribute('data-popup-open', '')
- expect(screen.getByRole('button', { name: /trigger\s*open/i })).toBeInTheDocument()
+ expect(trigger).toHaveTextContent(/trigger\s*open/i)
expect(screen.getByTestId('authorized-item'))!.toBeInTheDocument()
expect(screen.getByRole('button', { name: /addApiKey/i }))!.toBeInTheDocument()
})
@@ -141,9 +141,8 @@ describe('Authorized', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
expect(mockHandleOpenModal).toHaveBeenCalled()
- expect(screen.queryByTestId('authorized-item')).not.toBeInTheDocument()
})
it('should call onItemClick when credential is selected', () => {
@@ -158,7 +157,7 @@ describe('Authorized', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getAllByRole('button', { name: 'Select' })[0]!)
expect(onItemClick).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)
@@ -174,7 +173,7 @@ describe('Authorized', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getAllByRole('button', { name: 'Select' })[0]!)
expect(mockHandleActiveCredential).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)
@@ -195,7 +194,7 @@ describe('Authorized', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getByText(/addModelCredential/))
expect(mockHandleOpenModal).toHaveBeenCalledWith(undefined, {
@@ -215,7 +214,7 @@ describe('Authorized', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
expect(screen.queryByRole('button', { name: /addApiKey/i })).not.toBeInTheDocument()
})
@@ -231,7 +230,7 @@ describe('Authorized', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0]!)
fireEvent.click(screen.getAllByRole('button', { name: 'Delete' })[0]!)
fireEvent.click(screen.getAllByRole('button', { name: 'Select' })[0]!)
@@ -254,7 +253,7 @@ describe('Authorized', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0]!)
fireEvent.click(screen.getAllByRole('button', { name: 'Delete' })[0]!)
fireEvent.click(screen.getAllByRole('button', { name: 'Select' })[0]!)
@@ -278,11 +277,11 @@ describe('Authorized', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getAllByRole('button', { name: 'Edit' })[0]!)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getAllByRole('button', { name: 'Delete' })[0]!)
- fireEvent.click(screen.getByRole('button', { name: /trigger\s*closed/i }))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getAllByRole('button', { name: 'Select' })[0]!)
expect(mockHandleOpenModal).toHaveBeenCalledWith(mockCredentials[0], mockItems[0]!.model)
diff --git a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/dialog.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/dialog.spec.tsx
index 63320ef0f76..b937f94b2d5 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/dialog.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/dialog.spec.tsx
@@ -1,23 +1,10 @@
-import type { ReactNode } from 'react'
import type { Credential, ModelProvider } from '../../declarations'
-import { act, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import { render } from '@/test/console/render'
import { ConfigurationMethodEnum, ModelModalModeEnum } from '../../declarations'
import ModelModal from '../index'
-type DialogProps = {
- children: ReactNode
- onOpenChange?: (open: boolean) => void
-}
-
-type AlertDialogProps = {
- children: ReactNode
- onOpenChange?: (open: boolean) => void
-}
-
let mockLanguage = 'en_US'
-let latestDialogOnOpenChange: DialogProps['onOpenChange']
-let latestAlertDialogOnOpenChange: AlertDialogProps['onOpenChange']
let mockAvailableCredentials: Credential[] | undefined = []
let mockDeleteCredentialId: string | null = null
@@ -41,39 +28,6 @@ vi.mock('../../model-auth', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, onOpenChange }: DialogProps) => {
- latestDialogOnOpenChange = onOpenChange
- return <div>{children}</div>
- },
- DialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- DialogCloseButton: () => <button type="button">close</button>,
-}))
-
-vi.mock('@langgenius/dify-ui/alert-dialog', () => ({
- AlertDialog: ({ children, onOpenChange }: AlertDialogProps) => {
- latestAlertDialogOnOpenChange = onOpenChange
- return <div>{children}</div>
- },
- AlertDialogActions: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- AlertDialogCancelButton: ({ children }: { children: ReactNode }) => (
- <button type="button">{children}</button>
- ),
- AlertDialogConfirmButton: ({
- children,
- onClick,
- }: {
- children: ReactNode
- onClick?: () => void
- }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- AlertDialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- AlertDialogTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
-
vi.mock('../../model-auth/hooks', () => ({
useCredentialData: () => ({
isLoading: false,
@@ -153,53 +107,10 @@ describe('ModelModal dialog branches', () => {
beforeEach(() => {
vi.clearAllMocks()
mockLanguage = 'en_US'
- latestDialogOnOpenChange = undefined
- latestAlertDialogOnOpenChange = undefined
mockAvailableCredentials = []
mockDeleteCredentialId = null
})
- it('should only cancel when the dialog reports it has closed', () => {
- const onCancel = vi.fn()
- render(
- <ModelModal
- provider={createProvider()}
- configurateMethod={ConfigurationMethodEnum.predefinedModel}
- onCancel={onCancel}
- onSave={vi.fn()}
- onRemove={vi.fn()}
- />,
- )
-
- act(() => {
- latestDialogOnOpenChange?.(true)
- latestDialogOnOpenChange?.(false)
- })
-
- expect(onCancel).toHaveBeenCalledTimes(1)
- })
-
- it('should only close the confirm dialog when the alert dialog closes', () => {
- mockDeleteCredentialId = 'cred-1'
-
- render(
- <ModelModal
- provider={createProvider()}
- configurateMethod={ConfigurationMethodEnum.predefinedModel}
- onCancel={vi.fn()}
- onSave={vi.fn()}
- onRemove={vi.fn()}
- />,
- )
-
- act(() => {
- latestAlertDialogOnOpenChange?.(true)
- latestAlertDialogOnOpenChange?.(false)
- })
-
- expect(mockCloseConfirmDelete).toHaveBeenCalledTimes(1)
- })
-
it('should pass an empty credential list to the selector when no credentials are available', () => {
mockAvailableCredentials = undefined
diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.select.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.select.spec.tsx
index 82054f433bc..2cfed6de6c0 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.select.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.select.spec.tsx
@@ -1,45 +1,14 @@
-import type { ReactNode } from 'react'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import ParameterItem from '../parameter-item'
vi.mock('../../hooks', () => ({
useLanguage: () => 'en_US',
}))
-vi.mock('@langgenius/dify-ui/select', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@langgenius/dify-ui/select')>()
-
- return {
- ...actual,
- Select: ({
- children,
- onValueChange,
- }: {
- children: ReactNode
- onValueChange: (value: string | undefined) => void
- }) => (
- <div>
- <button type="button" onClick={() => onValueChange('updated')}>
- select-updated
- </button>
- <button type="button" onClick={() => onValueChange(undefined)}>
- select-empty
- </button>
- {children}
- </div>
- ),
- SelectContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- SelectLabel: () => null,
- SelectTrigger: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- SelectValue: () => <div>SelectValue</div>,
- SelectItemText: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- SelectItemIndicator: () => <span data-testid="select-item-indicator" />,
- }
-})
-
describe('ParameterItem select mode', () => {
- it('should propagate both explicit and empty select values', () => {
+ it('should propagate a selected value', async () => {
+ const user = userEvent.setup()
const onChange = vi.fn()
render(
@@ -57,10 +26,9 @@ describe('ParameterItem select mode', () => {
/>,
)
- fireEvent.click(screen.getByRole('button', { name: 'select-updated' }))
- fireEvent.click(screen.getByRole('button', { name: 'select-empty' }))
+ await user.click(screen.getByRole('combobox'))
+ await user.click(await screen.findByRole('option', { name: 'text' }))
- expect(onChange).toHaveBeenNthCalledWith(1, 'updated')
- expect(onChange).toHaveBeenNthCalledWith(2, undefined)
+ expect(onChange).toHaveBeenCalledWith('text')
})
})
diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx
index 890c88ecb44..901c2ba5ed9 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx
@@ -8,14 +8,6 @@ vi.mock('../../hooks', () => ({
useLanguage: () => 'en_US',
}))
-vi.mock('@langgenius/dify-ui/slider', () => ({
- Slider: ({ onValueChange }: { onValueChange: (v: number) => void }) => (
- <button onClick={() => onValueChange(2)} data-testid="slider-btn">
- Slide 2
- </button>
- ),
-}))
-
vi.mock('@/app/components/base/tag-input', () => ({
default: ({ onChange }: { onChange: (v: string[]) => void }) => (
<button onClick={() => onChange(['tag1', 'tag2'])} data-testid="tag-input">
@@ -83,7 +75,7 @@ describe('ParameterItem', () => {
const input = screen.getByRole('spinbutton')
fireEvent.change(input, { target: { value: '1.4' } })
expect(onChange).toHaveBeenCalledWith(1)
- expect(screen.getByTestId('slider-btn'))!.toBeInTheDocument()
+ expect(screen.getByRole('slider'))!.toBeInTheDocument()
})
it('should clamp float numeric input to min', () => {
@@ -139,20 +131,6 @@ describe('ParameterItem', () => {
expect(screen.getByRole('spinbutton'))!.toHaveAttribute('step', '0')
})
- it('should handle slide change and clamp values', () => {
- const onChange = vi.fn()
- render(
- <ParameterItem
- parameterRule={createRule({ type: 'float', min: 0, max: 10 })}
- value={0.7}
- onChange={onChange}
- />,
- )
-
- fireEvent.click(screen.getByTestId('slider-btn'))
- expect(onChange).toHaveBeenCalledWith(2)
- })
-
it('should render exact string input and propagate text changes', () => {
const onChange = vi.fn()
render(
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx
index 8a68107c8f4..4d7905404d9 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx
@@ -1,4 +1,4 @@
-import type { ReactElement, ReactNode } from 'react'
+import type { ReactElement } from 'react'
import type { PluginDetail } from '@/app/components/plugins/types'
import { fireEvent, screen } from '@testing-library/react'
import { PluginSource } from '@/app/components/plugins/types'
@@ -48,6 +48,10 @@ vi.mock('@/app/components/plugins/plugin-detail-panel/detail-header/hooks', () =
}),
}))
+vi.mock('@/service/use-plugins', () => ({
+ useVersionListOfPlugin: () => ({ data: { data: { versions: [] } } }),
+}))
+
vi.mock('@/app/components/plugins/plugin-detail-panel/detail-header/components', () => ({
HeaderModals: ({
targetVersion,
@@ -77,29 +81,6 @@ vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({
}),
}))
-vi.mock('@/app/components/plugins/update-plugin/plugin-version-picker', () => ({
- default: ({
- trigger,
- onSelect,
- disabled,
- }: {
- trigger: (open: boolean) => ReactNode
- onSelect: (state: { version: string; unique_identifier: string; isDowngrade?: boolean }) => void
- disabled?: boolean
- }) => (
- <div data-testid="plugin-version-picker" data-disabled={String(Boolean(disabled))}>
- {trigger(false)}
- <button
- type="button"
- onClick={() =>
- onSelect({ version: '2.0.0', unique_identifier: '[email protected]', isDowngrade: true })
- }
- >
- select version
- </button>
- </div>
- ),
-}))
vi.mock('@/hooks/use-theme', () => ({
default: () => ({ theme: 'light' }),
}))
@@ -150,20 +131,10 @@ describe('ProviderCardActions', () => {
)
})
- it('should render version controls for marketplace plugins and handle manual version selection', () => {
+ it('should render version controls for marketplace plugins', () => {
render(<ProviderCardActions detail={createDetail()} />)
- expect(screen.getByText('1.0.0')).toBeInTheDocument()
- expect(screen.getByTestId('plugin-version-picker')).toHaveAttribute('data-disabled', 'false')
-
- fireEvent.click(screen.getByRole('button', { name: 'select version' }))
-
- expect(mockSetTargetVersion).toHaveBeenCalledWith({
- version: '2.0.0',
- unique_identifier: '[email protected]',
- isDowngrade: true,
- })
- expect(mockHandleUpdate).toHaveBeenCalledWith(true)
+ expect(screen.getByRole('button', { name: '1.0.0' })).toBeEnabled()
})
it('should show a compact debug badge after the version for debugging plugins', () => {
@@ -232,7 +203,7 @@ describe('ProviderCardActions', () => {
/>,
)
- expect(screen.getByTestId('plugin-version-picker')).toHaveAttribute('data-disabled', 'true')
+ expect(screen.getByRole('button', { name: '1.0.0' })).toBeDisabled()
openActionsMenu()
expect(
screen.getByRole('menuitem', { name: 'plugin.detailPanel.operation.viewDetail' }),
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dialog.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dialog.spec.tsx
index b2e34d50897..f30764f1b79 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dialog.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/dialog.spec.tsx
@@ -1,16 +1,9 @@
-import type { ReactNode } from 'react'
import type { ModelProvider } from '../../../declarations'
import type { CredentialPanelState } from '../../use-credential-panel-state'
-import { act, fireEvent, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import { render } from '@/test/console/render'
import DropdownContent from '../dropdown-content'
-type AlertDialogProps = {
- children: ReactNode
- onOpenChange?: (open: boolean) => void
-}
-
-let latestOnOpenChange: AlertDialogProps['onOpenChange']
const mockOpenConfirmDelete = vi.fn()
const mockCloseConfirmDelete = vi.fn()
const mockHandleConfirmDelete = vi.fn()
@@ -42,44 +35,10 @@ vi.mock('../use-activate-credential', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/alert-dialog', () => ({
- AlertDialog: ({ children, onOpenChange }: AlertDialogProps) => {
- latestOnOpenChange = onOpenChange
- return <div>{children}</div>
- },
- AlertDialogActions: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- AlertDialogCancelButton: ({ children }: { children: ReactNode }) => (
- <button type="button">{children}</button>
- ),
- AlertDialogConfirmButton: ({
- children,
- onClick,
- }: {
- children: ReactNode
- onClick?: () => void
- }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- AlertDialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- AlertDialogDescription: () => <div />,
- AlertDialogTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
-
vi.mock('../api-key-section', () => ({
- default: ({
- credentials,
- onDelete,
- }: {
- credentials: unknown[]
- onDelete: (credential?: unknown) => void
- }) => (
+ default: ({ credentials }: { credentials: unknown[] }) => (
<div>
<span>{`credentials:${credentials.length}`}</span>
- <button type="button" onClick={() => onDelete(undefined)}>
- delete-undefined
- </button>
</div>
),
}))
@@ -135,7 +94,6 @@ vi.mock('@/context/permission-state', async () => {
describe('DropdownContent dialog branches', () => {
beforeEach(() => {
vi.clearAllMocks()
- latestOnOpenChange = undefined
})
it('should fall back to an empty credential list when the provider has no credentials', () => {
@@ -151,39 +109,4 @@ describe('DropdownContent dialog branches', () => {
expect(screen.getByText('credentials:0')).toBeInTheDocument()
})
-
- it('should ignore delete requests without a credential payload', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={vi.fn()}
- onClose={vi.fn()}
- />,
- )
-
- fireEvent.click(screen.getByRole('button', { name: 'delete-undefined' }))
-
- expect(mockOpenConfirmDelete).not.toHaveBeenCalled()
- })
-
- it('should only close the confirm dialog when the alert dialog reports closed', () => {
- render(
- <DropdownContent
- provider={createProvider()}
- state={createState()}
- isChangingPriority={false}
- onChangePriority={vi.fn()}
- onClose={vi.fn()}
- />,
- )
-
- act(() => {
- latestOnOpenChange?.(true)
- latestOnOpenChange?.(false)
- })
-
- expect(mockCloseConfirmDelete).toHaveBeenCalledTimes(1)
- })
})
diff --git a/web/app/components/header/account-setting/preference-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/preference-page/__tests__/index.spec.tsx
index d6095ac19a2..3006dc12a84 100644
--- a/web/app/components/header/account-setting/preference-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/preference-page/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
import { ToastHost } from '@langgenius/dify-ui/toast'
-import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
+import { screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { languages } from '@/i18n-config/language'
import { updateUserProfile } from '@/service/common'
import { render } from '@/test/console/render'
@@ -12,72 +13,6 @@ const mockMutateUserProfile = vi.fn()
let mockLocale: string | undefined = 'en-US'
let mockUserProfile: GetAccountProfileResponse
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
- const SelectContext = React.createContext<{
- disabled?: boolean
- onValueChange?: (value: string) => void
- }>({})
-
- return {
- Select: ({
- children,
- disabled,
- onValueChange,
- }: {
- children: React.ReactNode
- disabled?: boolean
- onValueChange?: (value: string) => void
- }) => {
- return (
- <SelectContext.Provider value={{ disabled, onValueChange }}>
- <div>{children}</div>
- </SelectContext.Provider>
- )
- },
- SelectTrigger: ({ children }: { children: React.ReactNode }) => {
- const context = React.useContext(SelectContext)
- return (
- <div>
- <button type="button" disabled={context.disabled}>
- {children}
- </button>
- <button
- data-testid="select-empty"
- type="button"
- onClick={() => context.onValueChange?.('')}
- >
- empty value
- </button>
- <button
- data-testid="select-invalid"
- type="button"
- onClick={() => context.onValueChange?.('__missing__')}
- >
- invalid value
- </button>
- </div>
- )
- },
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <button
- type="button"
- role="option"
- aria-selected={false}
- onClick={() => context.onValueChange?.(value)}
- >
- {children}
- </button>
- )
- },
- SelectItemText: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SelectItemIndicator: () => null,
- }
-})
-
vi.mock('@/next/navigation', () => ({
useRouter: () => ({ refresh: mockRefresh }),
}))
@@ -135,13 +70,10 @@ const getSectionByLabel = (sectionLabel: string) => {
}
const selectOption = async (sectionLabel: string, optionName: string) => {
+ const user = userEvent.setup()
const section = getSectionByLabel(sectionLabel)
- await act(async () => {
- fireEvent.click(within(section).getAllByRole('button')[0]!)
- })
- await act(async () => {
- fireEvent.click(await within(section).findByRole('option', { name: optionName }))
- })
+ await user.click(within(section).getByRole('combobox'))
+ await user.click(await screen.findByRole('option', { name: optionName }))
}
const getLanguageOption = (value: string) => {
@@ -178,8 +110,12 @@ describe('PreferencePage - Rendering', () => {
expect(screen.getByText('common.language.displayLanguage')).toBeInTheDocument()
expect(screen.getByText('common.language.timezone')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: english.name })).toBeInTheDocument()
- expect(screen.getByRole('button', { name: niueTimezone.name })).toBeInTheDocument()
+ expect(
+ within(getSectionByLabel('common.language.displayLanguage')).getByRole('combobox'),
+ ).toHaveTextContent(english.name)
+ expect(
+ within(getSectionByLabel('common.language.timezone')).getByRole('combobox'),
+ ).toHaveTextContent(niueTimezone.name)
})
it('should render placeholders when the current locale or timezone is unsupported', () => {
@@ -191,7 +127,12 @@ describe('PreferencePage - Rendering', () => {
renderPage()
- expect(screen.getAllByRole('button', { name: 'common.placeholder.select' })).toHaveLength(2)
+ expect(
+ within(getSectionByLabel('common.language.displayLanguage')).getByRole('combobox'),
+ ).toHaveTextContent('common.placeholder.select')
+ expect(
+ within(getSectionByLabel('common.language.timezone')).getByRole('combobox'),
+ ).toHaveTextContent('common.placeholder.select')
})
})
@@ -253,30 +194,4 @@ describe('PreferencePage - Interactions', () => {
expect(await screen.findByText('Timezone failed')).toBeInTheDocument()
}, 15000)
-
- it('should ignore empty and unknown language selections', async () => {
- renderPage()
-
- const section = getSectionByLabel('common.language.displayLanguage')
-
- await act(async () => {
- fireEvent.click(within(section).getByTestId('select-empty'))
- fireEvent.click(within(section).getByTestId('select-invalid'))
- })
-
- expect(updateUserProfileMock).not.toHaveBeenCalled()
- })
-
- it('should ignore empty and unknown timezone selections', async () => {
- renderPage()
-
- const section = getSectionByLabel('common.language.timezone')
-
- await act(async () => {
- fireEvent.click(within(section).getByTestId('select-empty'))
- fireEvent.click(within(section).getByTestId('select-invalid'))
- })
-
- expect(updateUserProfileMock).not.toHaveBeenCalled()
- })
})
diff --git a/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/selectPackage.spec.tsx b/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/selectPackage.spec.tsx
index 1b5ec618c25..9560916d014 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/selectPackage.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/selectPackage.spec.tsx
@@ -1,5 +1,6 @@
import type { PluginDeclaration, UpdateFromGitHubPayload } from '../../../../types'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { PluginCategoryEnum } from '../../../../types'
import SelectPackage from '../selectPackage'
@@ -21,69 +22,6 @@ vi.mock('../../../hooks', async (importOriginal) => {
}
})
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
- const SelectContext = React.createContext<{
- readOnly?: boolean
- onValueChange?: (value: string) => void
- }>({})
-
- return {
- Select: ({
- children,
- readOnly,
- onValueChange,
- }: {
- children: React.ReactNode
- readOnly?: boolean
- onValueChange?: (value: string) => void
- }) => (
- <SelectContext.Provider value={{ readOnly, onValueChange }}>
- <div>{children}</div>
- </SelectContext.Provider>
- ),
- SelectLabel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectTrigger: ({ children }: { children: React.ReactNode }) => {
- const context = React.useContext(SelectContext)
- return (
- <div>
- <div
- data-testid="select-trigger"
- className={context.readOnly ? 'cursor-not-allowed' : 'cursor-pointer'}
- >
- {children}
- </div>
- <button
- data-testid="select-empty"
- type="button"
- onClick={() => context.onValueChange?.('')}
- >
- empty select value
- </button>
- <button
- data-testid="select-invalid"
- type="button"
- onClick={() => context.onValueChange?.('__missing__')}
- >
- invalid select value
- </button>
- </div>
- )
- },
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <button type="button" onClick={() => context.onValueChange?.(value)}>
- {children}
- </button>
- )
- },
- SelectItemText: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SelectItemIndicator: () => null,
- }
-})
-
// Factory functions
const createMockManifest = (): PluginDeclaration => ({
plugin_unique_identifier: 'test-uid',
@@ -312,42 +250,20 @@ describe('SelectPackage', () => {
expect(mockHandleUpload).not.toHaveBeenCalled()
})
- it('should ignore empty and unknown version selections', () => {
- const onSelectVersion = vi.fn()
- renderSelectPackage({ onSelectVersion })
-
- const section = getSection('plugin.installFromGitHub.selectVersion')
- fireEvent.click(within(section).getByTestId('select-empty'))
- fireEvent.click(within(section).getByTestId('select-invalid'))
-
- expect(onSelectVersion).not.toHaveBeenCalled()
- })
-
- it('should select a valid version option', () => {
+ it('should select a valid version option', async () => {
+ const user = userEvent.setup()
const onSelectVersion = vi.fn()
renderSelectPackage({ onSelectVersion })
const section = getSection('plugin.installFromGitHub.selectVersion')
- fireEvent.click(within(section).getByRole('button', { name: 'v0.9.0' }))
+ await user.click(within(section).getByRole('combobox'))
+ await user.click(await screen.findByRole('option', { name: 'v0.9.0' }))
expect(onSelectVersion).toHaveBeenCalledWith({ value: 'v0.9.0', name: 'v0.9.0' })
})
- it('should ignore empty and unknown package selections', () => {
- const onSelectPackage = vi.fn()
- renderSelectPackage({
- selectedVersion: 'v1.0.0',
- onSelectPackage,
- })
-
- const section = getSection('plugin.installFromGitHub.selectPackage')
- fireEvent.click(within(section).getByTestId('select-empty'))
- fireEvent.click(within(section).getByTestId('select-invalid'))
-
- expect(onSelectPackage).not.toHaveBeenCalled()
- })
-
- it('should select a valid package option', () => {
+ it('should select a valid package option', async () => {
+ const user = userEvent.setup()
const onSelectPackage = vi.fn()
renderSelectPackage({
selectedVersion: 'v1.0.0',
@@ -355,7 +271,8 @@ describe('SelectPackage', () => {
})
const section = getSection('plugin.installFromGitHub.selectPackage')
- fireEvent.click(within(section).getByRole('button', { name: 'plugin.tar.gz' }))
+ await user.click(within(section).getByRole('combobox'))
+ await user.click(await screen.findByRole('option', { name: 'plugin.tar.gz' }))
expect(onSelectPackage).toHaveBeenCalledWith({
value: 'plugin.tar.gz',
@@ -563,16 +480,16 @@ describe('SelectPackage', () => {
renderSelectPackage({ selectedVersion: '' })
// When no version is selected, package select should be readonly
- const trigger = screen.getAllByTestId('select-trigger')[1]
- expect(trigger).toHaveClass('cursor-not-allowed')
+ const trigger = screen.getAllByRole('combobox')[1]
+ expect(trigger).toHaveAttribute('aria-readonly', 'true')
})
it('should make package select active when version is selected', () => {
renderSelectPackage({ selectedVersion: 'v1.0.0' })
// When version is selected, package select should be active
- const trigger = screen.getAllByTestId('select-trigger')[1]
- expect(trigger).toHaveClass('cursor-pointer')
+ const trigger = screen.getAllByRole('combobox')[1]
+ expect(trigger).not.toHaveAttribute('aria-readonly', 'true')
})
})
diff --git a/web/app/components/plugins/marketplace/search-box/__tests__/tags-filter.spec.tsx b/web/app/components/plugins/marketplace/search-box/__tests__/tags-filter.spec.tsx
index ed4cc1e6988..bc1e3a2986a 100644
--- a/web/app/components/plugins/marketplace/search-box/__tests__/tags-filter.spec.tsx
+++ b/web/app/components/plugins/marketplace/search-box/__tests__/tags-filter.spec.tsx
@@ -33,8 +33,6 @@ vi.mock('@/app/components/plugins/hooks', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
describe('TagsFilter', () => {
const ensurePopoverOpen = async (user: ReturnType<typeof userEvent.setup>) => {
if (!screen.queryByRole('searchbox', { name: 'pluginTags.searchTags' }))
diff --git a/web/app/components/plugins/marketplace/sort-dropdown/__tests__/index.spec.tsx b/web/app/components/plugins/marketplace/sort-dropdown/__tests__/index.spec.tsx
index bdd62b95299..64308a69659 100644
--- a/web/app/components/plugins/marketplace/sort-dropdown/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/marketplace/sort-dropdown/__tests__/index.spec.tsx
@@ -1,4 +1,3 @@
-import type { MouseEventHandler, ReactNode } from 'react'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import SortDropdown from '../index'
@@ -33,78 +32,6 @@ vi.mock('../../atoms', () => ({
useMarketplaceSort: () => [mockSort, mockHandleSortChange],
}))
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- open: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div data-testid="dropdown-wrapper" data-open={open}>
- {children}
- </div>
- </DropdownMenuContext>
- ),
- DropdownMenuTrigger: ({ children, className }: { children: ReactNode; className?: string }) => {
- const { open, setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- className={className}
- data-testid="dropdown-trigger"
- onClick={() => setOpen(!open)}
- >
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({ children }: { children: ReactNode }) => {
- const { open } = useDropdownMenuContext()
- return open ? <div data-testid="dropdown-content">{children}</div> : null
- },
- DropdownMenuItem: ({
- children,
- onClick,
- className,
- }: {
- children: ReactNode
- onClick?: MouseEventHandler<HTMLButtonElement>
- className?: string
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- className={className}
- onClick={(event) => {
- onClick?.(event)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- }
-})
-
describe('SortDropdown', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -114,7 +41,7 @@ describe('SortDropdown', () => {
it('renders the selected sort option in the trigger', () => {
render(<SortDropdown />)
- const trigger = screen.getByTestId('dropdown-trigger')
+ const trigger = screen.getByRole('button', { name: 'Sort by Most Popular' })
expect(within(trigger).getByText('Sort by')).toBeInTheDocument()
expect(within(trigger).getByText('Most Popular')).toBeInTheDocument()
})
@@ -131,9 +58,9 @@ describe('SortDropdown', () => {
const user = userEvent.setup()
render(<SortDropdown />)
- await user.click(screen.getByTestId('dropdown-trigger'))
+ await user.click(screen.getByRole('button', { name: 'Sort by Most Popular' }))
- const content = screen.getByTestId('dropdown-content')
+ const content = await screen.findByRole('menu')
expect(within(content).getByText('Most Popular')).toBeInTheDocument()
expect(within(content).getByText('Recently Updated')).toBeInTheDocument()
expect(within(content).getByText('Newly Released')).toBeInTheDocument()
@@ -142,24 +69,24 @@ describe('SortDropdown', () => {
it('shows a check icon for the currently selected option', async () => {
const user = userEvent.setup()
- const { container } = render(<SortDropdown />)
+ render(<SortDropdown />)
- await user.click(screen.getByTestId('dropdown-trigger'))
+ await user.click(screen.getByRole('button', { name: 'Sort by Most Popular' }))
- expect(container.querySelector('.i-ri-check-line')).toBeInTheDocument()
+ expect(document.querySelector('.i-ri-check-line')).toBeInTheDocument()
})
it('updates the sort and closes the menu when an option is selected', async () => {
const user = userEvent.setup()
render(<SortDropdown />)
- await user.click(screen.getByTestId('dropdown-trigger'))
- await user.click(screen.getByText('Recently Updated'))
+ await user.click(screen.getByRole('button', { name: 'Sort by Most Popular' }))
+ await user.click(await screen.findByRole('menuitem', { name: 'Recently Updated' }))
expect(mockHandleSortChange).toHaveBeenCalledWith({
sortBy: 'version_updated_at',
sortOrder: 'DESC',
})
- expect(screen.queryByTestId('dropdown-content')).not.toBeInTheDocument()
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx
index 2d1069dccad..42e69745f7a 100644
--- a/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx
@@ -82,8 +82,6 @@ vi.mock('@/hooks/use-oauth', () => ({
openOAuthPopup: vi.fn(),
}))
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-
const mockConsoleState = vi.hoisted(() => ({
userProfile: { id: 'test-user', name: 'Test User', email: '[email protected]', avatar_url: '' },
workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'] as string[],
@@ -203,13 +201,10 @@ describe('Authorized Component', () => {
{ wrapper: createWrapper() },
)
- const trigger = screen.getByTestId('popover-trigger')
- expect(trigger).not.toHaveAttribute('data-popup-open')
expect(screen.getByText('Closed'))!.toBeInTheDocument()
fireEvent.click(screen.getByTestId('custom-trigger'))
- expect(trigger).toHaveAttribute('data-popup-open', '')
expect(screen.getByText('Open')).toBeInTheDocument()
})
diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
index f67ef0a9496..a91e74a6fef 100644
--- a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
@@ -1,4 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { InputVarType } from '@/app/components/workflow/types'
import AppInputsForm from '../app-inputs-form'
@@ -26,59 +27,6 @@ vi.mock('@/app/components/base/file-uploader', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
- const SelectContext = React.createContext<{
- onValueChange?: (value: string) => void
- }>({})
-
- return {
- Select: ({
- children,
- onValueChange,
- }: {
- children: React.ReactNode
- onValueChange?: (value: string) => void
- }) => (
- <SelectContext.Provider value={{ onValueChange }}>
- <div>{children}</div>
- </SelectContext.Provider>
- ),
- SelectTrigger: ({ children }: { children: React.ReactNode }) => {
- const context = React.useContext(SelectContext)
-
- return (
- <div>
- <button type="button">{children}</button>
- <button
- data-testid="select-empty"
- type="button"
- onClick={() => context.onValueChange?.('')}
- >
- Empty Select
- </button>
- </div>
- )
- },
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <button
- key={value}
- data-testid={`select-${value}`}
- type="button"
- onClick={() => context.onValueChange?.(value)}
- >
- {children}
- </button>
- )
- },
- SelectItemText: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SelectItemIndicator: () => null,
- }
-})
-
describe('AppInputsForm', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -146,7 +94,8 @@ describe('AppInputsForm', () => {
expect(onFormChange).toHaveBeenCalledWith({ count: '42' })
})
- it('should update select values', () => {
+ it('should update select values', async () => {
+ const user = userEvent.setup()
const onFormChange = vi.fn()
const inputsRef = { current: { tone: '' } }
@@ -167,38 +116,12 @@ describe('AppInputsForm', () => {
/>,
)
- fireEvent.click(screen.getByTestId('select-formal'))
+ await user.click(screen.getByRole('combobox'))
+ await user.click(await screen.findByRole('option', { name: 'formal' }))
expect(onFormChange).toHaveBeenCalledWith({ tone: 'formal' })
})
- it('should ignore empty select values and render the placeholder when there is no current selection', () => {
- const onFormChange = vi.fn()
- const inputsRef = { current: { tone: '' } }
-
- render(
- <AppInputsForm
- inputsForms={[
- {
- variable: 'tone',
- label: 'Tone',
- type: InputVarType.select,
- options: ['friendly', 'formal'],
- required: false,
- },
- ]}
- inputs={{ tone: '' }}
- inputsRef={inputsRef}
- onFormChange={onFormChange}
- />,
- )
-
- expect(screen.getAllByText('Tone').length).toBeGreaterThan(0)
- fireEvent.click(screen.getByTestId('select-empty'))
-
- expect(onFormChange).not.toHaveBeenCalled()
- })
-
it('should update uploaded single file values', () => {
const onFormChange = vi.fn()
const inputsRef = { current: { attachment: null } }
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
index 1a4cb2fced0..e849f6ef2bd 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
@@ -36,6 +36,10 @@ vi.mock('@/service/use-tools', () => ({
}),
}))
+vi.mock('@/service/use-plugins', () => ({
+ useVersionListOfPlugin: () => ({ data: { data: { versions: [] } } }),
+}))
+
vi.mock('@/utils/var', () => ({
getMarketplaceUrl: (path: string) => `https://marketplace.example.com${path}`,
}))
@@ -48,24 +52,12 @@ vi.mock('@/app/components/base/action-button', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) => (
- <button onClick={onClick}>{children}</button>
- ),
-}))
-
vi.mock('@/app/components/base/badge', () => ({
default: ({ text, children }: { text?: React.ReactNode; children?: React.ReactNode }) => (
<div data-testid="badge">{text ?? children}</div>
),
}))
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- TooltipTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,
- TooltipContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
vi.mock('@/app/components/plugins/plugin-auth', () => ({
AuthCategory: {
tool: 'tool',
@@ -75,28 +67,6 @@ vi.mock('@/app/components/plugins/plugin-auth', () => ({
),
}))
-vi.mock('@/app/components/plugins/update-plugin/plugin-version-picker', () => ({
- default: ({
- onSelect,
- trigger,
- }: {
- onSelect: (value: { version: string; unique_identifier: string; isDowngrade?: boolean }) => void
- trigger: React.ReactNode
- }) => (
- <div>
- {trigger}
- <button
- data-testid="version-select"
- onClick={() =>
- onSelect({ version: '2.0.0', unique_identifier: 'uid-2', isDowngrade: true })
- }
- >
- select version
- </button>
- </div>
- ),
-}))
-
vi.mock('@/app/components/base/badges/verified', () => ({
default: () => <div data-testid="verified" />,
}))
@@ -244,21 +214,14 @@ describe('DetailHeader', () => {
expect(screen.getByTestId('header-modals')).toBeInTheDocument()
})
- it('wires version selection, latest update, and hide actions', () => {
+ it('wires latest update and hide actions', () => {
const onHide = vi.fn()
render(<DetailHeader detail={createDetail()} onHide={onHide} onUpdate={vi.fn()} />)
- fireEvent.click(screen.getByTestId('version-select'))
fireEvent.click(screen.getByText('plugin.detailPanel.operation.update'))
fireEvent.click(screen.getByTestId('close-button'))
- expect(mockSetTargetVersion).toHaveBeenCalledWith({
- version: '2.0.0',
- unique_identifier: 'uid-2',
- isDowngrade: true,
- })
- expect(mockHandleUpdate).toHaveBeenCalledTimes(2)
- expect(mockHandleUpdate).toHaveBeenNthCalledWith(1, true)
+ expect(mockHandleUpdate).toHaveBeenCalledTimes(1)
expect(onHide).toHaveBeenCalled()
})
})
diff --git a/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/tts-params-panel.spec.tsx b/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/tts-params-panel.spec.tsx
index 28c4b475935..f2be3c2d620 100644
--- a/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/tts-params-panel.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/tts-params-panel.spec.tsx
@@ -1,689 +1,73 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import * as React from 'react'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-// Import component after mocks
+import { fireEvent, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import TTSParamsPanel from '../tts-params-panel'
-// ==================== Mock Setup ====================
-// All vi.mock() calls are hoisted, so inline all mock data
-
-// Mock languages data with inline definition
vi.mock('@/i18n-config/language', () => ({
languages: [
- { value: 'en-US', name: 'English (United States)', supported: true },
- { value: 'zh-Hans', name: '简体中文', supported: true },
- { value: 'ja-JP', name: '日本語', supported: true },
- { value: 'unsupported-lang', name: 'Unsupported Language', supported: false },
+ { value: 'en-US', name: 'English', supported: true },
+ { value: 'zh-Hans', name: 'Chinese', supported: true },
+ { value: 'unsupported', name: 'Unsupported', supported: false },
],
}))
-const MockSelectContext = React.createContext<{
- value: string
- onValueChange: (value: string) => void
-}>({
- value: '',
- onValueChange: () => {},
-})
-
-vi.mock('@langgenius/dify-ui/select', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@langgenius/dify-ui/select')>()
-
- return {
- ...actual,
- Select: ({
- value,
- onValueChange,
- children,
- }: {
- value: string
- onValueChange: (value: string) => void
- children: React.ReactNode
- }) => (
- <MockSelectContext.Provider value={{ value, onValueChange }}>
- <div data-testid="select-root">{children}</div>
- </MockSelectContext.Provider>
- ),
- SelectTrigger: ({
- children,
- className,
- 'data-testid': testId,
- }: {
- children: React.ReactNode
- className?: string
- 'data-testid'?: string
- }) => (
- <button data-testid={testId ?? 'select-trigger'} data-class={className}>
- {children}
- </button>
- ),
- SelectValue: () => {
- const { value } = React.useContext(MockSelectContext)
- return <span data-testid="selected-value">{value}</span>
- },
- SelectContent: ({
- children,
- popupClassName,
- }: {
- children: React.ReactNode
- popupClassName?: string
- }) => (
- <div data-testid="select-content" data-popup-class={popupClassName}>
- {children}
- </div>
- ),
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const { onValueChange } = React.useContext(MockSelectContext)
- return (
- <button data-testid={`select-item-${value}`} onClick={() => onValueChange(value)}>
- {children}
- </button>
- )
- },
- SelectItemText: ({
- children,
- className,
- }: {
- children: React.ReactNode
- className?: string
- }) => <span data-class={className}>{children}</span>,
- SelectItemIndicator: ({ className }: { className?: string }) => (
- <span data-testid="select-item-indicator" data-class={className} />
- ),
- }
-})
-
-// ==================== Test Utilities ====================
-
-/**
- * Factory function to create a voice item
- */
-const createVoiceItem = (overrides: Partial<{ mode: string; name: string }> = {}) => ({
- mode: 'alloy',
- name: 'Alloy',
- ...overrides,
-})
-
-/**
- * Factory function to create a currentModel with voices
- */
-const createCurrentModel = (voices: Array<{ mode: string; name: string }> = []) => ({
+const model = {
model_properties: {
- voices,
+ voices: [
+ { mode: 'alloy', name: 'Alloy' },
+ { mode: 'echo', name: 'Echo' },
+ ],
},
-})
-
-/**
- * Factory function to create default props
- */
-const createDefaultProps = (
- overrides: Partial<{
- currentModel: { model_properties: { voices: Array<{ mode: string; name: string }> } } | null
- language: string
- voice: string
- onChange: (language: string, voice: string) => void
- }> = {},
-) => ({
- currentModel: createCurrentModel([
- createVoiceItem({ mode: 'alloy', name: 'Alloy' }),
- createVoiceItem({ mode: 'echo', name: 'Echo' }),
- createVoiceItem({ mode: 'fable', name: 'Fable' }),
- ]),
- language: 'en-US',
- voice: 'alloy',
- onChange: vi.fn(),
- ...overrides,
-})
-
-// ==================== Tests ====================
+}
describe('TTSParamsPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks()
+ it('renders the selected language and voice', () => {
+ render(
+ <TTSParamsPanel currentModel={model} language="en-US" voice="alloy" onChange={vi.fn()} />,
+ )
+
+ expect(
+ screen.getByRole('combobox', { name: 'appDebug.voice.voiceSettings.language' }),
+ ).toHaveTextContent('en-US')
+ expect(
+ screen.getByRole('combobox', { name: 'appDebug.voice.voiceSettings.voice' }),
+ ).toHaveTextContent('alloy')
})
- // ==================== Rendering Tests ====================
- describe('Rendering', () => {
- it('should render language label', () => {
- // Arrange
- const props = createDefaultProps()
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByText('appDebug.voice.voiceSettings.language'))!.toBeInTheDocument()
- })
-
- it('should render voice label', () => {
- // Arrange
- const props = createDefaultProps()
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByText('appDebug.voice.voiceSettings.voice'))!.toBeInTheDocument()
- })
-
- it('should render two Select components', () => {
- // Arrange
- const props = createDefaultProps()
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- const selects = screen.getAllByTestId('select-root')
- expect(selects).toHaveLength(2)
- })
-
- it('should render language select with correct value', () => {
- // Arrange
- const props = createDefaultProps({ language: 'zh-Hans' })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- const values = screen.getAllByTestId('selected-value')
- expect(values[0])!.toHaveTextContent('zh-Hans')
- })
-
- it('should render voice select with correct value', () => {
- // Arrange
- const props = createDefaultProps({ voice: 'echo' })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- const values = screen.getAllByTestId('selected-value')
- expect(values[1])!.toHaveTextContent('echo')
- })
-
- it('should only show supported languages in language select', () => {
- // Arrange
- const props = createDefaultProps()
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('select-item-en-US'))!.toBeInTheDocument()
- expect(screen.getByTestId('select-item-zh-Hans'))!.toBeInTheDocument()
- expect(screen.getByTestId('select-item-ja-JP'))!.toBeInTheDocument()
- expect(screen.queryByTestId('select-item-unsupported-lang')).not.toBeInTheDocument()
- })
-
- it('should render voice items from currentModel', () => {
- // Arrange
- const props = createDefaultProps()
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('select-item-alloy'))!.toBeInTheDocument()
- expect(screen.getByTestId('select-item-echo'))!.toBeInTheDocument()
- expect(screen.getByTestId('select-item-fable'))!.toBeInTheDocument()
- })
+ it('only exposes supported languages and preserves the selected voice', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ render(
+ <TTSParamsPanel currentModel={model} language="en-US" voice="alloy" onChange={onChange} />,
+ )
+
+ await user.click(
+ screen.getByRole('combobox', { name: 'appDebug.voice.voiceSettings.language' }),
+ )
+ const listbox = await screen.findByRole('listbox')
+ expect(within(listbox).queryByRole('option', { name: 'Unsupported' })).not.toBeInTheDocument()
+ await user.click(within(listbox).getByRole('option', { name: 'Chinese' }))
+
+ expect(onChange).toHaveBeenCalledWith('zh-Hans', 'alloy')
})
- // ==================== Props Testing ====================
-
- // ==================== Event Handlers ====================
- describe('Event Handlers', () => {
- describe('setLanguage', () => {
- it('should call onChange with new language and current voice', () => {
- // Arrange
- const onChange = vi.fn()
- const props = createDefaultProps({
- onChange,
- language: 'en-US',
- voice: 'alloy',
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
- fireEvent.click(screen.getByTestId('select-item-zh-Hans'))
-
- // Assert
- expect(onChange).toHaveBeenCalledWith('zh-Hans', 'alloy')
- })
-
- it('should call onChange with different languages', () => {
- // Arrange
- const onChange = vi.fn()
- const props = createDefaultProps({
- onChange,
- language: 'en-US',
- voice: 'echo',
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
- fireEvent.click(screen.getByTestId('select-item-ja-JP'))
-
- // Assert
- expect(onChange).toHaveBeenCalledWith('ja-JP', 'echo')
- })
+ it('changes the voice while preserving the selected language', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ render(
+ <TTSParamsPanel currentModel={model} language="en-US" voice="alloy" onChange={onChange} />,
+ )
- it('should preserve voice when changing language', () => {
- // Arrange
- const onChange = vi.fn()
- const props = createDefaultProps({
- onChange,
- language: 'en-US',
- voice: 'fable',
- })
+ await user.click(screen.getByRole('combobox', { name: 'appDebug.voice.voiceSettings.voice' }))
+ await user.click(await screen.findByRole('option', { name: 'Echo' }))
- // Act
- render(<TTSParamsPanel {...props} />)
- fireEvent.click(screen.getByTestId('select-item-zh-Hans'))
-
- // Assert
- expect(onChange).toHaveBeenCalledWith('zh-Hans', 'fable')
- })
- })
-
- describe('setVoice', () => {
- it('should call onChange with current language and new voice', () => {
- // Arrange
- const onChange = vi.fn()
- const props = createDefaultProps({
- onChange,
- language: 'en-US',
- voice: 'alloy',
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
- fireEvent.click(screen.getByTestId('select-item-echo'))
-
- // Assert
- expect(onChange).toHaveBeenCalledWith('en-US', 'echo')
- })
-
- it('should call onChange with different voices', () => {
- // Arrange
- const onChange = vi.fn()
- const props = createDefaultProps({
- onChange,
- language: 'zh-Hans',
- voice: 'alloy',
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
- fireEvent.click(screen.getByTestId('select-item-fable'))
-
- // Assert
- expect(onChange).toHaveBeenCalledWith('zh-Hans', 'fable')
- })
-
- it('should preserve language when changing voice', () => {
- // Arrange
- const onChange = vi.fn()
- const props = createDefaultProps({
- onChange,
- language: 'ja-JP',
- voice: 'alloy',
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
- fireEvent.click(screen.getByTestId('select-item-echo'))
-
- // Assert
- expect(onChange).toHaveBeenCalledWith('ja-JP', 'echo')
- })
- })
+ expect(onChange).toHaveBeenCalledWith('en-US', 'echo')
})
- // ==================== Memoization ====================
- describe('Memoization - voiceList', () => {
- it('should return empty array when currentModel is null', () => {
- // Arrange
- const props = createDefaultProps({ currentModel: null })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- // Assert - no voice items should be rendered
- expect(screen.queryByTestId('select-item-alloy')).not.toBeInTheDocument()
- expect(screen.queryByTestId('select-item-echo')).not.toBeInTheDocument()
- })
-
- it('should return empty array when currentModel is undefined', () => {
- // Arrange
- const props = {
- currentModel: undefined,
- language: 'en-US',
- voice: 'alloy',
- onChange: vi.fn(),
- }
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- expect(screen.queryByTestId('select-item-alloy')).not.toBeInTheDocument()
- })
-
- it('should map voices with mode as value', () => {
- // Arrange
- const props = createDefaultProps({
- currentModel: createCurrentModel([
- { mode: 'voice-1', name: 'Voice One' },
- { mode: 'voice-2', name: 'Voice Two' },
- ]),
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('select-item-voice-1'))!.toBeInTheDocument()
- expect(screen.getByTestId('select-item-voice-2'))!.toBeInTheDocument()
- })
-
- it('should handle currentModel with empty voices array', () => {
- // Arrange
- const props = createDefaultProps({
- currentModel: createCurrentModel([]),
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert - no voice items (except language items)
- expect(screen.getAllByTestId('select-content')[1]!.children).toHaveLength(0)
- expect(screen.queryByTestId('select-item-alloy')).not.toBeInTheDocument()
- })
-
- it('should handle currentModel with single voice', () => {
- // Arrange
- const props = createDefaultProps({
- currentModel: createCurrentModel([{ mode: 'single-voice', name: 'Single Voice' }]),
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('select-item-single-voice'))!.toBeInTheDocument()
- })
- })
-
- // ==================== Edge Cases ====================
- describe('Edge Cases', () => {
- it('should handle empty language value', () => {
- // Arrange
- const props = createDefaultProps({ language: '' })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- const values = screen.getAllByTestId('selected-value')
- expect(values[0])!.toHaveTextContent('')
- })
-
- it('should handle empty voice value', () => {
- // Arrange
- const props = createDefaultProps({ voice: '' })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- const values = screen.getAllByTestId('selected-value')
- expect(values[1])!.toHaveTextContent('')
- })
-
- it('should handle many voices', () => {
- // Arrange
- const manyVoices = Array.from({ length: 20 }, (_, i) => ({
- mode: `voice-${i}`,
- name: `Voice ${i}`,
- }))
- const props = createDefaultProps({
- currentModel: createCurrentModel(manyVoices),
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('select-item-voice-0'))!.toBeInTheDocument()
- expect(screen.getByTestId('select-item-voice-19'))!.toBeInTheDocument()
- })
-
- it('should handle voice with special characters in mode', () => {
- // Arrange
- const props = createDefaultProps({
- currentModel: createCurrentModel([
- { mode: 'voice-with_special.chars', name: 'Special Voice' },
- ]),
- })
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('select-item-voice-with_special.chars'))!.toBeInTheDocument()
- })
-
- it('should handle onChange not being called multiple times', () => {
- // Arrange
- const onChange = vi.fn()
- const props = createDefaultProps({ onChange })
-
- // Act
- render(<TTSParamsPanel {...props} />)
- fireEvent.click(screen.getByTestId('select-item-echo'))
-
- // Assert
- expect(onChange).toHaveBeenCalledTimes(1)
- })
- })
-
- // ==================== Re-render Behavior ====================
- describe('Re-render Behavior', () => {
- it('should update when language prop changes', () => {
- // Arrange
- const props = createDefaultProps({ language: 'en-US' })
-
- // Act
- const { rerender } = render(<TTSParamsPanel {...props} />)
- const values = screen.getAllByTestId('selected-value')
- expect(values[0])!.toHaveTextContent('en-US')
-
- rerender(<TTSParamsPanel {...props} language="zh-Hans" />)
-
- // Assert
- const updatedValues = screen.getAllByTestId('selected-value')
- expect(updatedValues[0])!.toHaveTextContent('zh-Hans')
- })
-
- it('should update when voice prop changes', () => {
- // Arrange
- const props = createDefaultProps({ voice: 'alloy' })
-
- // Act
- const { rerender } = render(<TTSParamsPanel {...props} />)
- const values = screen.getAllByTestId('selected-value')
- expect(values[1])!.toHaveTextContent('alloy')
-
- rerender(<TTSParamsPanel {...props} voice="echo" />)
-
- // Assert
- const updatedValues = screen.getAllByTestId('selected-value')
- expect(updatedValues[1])!.toHaveTextContent('echo')
- })
-
- it('should update voice list when currentModel changes', () => {
- // Arrange
- const initialModel = createCurrentModel([{ mode: 'alloy', name: 'Alloy' }])
- const props = createDefaultProps({ currentModel: initialModel })
-
- // Act
- const { rerender } = render(<TTSParamsPanel {...props} />)
- expect(screen.getByTestId('select-item-alloy'))!.toBeInTheDocument()
- expect(screen.queryByTestId('select-item-nova')).not.toBeInTheDocument()
-
- const newModel = createCurrentModel([
- { mode: 'alloy', name: 'Alloy' },
- { mode: 'nova', name: 'Nova' },
- ])
- rerender(<TTSParamsPanel {...props} currentModel={newModel} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('select-item-alloy'))!.toBeInTheDocument()
- expect(screen.getByTestId('select-item-nova'))!.toBeInTheDocument()
- })
-
- it('should handle currentModel becoming null', () => {
- // Arrange
- const props = createDefaultProps()
-
- // Act
- const { rerender } = render(<TTSParamsPanel {...props} />)
- expect(screen.getByTestId('select-item-alloy'))!.toBeInTheDocument()
-
- rerender(<TTSParamsPanel {...props} currentModel={null} />)
-
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- expect(screen.queryByTestId('select-item-alloy')).not.toBeInTheDocument()
- })
- })
-
- // ==================== Accessibility ====================
- describe('Accessibility', () => {
- it('should have proper label structure for language select', () => {
- // Arrange
- const props = createDefaultProps()
-
- // Act
- render(<TTSParamsPanel {...props} />)
-
- // Assert
- const languageLabel = screen.getByText('appDebug.voice.voiceSettings.language')
- expect(languageLabel)!.toHaveClass('system-sm-semibold')
- })
-
- it('should have proper label structure for voice select', () => {
- // Arrange
- const props = createDefaultProps()
+ it('renders an empty voice list without a model', async () => {
+ render(<TTSParamsPanel currentModel={null} language="en-US" voice="" onChange={vi.fn()} />)
- // Act
- render(<TTSParamsPanel {...props} />)
+ fireEvent.click(screen.getByRole('combobox', { name: 'appDebug.voice.voiceSettings.voice' }))
- // Assert
- const voiceLabel = screen.getByText('appDebug.voice.voiceSettings.voice')
- expect(voiceLabel)!.toHaveClass('system-sm-semibold')
- })
+ expect(await screen.findByRole('listbox')).toBeEmptyDOMElement()
})
})
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-entry.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-entry.spec.tsx
index 758909fffeb..37186813f83 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-entry.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-entry.spec.tsx
@@ -1,72 +1,10 @@
import type { TriggerSubscription } from '@/app/components/workflow/block-selector/types'
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TriggerCredentialType } from '@/app/components/workflow/block-selector/types'
import { SubscriptionSelectorEntry } from '../selector-entry'
-vi.mock('@langgenius/dify-ui/popover', async () => {
- const React = await import('react')
- const PopoverContext = React.createContext({
- open: false,
- setOpen: (_open: boolean) => {},
- })
-
- const Popover = ({
- children,
- open: controlledOpen,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) => {
- const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false)
- const isControlled = controlledOpen !== undefined
- const open = isControlled ? !!controlledOpen : uncontrolledOpen
- const setOpen = (nextOpen: boolean) => {
- if (!isControlled) setUncontrolledOpen(nextOpen)
- onOpenChange?.(nextOpen)
- }
-
- return <PopoverContext.Provider value={{ open, setOpen }}>{children}</PopoverContext.Provider>
- }
-
- type TriggerProps = React.HTMLAttributes<HTMLElement> & {
- 'data-popup-open'?: string
- 'data-testid'?: string
- }
-
- const PopoverTrigger = ({
- render,
- }: {
- render:
- | React.ReactNode
- | ((props: TriggerProps, state: { open: boolean }) => React.ReactElement)
- }) => {
- const { open, setOpen } = React.useContext(PopoverContext)
- const props: TriggerProps = {
- 'data-testid': 'popover-trigger',
- 'data-popup-open': open ? '' : undefined,
- onClick: () => setOpen(!open),
- }
-
- if (typeof render === 'function') return render(props, { open })
-
- return <div {...props}>{render}</div>
- }
-
- const PopoverContent = ({ children }: { children: React.ReactNode }) => {
- const { open } = React.useContext(PopoverContext)
- return open ? <div data-testid="popover-content">{children}</div> : null
- }
-
- return {
- Popover,
- PopoverTrigger,
- PopoverContent,
- }
-})
-
let mockSubscriptions: TriggerSubscription[] = []
const mockRefetch = vi.fn()
@@ -128,16 +66,15 @@ describe('SubscriptionSelectorEntry', () => {
).toBeInTheDocument()
})
- it('should render placeholder when open without selection', () => {
+ it('should render placeholder when open without selection', async () => {
+ const user = userEvent.setup()
render(<SubscriptionSelectorEntry selectedId={undefined} onSelect={vi.fn()} />)
- const trigger = screen.getByTestId('popover-trigger')
- expect(trigger).not.toHaveAttribute('data-popup-open')
+ await user.click(screen.getByRole('button'))
- fireEvent.click(screen.getByRole('button'))
-
- expect(trigger).toHaveAttribute('data-popup-open', '')
- expect(screen.getByText('pluginTrigger.subscription.selectPlaceholder')).toBeInTheDocument()
+ expect(
+ await screen.findByText('pluginTrigger.subscription.selectPlaceholder'),
+ ).toBeInTheDocument()
})
it('should show selected subscription name when id matches', () => {
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/index.spec.tsx
index 504fd9ec9eb..6d819b8a53b 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/__tests__/index.spec.tsx
@@ -1,1999 +1,210 @@
-import type { SimpleDetail } from '../../../store'
import type {
TriggerOAuthConfig,
TriggerProviderApiEntity,
TriggerSubscription,
- TriggerSubscriptionBuilder,
} from '@/app/components/workflow/block-selector/types'
-import { toast } from '@langgenius/dify-ui/toast'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { SupportedCreationMethods } from '@/app/components/plugins/types'
-import { TriggerCredentialType } from '@/app/components/workflow/block-selector/types'
import { CreateSubscriptionButton } from '../index'
-import { CreateButtonType, DEFAULT_METHOD } from '../types'
+
+const toastMocks = vi.hoisted(() => ({
+ success: vi.fn(),
+ error: vi.fn(),
+}))
vi.mock('@langgenius/dify-ui/toast', () => ({
- toast: Object.assign(vi.fn(), {
- success: vi.fn(),
- error: vi.fn(),
- warning: vi.fn(),
- info: vi.fn(),
- dismiss: vi.fn(),
- update: vi.fn(),
- promise: vi.fn(),
- }),
+ toast: toastMocks,
}))
-let mockStoreDetail: SimpleDetail | undefined
vi.mock('../../../store', () => ({
- usePluginStore: (
- selector: (state: { detail: SimpleDetail | undefined }) => SimpleDetail | undefined,
- ) => selector({ detail: mockStoreDetail }),
+ usePluginStore: (selector: (state: { detail: { provider: string } }) => unknown) =>
+ selector({ detail: { provider: 'test-provider' } }),
}))
const mockSubscriptions: TriggerSubscription[] = []
-const mockRefetch = vi.fn()
vi.mock('../../use-subscription-list', () => ({
- useSubscriptionList: () => ({
- subscriptions: mockSubscriptions,
- refetch: mockRefetch,
- }),
+ useSubscriptionList: () => ({ subscriptions: mockSubscriptions }),
}))
-let mockProviderInfo: { data: TriggerProviderApiEntity | undefined } = { data: undefined }
-let mockOAuthConfig: { data: TriggerOAuthConfig | undefined; refetch: () => void } = {
- data: undefined,
- refetch: vi.fn(),
-}
+let mockProviderInfo: TriggerProviderApiEntity | undefined
+let mockOAuthConfig: TriggerOAuthConfig | undefined
+const mockRefetchOAuthConfig = vi.fn()
const mockInitiateOAuth = vi.fn()
vi.mock('@/service/use-triggers', () => ({
- useTriggerProviderInfo: () => mockProviderInfo,
- useTriggerOAuthConfig: () => mockOAuthConfig,
- useInitiateTriggerOAuth: () => ({
- mutate: mockInitiateOAuth,
- }),
+ useTriggerProviderInfo: () => ({ data: mockProviderInfo }),
+ useTriggerOAuthConfig: () => ({ data: mockOAuthConfig, refetch: mockRefetchOAuthConfig }),
+ useInitiateTriggerOAuth: () => ({ mutate: mockInitiateOAuth }),
}))
+const mockOpenOAuthPopup = vi.fn()
vi.mock('@/hooks/use-oauth', () => ({
- openOAuthPopup: vi.fn((url: string, callback: (data?: unknown) => void) => {
- callback({ success: true, subscriptionId: 'test-subscription' })
- }),
+ openOAuthPopup: (...args: unknown[]) => mockOpenOAuthPopup(...args),
}))
vi.mock('../common-modal', () => ({
CommonCreateModal: ({
open,
createType,
- onClose,
builder,
+ onClose,
}: {
- open?: boolean
+ open: boolean
createType: SupportedCreationMethods
+ builder?: { id: string }
onClose: () => void
- builder?: TriggerSubscriptionBuilder
- }) => {
- if (open === false) return null
-
- return (
- <div
- data-testid="common-create-modal"
- data-create-type={createType}
- data-has-builder={!!builder}
- >
- <button data-testid="close-modal" onClick={onClose}>
- Close
- </button>
+ }) =>
+ open ? (
+ <div role="dialog" data-create-type={createType} data-builder-id={builder?.id}>
+ <button onClick={onClose}>Close create modal</button>
</div>
- )
- },
+ ) : null,
}))
vi.mock('../oauth-client', () => ({
OAuthClientSettingsModal: ({
open,
- oauthConfig,
onOpenChange,
- showOAuthCreateModal,
}: {
open: boolean
- oauthConfig?: TriggerOAuthConfig
onOpenChange: (open: boolean) => void
- showOAuthCreateModal: (builder: TriggerSubscriptionBuilder) => void
- }) => {
- if (!open) return null
-
- return (
- <div data-testid="oauth-client-modal" data-has-config={!!oauthConfig}>
- <button data-testid="close-oauth-modal" onClick={() => onOpenChange(false)}>
- Close
- </button>
- <button
- data-testid="show-create-modal"
- onClick={() =>
- showOAuthCreateModal({
- id: 'test-builder',
- name: 'test',
- provider: 'test-provider',
- credential_type: TriggerCredentialType.Oauth2,
- credentials: {},
- endpoint: 'https://test.com',
- parameters: {},
- properties: {},
- workflows_in_use: 0,
- })
- }
- >
- Show Create Modal
- </button>
+ }) =>
+ open ? (
+ <div role="dialog" aria-label="OAuth client settings">
+ <button onClick={() => onOpenChange(false)}>Close OAuth settings</button>
</div>
- )
- },
+ ) : null,
}))
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
-
- const SelectContext = React.createContext<{
- onOpenChange?: (open: boolean) => void
- onValueChange?: (value: string) => void
- }>({})
-
- const countOptions = (children: React.ReactNode): number => {
- return React.Children.toArray(children).reduce<number>((count, child) => {
- if (!React.isValidElement<{ children?: React.ReactNode }>(child)) return count
-
- return (
- count +
- React.Children.toArray(child.props.children).filter((nestedChild) => {
- return (
- React.isValidElement<{ value?: string }>(nestedChild) && 'value' in nestedChild.props
- )
- }).length
- )
- }, 0)
- }
-
- return {
- Select: ({
- children,
- value,
- open,
- onOpenChange,
- onValueChange,
- }: {
- children: React.ReactNode
- value: string | null
- open?: boolean
- onOpenChange?: (open: boolean) => void
- onValueChange?: (value: string) => void
- }) => {
- const currentValue = value ?? DEFAULT_METHOD
- const optionsCount = countOptions(children)
- const containerOpen =
- currentValue === DEFAULT_METHOD ||
- (currentValue === SupportedCreationMethods.OAUTH && optionsCount === 1)
- ? undefined
- : String(open ?? false)
-
- return (
- <SelectContext.Provider value={{ onOpenChange, onValueChange }}>
- <div
- data-testid="custom-select"
- data-value={currentValue}
- data-open={String(open ?? false)}
- data-options-count={optionsCount}
- data-container-open={containerOpen}
- >
- {children}
- </div>
- </SelectContext.Provider>
- )
- },
- SelectTrigger: ({
- children,
- className,
- }: {
- children: React.ReactNode
- render?: React.ReactNode
- className?: string
- }) => {
- const context = React.useContext(SelectContext)
- return (
- <div
- data-testid="custom-trigger"
- role="button"
- aria-label="custom trigger"
- tabIndex={0}
- className={className}
- onClick={() => context.onOpenChange?.(true)}
- onKeyDown={(event) => {
- if (event.key === 'Enter' || event.key === ' ') context.onOpenChange?.(true)
- }}
- >
- {children}
- </div>
- )
- },
- SelectContent: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="options-container">{children}</div>
- ),
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <div
- data-testid={`option-${value}`}
- role="button"
- aria-label={`option ${value}`}
- tabIndex={0}
- onClick={() => context.onValueChange?.(value)}
- onKeyDown={(event) => {
- if (event.key === 'Enter' || event.key === ' ') context.onValueChange?.(value)
- }}
- >
- {children}
- </div>
- )
- },
- SelectItemText: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SelectItemIndicator: () => null,
- }
-})
-
-const createProviderInfo = (
- overrides: Partial<TriggerProviderApiEntity> = {},
-): TriggerProviderApiEntity => ({
- author: 'test-author',
- name: 'test-provider',
- label: { en_US: 'Test Provider', zh_Hans: 'Test Provider' },
- description: { en_US: 'Test Description', zh_Hans: 'Test Description' },
- icon: 'test-icon',
- tags: [],
- plugin_unique_identifier: 'test-plugin',
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- subscription_schema: [],
- events: [],
- ...overrides,
-})
-
-const createOAuthConfig = (overrides: Partial<TriggerOAuthConfig> = {}): TriggerOAuthConfig => ({
- configured: false,
- custom_configured: false,
- custom_enabled: false,
- redirect_uri: 'https://test.com/callback',
- oauth_client_schema: [],
- params: {
- client_id: '',
- client_secret: '',
- },
- system_configured: false,
- ...overrides,
-})
-
-const createStoreDetail = (overrides: Partial<SimpleDetail> = {}): SimpleDetail => ({
- plugin_id: 'test-plugin',
- name: 'Test Plugin',
- plugin_unique_identifier: 'test-plugin-unique',
- id: 'test-id',
- provider: 'test-provider',
- declaration: {},
- ...overrides,
-})
-
-const createSubscription = (overrides: Partial<TriggerSubscription> = {}): TriggerSubscription => ({
- id: 'test-subscription',
- name: 'Test Subscription',
- provider: 'test-provider',
- credential_type: TriggerCredentialType.ApiKey,
- credentials: {},
- endpoint: 'https://test.com',
- parameters: {},
- properties: {},
- workflows_in_use: 0,
- ...overrides,
-})
-
-const createDefaultProps = (
- overrides: Partial<Parameters<typeof CreateSubscriptionButton>[0]> = {},
-) => ({
- ...overrides,
-})
+const providerInfo = (
+ supported_creation_methods: SupportedCreationMethods[],
+): TriggerProviderApiEntity =>
+ ({
+ name: 'test-provider',
+ supported_creation_methods,
+ }) as TriggerProviderApiEntity
-const getCreateButton = () =>
- screen.getByRole('button', {
- name: /pluginTrigger\.subscription\.(createButton|empty\.button)/,
- })
-
-const setupMocks = (
- config: {
- providerInfo?: TriggerProviderApiEntity
- oauthConfig?: TriggerOAuthConfig
- storeDetail?: SimpleDetail
- subscriptions?: TriggerSubscription[]
- } = {},
-) => {
- mockProviderInfo = { data: config.providerInfo }
- mockOAuthConfig = { data: config.oauthConfig, refetch: vi.fn() }
- mockStoreDetail = config.storeDetail
- mockSubscriptions.length = 0
- if (config.subscriptions) mockSubscriptions.push(...config.subscriptions)
-}
+const oauthConfig = (configured: boolean): TriggerOAuthConfig =>
+ ({ configured, custom_configured: false, custom_enabled: false }) as TriggerOAuthConfig
describe('CreateSubscriptionButton', () => {
beforeEach(() => {
vi.clearAllMocks()
- setupMocks()
+ mockSubscriptions.splice(0)
+ mockProviderInfo = providerInfo([SupportedCreationMethods.MANUAL])
+ mockOAuthConfig = undefined
})
- describe('Rendering', () => {
- it('should render null when supportedMethods is empty', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({ supported_creation_methods: [] }),
- })
- const props = createDefaultProps()
-
- // Act
- const { container } = render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(container)!.toBeEmptyDOMElement()
- })
-
- it('should render full button by default', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(getCreateButton()).toBeInTheDocument()
- })
-
- it('should render icon button when buttonType is ICON_BUTTON', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps({ buttonType: CreateButtonType.ICON_BUTTON })
+ it('does not render without a supported creation method', () => {
+ mockProviderInfo = providerInfo([])
- // Act
- render(<CreateSubscriptionButton {...props} />)
+ const { container } = render(<CreateSubscriptionButton />)
- // Assert
- const actionButton = screen.getByTestId('custom-trigger')
- expect(actionButton)!.toBeInTheDocument()
- })
+ expect(container).toBeEmptyDOMElement()
})
- describe('Props', () => {
- it('should apply default buttonType as FULL_BUTTON', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(getCreateButton()).toBeInTheDocument()
- })
-
- it('should apply shape prop correctly', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps({
- buttonType: CreateButtonType.ICON_BUTTON,
- shape: 'circle',
- })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
- })
-
- describe('State Management', () => {
- it('should show CommonCreateModal when selectedCreateInfo is set', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on MANUAL option to set selectedCreateInfo
- const manualOption = screen.getByTestId(`option-${SupportedCreationMethods.MANUAL}`)
- fireEvent.click(manualOption)
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('common-create-modal'))!.toBeInTheDocument()
- expect(screen.getByTestId('common-create-modal'))!.toHaveAttribute(
- 'data-create-type',
- SupportedCreationMethods.MANUAL,
- )
- })
- })
-
- it('should close CommonCreateModal when onClose is called', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Open modal
- const manualOption = screen.getByTestId(`option-${SupportedCreationMethods.MANUAL}`)
- fireEvent.click(manualOption)
-
- await waitFor(() => {
- expect(screen.getByTestId('common-create-modal'))!.toBeInTheDocument()
- })
-
- // Close modal
- fireEvent.click(screen.getByTestId('close-modal'))
-
- // Assert
- await waitFor(() => {
- expect(screen.queryByTestId('common-create-modal')).not.toBeInTheDocument()
- })
- })
-
- it('should show OAuthClientSettingsModal when oauth settings is clicked', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: false }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on OAuth option (which should show client settings when not configured)
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('oauth-client-modal'))!.toBeInTheDocument()
- })
- })
-
- it('should close dropdown when oauth settings is clicked from option extra action', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.OAUTH,
- SupportedCreationMethods.APIKEY,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- oauthConfig: createOAuthConfig({ configured: false }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- fireEvent.click(screen.getByTestId('custom-trigger'))
- expect(screen.getByTestId('custom-select'))!.toHaveAttribute('data-open', 'true')
-
- fireEvent.click(
- screen.getByRole('button', {
- name: 'pluginTrigger.subscription.addType.options.oauth.clientSettings',
- }),
- )
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('oauth-client-modal'))!.toBeInTheDocument()
- expect(screen.getByTestId('custom-select'))!.toHaveAttribute('data-open', 'false')
- })
- })
-
- it('should close OAuthClientSettingsModal and refetch config when closed', async () => {
- // Arrange
- const mockRefetchOAuth = vi.fn()
- mockOAuthConfig = {
- data: createOAuthConfig({ configured: false }),
- refetch: mockRefetchOAuth,
- }
-
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: false }),
- })
- // Reset after setupMocks to keep our custom refetch
- mockOAuthConfig.refetch = mockRefetchOAuth
-
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Open OAuth modal
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- await waitFor(() => {
- expect(screen.getByTestId('oauth-client-modal'))!.toBeInTheDocument()
- })
-
- // Close modal
- fireEvent.click(screen.getByTestId('close-oauth-modal'))
-
- // Assert
- await waitFor(() => {
- expect(screen.queryByTestId('oauth-client-modal')).not.toBeInTheDocument()
- expect(mockRefetchOAuth).toHaveBeenCalled()
- })
- })
- })
-
- describe('Memoization - buttonTextMap', () => {
- it('should display correct button text for OAUTH method', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
+ it('opens the create modal directly for a single manual method', async () => {
+ const user = userEvent.setup()
+ render(<CreateSubscriptionButton />)
- // Act
- render(<CreateSubscriptionButton {...props} />)
+ await user.click(screen.getByRole('button', { name: /subscription\.createButton\.manual/ }))
- // Assert - OAuth mode renders with settings button, use getAllByRole
- const buttons = screen.getAllByRole('button')
- expect(buttons[0])!.toHaveTextContent('pluginTrigger.subscription.createButton.oauth')
- })
-
- it('should display correct button text for APIKEY method', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.APIKEY],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(getCreateButton()).toHaveTextContent('pluginTrigger.subscription.createButton.apiKey')
- })
-
- it('should display correct button text for MANUAL method', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(getCreateButton()).toHaveTextContent('pluginTrigger.subscription.createButton.manual')
- })
-
- it('should display default button text when multiple methods are supported', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(getCreateButton()).toHaveTextContent('pluginTrigger.subscription.empty.button')
- })
- })
-
- describe('Memoization - allOptions', () => {
- it('should show only OAUTH option when only OAUTH is supported', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig(),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- const customSelect = screen.getByTestId('custom-select')
- expect(customSelect)!.toHaveAttribute('data-options-count', '1')
- })
-
- it('should show all options when all methods are supported', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.OAUTH,
- SupportedCreationMethods.APIKEY,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- oauthConfig: createOAuthConfig(),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- const customSelect = screen.getByTestId('custom-select')
- expect(customSelect)!.toHaveAttribute('data-options-count', '3')
- })
-
- it('should show custom badge when OAuth custom is enabled and configured', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({
- custom_enabled: true,
- custom_configured: true,
- configured: true,
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - Custom badge should appear in the button
- const buttons = screen.getAllByRole('button')
- expect(buttons[0])!.toHaveTextContent('plugin.auth.custom')
- })
-
- it('should not show custom badge when OAuth custom is not configured', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({
- custom_enabled: true,
- custom_configured: false,
- configured: true,
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - The button should be there but no custom badge text
- const buttons = screen.getAllByRole('button')
- expect(buttons[0]).not.toHaveTextContent('plugin.auth.custom')
- })
- })
-
- describe('Memoization - methodType', () => {
- it('should set methodType to DEFAULT_METHOD when multiple methods supported', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- const customSelect = screen.getByTestId('custom-select')
- expect(customSelect)!.toHaveAttribute('data-value', DEFAULT_METHOD)
- })
-
- it('should set methodType to single method when only one supported', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- const customSelect = screen.getByTestId('custom-select')
- expect(customSelect)!.toHaveAttribute('data-value', SupportedCreationMethods.MANUAL)
- })
- })
-
- // ==================== User Interactions ====================
- // Helper to create max subscriptions array
- const createMaxSubscriptions = () =>
- Array.from({ length: 10 }, (_, i) => createSubscription({ id: `sub-${i}` }))
-
- describe('User Interactions - onClickCreate', () => {
- it('should prevent action when subscription count is at max', () => {
- // Arrange
- const maxSubscriptions = createMaxSubscriptions()
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- subscriptions: maxSubscriptions,
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
- const button = getCreateButton()
- fireEvent.click(button)
-
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- // Assert - modal should not open
- expect(screen.queryByTestId('common-create-modal')).not.toBeInTheDocument()
- })
-
- it('should call onChooseCreateType when single method (non-OAuth) is used', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
- const button = getCreateButton()
- fireEvent.click(button)
-
- // Assert - modal should open
- // Assert - modal should open
- expect(screen.getByTestId('common-create-modal'))!.toBeInTheDocument()
- })
-
- it('should not call onChooseCreateType for DEFAULT_METHOD or single OAuth', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
- // For OAuth mode, there are multiple buttons; get the primary button (first one)
- const buttons = screen.getAllByRole('button')
- fireEvent.click(buttons[0]!)
-
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- // Assert - For single OAuth, should not directly create but wait for dropdown
- // The modal should not immediately open
- expect(screen.queryByTestId('common-create-modal')).not.toBeInTheDocument()
- })
- })
-
- describe('User Interactions - onChooseCreateType', () => {
- it('should open OAuth client settings modal when OAuth not configured', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.OAUTH,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- oauthConfig: createOAuthConfig({ configured: false }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on OAuth option
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('oauth-client-modal'))!.toBeInTheDocument()
- })
- })
-
- it('should initiate OAuth flow when OAuth is configured', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.OAUTH,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on OAuth option
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- // Assert
- await waitFor(() => {
- expect(mockInitiateOAuth).toHaveBeenCalledWith('test-provider', expect.any(Object))
- })
- })
-
- it('should set selectedCreateInfo for APIKEY type', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.APIKEY,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on APIKEY option
- const apiKeyOption = screen.getByTestId(`option-${SupportedCreationMethods.APIKEY}`)
- fireEvent.click(apiKeyOption)
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('common-create-modal'))!.toBeInTheDocument()
- expect(screen.getByTestId('common-create-modal'))!.toHaveAttribute(
- 'data-create-type',
- SupportedCreationMethods.APIKEY,
- )
- })
- })
-
- it('should set selectedCreateInfo for MANUAL type', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on MANUAL option
- const manualOption = screen.getByTestId(`option-${SupportedCreationMethods.MANUAL}`)
- fireEvent.click(manualOption)
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('common-create-modal'))!.toBeInTheDocument()
- expect(screen.getByTestId('common-create-modal'))!.toHaveAttribute(
- 'data-create-type',
- SupportedCreationMethods.MANUAL,
- )
- })
- })
- })
-
- describe('User Interactions - onClickClientSettings', () => {
- it('should open OAuth client settings modal when settings icon clicked', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Find the settings div inside the button (p-2 class)
- const buttons = screen.getAllByRole('button')
- const primaryButton = buttons[0]
- const settingsDiv = primaryButton!.querySelector('.p-2')
-
- // Assert that settings div exists and click it
- // Assert that settings div exists and click it
- expect(settingsDiv)!.toBeInTheDocument()
- if (settingsDiv) {
- fireEvent.click(settingsDiv)
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('oauth-client-modal'))!.toBeInTheDocument()
- })
- }
- })
- })
-
- // ==================== API Calls ====================
- describe('API Calls', () => {
- it('should call useTriggerProviderInfo with correct provider', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail({ provider: 'my-provider' }),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - Component renders, which means hook was called
- // Assert - Component renders, which means hook was called
- expect(screen.getByTestId('custom-select'))!.toBeInTheDocument()
- })
-
- it('should handle OAuth initiation success', async () => {
- // Arrange
- const mockBuilder: TriggerSubscriptionBuilder = {
- id: 'oauth-builder',
- name: 'OAuth Builder',
- provider: 'test-provider',
- credential_type: TriggerCredentialType.Oauth2,
- credentials: {},
- endpoint: 'https://test.com',
- parameters: {},
- properties: {},
- workflows_in_use: 0,
- }
-
- type OAuthSuccessResponse = {
- authorization_url: string
- subscription_builder: TriggerSubscriptionBuilder
- }
- type OAuthCallbacks = { onSuccess: (response: OAuthSuccessResponse) => void }
-
- mockInitiateOAuth.mockImplementation((_provider: string, callbacks: OAuthCallbacks) => {
- callbacks.onSuccess({
- authorization_url: 'https://oauth.test.com/authorize',
- subscription_builder: mockBuilder,
- })
- })
-
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.OAUTH,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on OAuth option
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- // Assert - modal should open with OAuth type and builder
- await waitFor(() => {
- expect(screen.getByTestId('common-create-modal'))!.toBeInTheDocument()
- expect(screen.getByTestId('common-create-modal'))!.toHaveAttribute(
- 'data-has-builder',
- 'true',
- )
- })
- })
-
- it('should handle OAuth initiation error', async () => {
- // Arrange
- mockInitiateOAuth.mockImplementation(
- (_provider: string, callbacks: { onError: () => void }) => {
- callbacks.onError()
- },
- )
-
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.OAUTH,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on OAuth option
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- // Assert
- await waitFor(() => {
- expect(toast.error).toHaveBeenCalled()
- })
- })
- })
-
- // ==================== Edge Cases ====================
- describe('Edge Cases', () => {
- it('should handle null subscriptions gracefully', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- subscriptions: undefined,
- })
- const props = createDefaultProps()
-
- // Act
- const { container } = render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- expect(container).not.toBeEmptyDOMElement()
- })
-
- it('should handle undefined provider gracefully', () => {
- // Arrange
- setupMocks({
- storeDetail: undefined,
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - component should still render
- // Assert - component should still render
- expect(screen.getByTestId('custom-select'))!.toBeInTheDocument()
- })
-
- it('should handle empty oauthConfig gracefully', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: undefined,
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('custom-select'))!.toBeInTheDocument()
- })
-
- it('should show max count tooltip when subscriptions reach limit', () => {
- // Arrange
- const maxSubscriptions = Array.from({ length: 10 }, (_, i) =>
- createSubscription({ id: `sub-${i}` }),
- )
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- subscriptions: maxSubscriptions,
- })
- const props = createDefaultProps({ buttonType: CreateButtonType.ICON_BUTTON })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - ActionButton should be in disabled state
- // Assert - ActionButton should be in disabled state
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
-
- it('should handle showOAuthCreateModal callback from OAuthClientSettingsModal', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: false }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Open OAuth modal
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- await waitFor(() => {
- expect(screen.getByTestId('oauth-client-modal'))!.toBeInTheDocument()
- })
-
- // Click show create modal button
- fireEvent.click(screen.getByTestId('show-create-modal'))
-
- // Assert - CommonCreateModal should be shown with OAuth type and builder
- await waitFor(() => {
- expect(screen.getByTestId('common-create-modal'))!.toBeInTheDocument()
- expect(screen.getByTestId('common-create-modal'))!.toHaveAttribute(
- 'data-create-type',
- SupportedCreationMethods.OAUTH,
- )
- expect(screen.getByTestId('common-create-modal'))!.toHaveAttribute(
- 'data-has-builder',
- 'true',
- )
- })
- })
- })
-
- // ==================== Conditional Rendering ====================
- describe('Conditional Rendering', () => {
- it('should render settings icon for OAuth in full button mode', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - settings icon should be present in button, OAuth mode has multiple buttons
- const buttons = screen.getAllByRole('button')
- const primaryButton = buttons[0]
- const settingsDiv = primaryButton!.querySelector('.p-2')
- expect(settingsDiv)!.toBeInTheDocument()
- })
-
- it('should not render settings icon for non-OAuth methods', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - should not have settings divider
- const button = getCreateButton()
- const divider = button.querySelector('.bg-text-primary-on-surface')
- expect(divider).not.toBeInTheDocument()
- })
-
- it('should apply disabled state when subscription count reaches max', () => {
- // Arrange
- const maxSubscriptions = Array.from({ length: 10 }, (_, i) =>
- createSubscription({ id: `sub-${i}` }),
- )
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- subscriptions: maxSubscriptions,
- })
- const props = createDefaultProps({ buttonType: CreateButtonType.ICON_BUTTON })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - icon button should exist
- // Assert - icon button should exist
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
-
- it('should apply circle shape class when shape is circle', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps({
- buttonType: CreateButtonType.ICON_BUTTON,
- shape: 'circle',
- })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
- })
-
- // ==================== CustomSelect containerProps ====================
- describe('CustomSelect containerProps', () => {
- it('should set open to undefined for default method with multiple supported methods', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - open should be undefined to allow dropdown to work
- const customSelect = screen.getByTestId('custom-select')
- expect(customSelect.getAttribute('data-container-open')).toBeNull()
- })
-
- it('should set open to undefined for single OAuth method', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - for single OAuth, open should be undefined
- const customSelect = screen.getByTestId('custom-select')
- expect(customSelect.getAttribute('data-container-open')).toBeNull()
- })
-
- it('should set open to false for single non-OAuth method', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - for single non-OAuth, dropdown should be disabled (open = false)
- const customSelect = screen.getByTestId('custom-select')
- expect(customSelect)!.toHaveAttribute('data-container-open', 'false')
- })
- })
-
- // ==================== Button Type Variations ====================
- describe('Button Type Variations', () => {
- it('should render icon button with float-right class', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- })
- const props = createDefaultProps({ buttonType: CreateButtonType.ICON_BUTTON })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
- })
-
- // ==================== CommonCreateModal Integration Tests ====================
- // These tests verify that CreateSubscriptionButton correctly interacts with CommonCreateModal
- describe('CommonCreateModal Integration', () => {
- it('should pass correct createType to CommonCreateModal for MANUAL', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on MANUAL option
- const manualOption = screen.getByTestId(`option-${SupportedCreationMethods.MANUAL}`)
- fireEvent.click(manualOption)
-
- // Assert
- await waitFor(() => {
- const modal = screen.getByTestId('common-create-modal')
- expect(modal)!.toHaveAttribute('data-create-type', SupportedCreationMethods.MANUAL)
- })
- })
-
- it('should pass correct createType to CommonCreateModal for APIKEY', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on APIKEY option
- const apiKeyOption = screen.getByTestId(`option-${SupportedCreationMethods.APIKEY}`)
- fireEvent.click(apiKeyOption)
-
- // Assert
- await waitFor(() => {
- const modal = screen.getByTestId('common-create-modal')
- expect(modal)!.toHaveAttribute('data-create-type', SupportedCreationMethods.APIKEY)
- })
- })
-
- it('should pass builder to CommonCreateModal for OAuth flow', async () => {
- // Arrange
- const mockBuilder: TriggerSubscriptionBuilder = {
- id: 'oauth-builder',
- name: 'OAuth Builder',
- provider: 'test-provider',
- credential_type: TriggerCredentialType.Oauth2,
- credentials: {},
- endpoint: 'https://test.com',
- parameters: {},
- properties: {},
- workflows_in_use: 0,
- }
-
- type OAuthSuccessResponse = {
- authorization_url: string
- subscription_builder: TriggerSubscriptionBuilder
- }
- type OAuthCallbacks = { onSuccess: (response: OAuthSuccessResponse) => void }
-
- mockInitiateOAuth.mockImplementation((_provider: string, callbacks: OAuthCallbacks) => {
- callbacks.onSuccess({
- authorization_url: 'https://oauth.test.com/authorize',
- subscription_builder: mockBuilder,
- })
- })
-
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.OAUTH,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on OAuth option
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- // Assert
- await waitFor(() => {
- const modal = screen.getByTestId('common-create-modal')
- expect(modal)!.toHaveAttribute('data-has-builder', 'true')
- })
- })
- })
-
- // ==================== OAuthClientSettingsModal Integration Tests ====================
- // These tests verify that CreateSubscriptionButton correctly interacts with OAuthClientSettingsModal
- describe('OAuthClientSettingsModal Integration', () => {
- it('should pass oauthConfig to OAuthClientSettingsModal', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: false }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on OAuth option (opens settings when not configured)
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- // Assert
- await waitFor(() => {
- const modal = screen.getByTestId('oauth-client-modal')
- expect(modal)!.toHaveAttribute('data-has-config', 'true')
- })
- })
-
- it('should refetch OAuth config when OAuthClientSettingsModal is closed', async () => {
- // Arrange
- const mockRefetchOAuth = vi.fn()
- mockOAuthConfig = {
- data: createOAuthConfig({ configured: false }),
- refetch: mockRefetchOAuth,
- }
-
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: false }),
- })
- // Reset after setupMocks to keep our custom refetch
- mockOAuthConfig.refetch = mockRefetchOAuth
-
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Open OAuth modal
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- await waitFor(() => {
- expect(screen.getByTestId('oauth-client-modal'))!.toBeInTheDocument()
- })
-
- // Close modal
- fireEvent.click(screen.getByTestId('close-oauth-modal'))
-
- // Assert
- await waitFor(() => {
- expect(mockRefetchOAuth).toHaveBeenCalled()
- })
- })
-
- it('should show CommonCreateModal with builder when showOAuthCreateModal callback is invoked', async () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.OAUTH],
- }),
- oauthConfig: createOAuthConfig({ configured: false }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Open OAuth modal
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
-
- await waitFor(() => {
- expect(screen.getByTestId('oauth-client-modal'))!.toBeInTheDocument()
- })
-
- // Click showOAuthCreateModal button
- fireEvent.click(screen.getByTestId('show-create-modal'))
-
- // Assert - CommonCreateModal should appear with OAuth type and builder
- await waitFor(() => {
- expect(screen.getByTestId('common-create-modal'))!.toBeInTheDocument()
- expect(screen.getByTestId('common-create-modal'))!.toHaveAttribute(
- 'data-create-type',
- SupportedCreationMethods.OAUTH,
- )
- expect(screen.getByTestId('common-create-modal'))!.toHaveAttribute(
- 'data-has-builder',
- 'true',
- )
- })
- })
+ expect(await screen.findByRole('dialog')).toHaveAttribute(
+ 'data-create-type',
+ SupportedCreationMethods.MANUAL,
+ )
})
- // ==================== OAuth Callback Edge Cases ====================
- describe('OAuth Callback - Falsy Data', () => {
- it('should not open modal when OAuth callback returns falsy data', async () => {
- // Arrange
- const { openOAuthPopup } = await import('@/hooks/use-oauth')
- vi.mocked(openOAuthPopup).mockImplementation(
- (url: string, callback: (data?: unknown) => void) => {
- callback(undefined) // falsy callback data
- return null
- },
- )
-
- const mockBuilder: TriggerSubscriptionBuilder = {
- id: 'oauth-builder',
- name: 'OAuth Builder',
- provider: 'test-provider',
- credential_type: TriggerCredentialType.Oauth2,
- credentials: {},
- endpoint: 'https://test.com',
- parameters: {},
- properties: {},
- workflows_in_use: 0,
- }
-
- mockInitiateOAuth.mockImplementation(
- (
- _provider: string,
- callbacks: {
- onSuccess: (response: {
- authorization_url: string
- subscription_builder: TriggerSubscriptionBuilder
- }) => void
- },
- ) => {
- callbacks.onSuccess({
- authorization_url: 'https://oauth.test.com/authorize',
- subscription_builder: mockBuilder,
- })
- },
- )
-
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.OAUTH,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- oauthConfig: createOAuthConfig({ configured: true }),
- })
- const props = createDefaultProps()
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Click on OAuth option
- const oauthOption = screen.getByTestId(`option-${SupportedCreationMethods.OAUTH}`)
- fireEvent.click(oauthOption)
+ it('uses the real select to choose among multiple methods', async () => {
+ const user = userEvent.setup()
+ mockProviderInfo = providerInfo([
+ SupportedCreationMethods.MANUAL,
+ SupportedCreationMethods.APIKEY,
+ ])
+ render(<CreateSubscriptionButton />)
+
+ await user.click(screen.getByRole('button', { name: /subscription\.empty\.button/ }))
+ const listbox = await screen.findByRole('listbox')
+ await user.click(
+ within(listbox).getByRole('option', {
+ name: /subscription\.addType\.options\.apikey\.title/,
+ }),
+ )
- // Assert - modal should NOT open because callback data was falsy
- await waitFor(() => {
- expect(screen.queryByTestId('common-create-modal')).not.toBeInTheDocument()
- })
- })
+ expect(await screen.findByRole('dialog')).toHaveAttribute(
+ 'data-create-type',
+ SupportedCreationMethods.APIKEY,
+ )
})
- // ==================== TriggerProps ClassName Branches ====================
- describe('TriggerProps ClassName Branches', () => {
- it('should apply pointer-events-none when non-default method with multiple supported methods', () => {
- // Arrange - Single APIKEY method (methodType = APIKEY, not DEFAULT_METHOD)
- // But we need multiple methods to test this branch
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.APIKEY,
- SupportedCreationMethods.MANUAL,
- ],
- }),
- })
- const props = createDefaultProps()
+ it('opens OAuth settings when OAuth is not configured', async () => {
+ const user = userEvent.setup()
+ mockProviderInfo = providerInfo([SupportedCreationMethods.OAUTH])
+ mockOAuthConfig = oauthConfig(false)
+ render(<CreateSubscriptionButton />)
- // Act
- render(<CreateSubscriptionButton {...props} />)
+ await user.click(screen.getByRole('button', { name: /subscription\.createButton\.oauth/ }))
+ const listbox = await screen.findByRole('listbox')
+ await user.click(
+ within(listbox).getByRole('option', {
+ name: /subscription\.addType\.options\.oauth\.title/,
+ }),
+ )
- // The methodType will be DEFAULT_METHOD since multiple methods
- // This verifies the render doesn't crash with multiple methods
- // The methodType will be DEFAULT_METHOD since multiple methods
- // This verifies the render doesn't crash with multiple methods
- expect(screen.getByTestId('custom-select'))!.toHaveAttribute('data-value', 'default')
- })
+ expect(await screen.findByRole('dialog', { name: 'OAuth client settings' })).toBeInTheDocument()
})
- // ==================== Tooltip Disabled Branches ====================
- describe('Tooltip Disabled Branches', () => {
- it('should enable tooltip when single method and not at max count', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- subscriptions: [createSubscription()], // Not at max
- })
- const props = createDefaultProps({ buttonType: CreateButtonType.ICON_BUTTON })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - tooltip should be enabled (disabled prop = false for single method)
- // Assert - tooltip should be enabled (disabled prop = false for single method)
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
+ it('refetches OAuth configuration when settings close', async () => {
+ const user = userEvent.setup()
+ mockProviderInfo = providerInfo([SupportedCreationMethods.OAUTH])
+ mockOAuthConfig = oauthConfig(false)
+ render(<CreateSubscriptionButton />)
- it('should disable tooltip when multiple methods and not at max count', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [
- SupportedCreationMethods.MANUAL,
- SupportedCreationMethods.APIKEY,
- ],
- }),
- subscriptions: [createSubscription()], // Not at max
- })
- const props = createDefaultProps({ buttonType: CreateButtonType.ICON_BUTTON })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
+ await user.click(screen.getByRole('button', { name: /subscription\.createButton\.oauth/ }))
+ await user.click(
+ screen.getByLabelText('pluginTrigger.subscription.addType.options.oauth.clientSettings'),
+ )
+ await user.click(await screen.findByRole('button', { name: 'Close OAuth settings' }))
- // Assert - tooltip should be disabled (neither single method nor at max)
- // Assert - tooltip should be disabled (neither single method nor at max)
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
+ expect(mockRefetchOAuthConfig).toHaveBeenCalledTimes(1)
})
- // ==================== Tooltip PopupContent Branches ====================
- describe('Tooltip PopupContent Branches', () => {
- it('should show max count message when at max subscriptions', () => {
- // Arrange
- const maxSubscriptions = createMaxSubscriptions()
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
- }),
- subscriptions: maxSubscriptions,
- })
- const props = createDefaultProps({ buttonType: CreateButtonType.ICON_BUTTON })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - component renders with max subscriptions
- // Assert - component renders with max subscriptions
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
-
- it('should show method description when not at max', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.MANUAL],
+ it('continues configured OAuth into the create modal', async () => {
+ const user = userEvent.setup()
+ mockProviderInfo = providerInfo([SupportedCreationMethods.OAUTH])
+ mockOAuthConfig = oauthConfig(true)
+ mockInitiateOAuth.mockImplementationOnce(
+ (_provider: string, { onSuccess }: { onSuccess: (response: unknown) => void }) =>
+ onSuccess({
+ authorization_url: 'https://example.com/oauth',
+ subscription_builder: { id: 'builder-1' },
}),
- subscriptions: [], // Not at max
- })
- const props = createDefaultProps({ buttonType: CreateButtonType.ICON_BUTTON })
-
- // Act
- render(<CreateSubscriptionButton {...props} />)
-
- // Assert - component renders without max subscriptions
- // Assert - component renders without max subscriptions
- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()
- })
- })
-
- // ==================== Provider Info Fallbacks ====================
- describe('Provider Info Fallbacks', () => {
- it('should handle undefined supported_creation_methods', () => {
- // Arrange - providerInfo with undefined supported_creation_methods
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: {
- ...createProviderInfo(),
- supported_creation_methods: undefined as unknown as SupportedCreationMethods[],
- },
- })
- const props = createDefaultProps()
-
- // Act
- const { container } = render(<CreateSubscriptionButton {...props} />)
-
- // Assert - should render null when supported methods fallback to empty
- // Assert - should render null when supported methods fallback to empty
- expect(container)!.toBeEmptyDOMElement()
- })
-
- it('should handle providerInfo with null supported_creation_methods', () => {
- // Arrange
- mockProviderInfo = {
- data: {
- ...createProviderInfo(),
- supported_creation_methods: null as unknown as SupportedCreationMethods[],
- },
- }
- mockOAuthConfig = { data: undefined, refetch: vi.fn() }
- mockStoreDetail = createStoreDetail()
- const props = createDefaultProps()
+ )
+ mockOpenOAuthPopup.mockImplementationOnce((_url: string, callback: (data: unknown) => void) =>
+ callback({ success: true }),
+ )
+ render(<CreateSubscriptionButton />)
- // Act
- const { container } = render(<CreateSubscriptionButton {...props} />)
+ await user.click(screen.getByRole('button', { name: /subscription\.createButton\.oauth/ }))
+ await user.click(
+ within(await screen.findByRole('listbox')).getByRole('option', {
+ name: /subscription\.addType\.options\.oauth\.title/,
+ }),
+ )
- // Assert - should render null
- // Assert - should render null
- expect(container)!.toBeEmptyDOMElement()
- })
+ expect(await screen.findByRole('dialog')).toHaveAttribute('data-builder-id', 'builder-1')
+ expect(toastMocks.success).toHaveBeenCalledTimes(1)
})
- // ==================== Method Type Logic ====================
- describe('Method Type Logic', () => {
- it('should use single method as methodType when only one supported', () => {
- // Arrange
- setupMocks({
- storeDetail: createStoreDetail(),
- providerInfo: createProviderInfo({
- supported_creation_methods: [SupportedCreationMethods.APIKEY],
- }),
- })
- const props = createDefaultProps()
+ it('does not create more than ten subscriptions', async () => {
+ mockSubscriptions.push(
+ ...Array.from({ length: 10 }, (_, index) => ({ id: `${index}` }) as TriggerSubscription),
+ )
+ render(<CreateSubscriptionButton />)
- // Act
- render(<CreateSubscriptionButton {...props} />)
+ fireEvent.click(screen.getByRole('button', { name: /subscription\.createButton\.manual/ }))
- // Assert
- const customSelect = screen.getByTestId('custom-select')
- expect(customSelect)!.toHaveAttribute('data-value', SupportedCreationMethods.APIKEY)
- })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx
index df7f319816f..a8d1441a32c 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx
@@ -2,66 +2,13 @@ import type { ReactNode } from 'react'
import type { AppSelectorValue } from '@/app/components/plugins/plugin-detail-panel/app-selector'
import type { ToolFormSchema } from '@/app/components/tools/utils/to-form-schema'
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { Type } from '@/app/components/workflow/nodes/llm/types'
import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
import ReasoningConfigForm from '../reasoning-config-form'
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
- const SelectContext = React.createContext<{
- onValueChange?: (value: string) => void
- }>({})
-
- return {
- Select: ({
- children,
- onValueChange,
- }: {
- children: React.ReactNode
- onValueChange?: (value: string) => void
- }) => (
- <SelectContext value={{ onValueChange }}>
- <div>{children}</div>
- </SelectContext>
- ),
- SelectTrigger: ({ children }: { children: React.ReactNode }) => (
- <button type="button">{children}</button>
- ),
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const context = React.use(SelectContext)
- return (
- <button
- key={value}
- data-testid={`select-${value}`}
- type="button"
- onClick={() => context.onValueChange?.(value)}
- >
- {children}
- </button>
- )
- },
- SelectItemText: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SelectItemIndicator: () => null,
- }
-})
-
-vi.mock('@langgenius/dify-ui/switch', () => ({
- Switch: ({
- checked,
- onCheckedChange,
- }: {
- checked: boolean
- onCheckedChange: (checked: boolean) => void
- }) => (
- <button data-testid="auto-switch" onClick={() => onCheckedChange(!checked)}>
- {checked ? 'on' : 'off'}
- </button>
- ),
-}))
-
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
useLanguage: () => 'en_US',
}))
@@ -211,7 +158,7 @@ describe('ReasoningConfigForm', () => {
/>,
)
- fireEvent.click(screen.getByTestId('auto-switch'))
+ fireEvent.click(screen.getByRole('switch'))
expect(onChange).toHaveBeenCalledWith({
field: {
@@ -407,7 +354,8 @@ describe('ReasoningConfigForm', () => {
})
})
- it('should update number, boolean, and select fields', () => {
+ it('should update number, boolean, and select fields', async () => {
+ const user = userEvent.setup()
const onChange = vi.fn()
render(
@@ -469,7 +417,8 @@ describe('ReasoningConfigForm', () => {
fireEvent.change(screen.getByRole('spinbutton'), { target: { value: '7' } })
fireEvent.click(screen.getByTestId('boolean-input'))
- fireEvent.click(screen.getByTestId('select-beta'))
+ await user.click(screen.getByRole('combobox'))
+ await user.click(await screen.findByRole('option', { name: 'Beta' }))
expect(onChange).toHaveBeenNthCalledWith(
1,
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/schema-modal.spec.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/schema-modal.spec.tsx
index 95878edadda..428f0cfb352 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/schema-modal.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/schema-modal.spec.tsx
@@ -2,15 +2,6 @@ import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { SchemaModal } from '../schema-modal'
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, open }: { children: React.ReactNode; open?: boolean }) =>
- open === false ? null : <>{children}</>,
- DialogContent: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="modal">{children}</div>
- ),
- DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
vi.mock(
'@/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor',
() => ({
diff --git a/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx b/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
index 1d1da23f212..382b7495453 100644
--- a/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
+++ b/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
@@ -1,5 +1,6 @@
import type { MetaData, PluginCategoryEnum } from '../../types'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { expectLoadingButton } from '@/test/button'
// ==================== Imports (after mocks) ====================
@@ -94,8 +95,6 @@ vi.mock('../../plugin-page/plugin-info', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/tooltip', () => import('@/__mocks__/base-ui-tooltip'))
-
// ==================== Test Utilities ====================
type ActionProps = {
@@ -229,7 +228,8 @@ describe('Action Component', () => {
expect(queryActionButtons()).toHaveLength(0)
})
- it('should render tooltips for each button', () => {
+ it('should render tooltips for each button', async () => {
+ const user = userEvent.setup()
// Arrange
const props = createActionProps({
isShowFetchNewVersion: true,
@@ -242,16 +242,16 @@ describe('Action Component', () => {
// Assert
const buttons = getActionButtons()
- fireEvent.mouseEnter(buttons[0]!)
- expect(screen.getByText('plugin.action.checkForUpdates'))!.toBeInTheDocument()
- fireEvent.mouseLeave(buttons[0]!)
+ await user.hover(buttons[0]!)
+ expect(await screen.findByText('plugin.action.checkForUpdates'))!.toBeInTheDocument()
+ await user.unhover(buttons[0]!)
- fireEvent.mouseEnter(buttons[1]!)
- expect(screen.getByText('plugin.action.pluginInfo'))!.toBeInTheDocument()
- fireEvent.mouseLeave(buttons[1]!)
+ await user.hover(buttons[1]!)
+ expect(await screen.findByText('plugin.action.pluginInfo'))!.toBeInTheDocument()
+ await user.unhover(buttons[1]!)
- fireEvent.mouseEnter(buttons[2]!)
- expect(screen.getByText('plugin.action.delete'))!.toBeInTheDocument()
+ await user.hover(buttons[2]!)
+ expect(await screen.findByText('plugin.action.delete'))!.toBeInTheDocument()
})
})
diff --git a/web/app/components/plugins/plugin-page/__tests__/install-plugin-dropdown.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/install-plugin-dropdown.spec.tsx
index 6707d385661..feef5372391 100644
--- a/web/app/components/plugins/plugin-page/__tests__/install-plugin-dropdown.spec.tsx
+++ b/web/app/components/plugins/plugin-page/__tests__/install-plugin-dropdown.spec.tsx
@@ -45,149 +45,6 @@ vi.mock('@remixicon/react', () => ({
),
}))
-type MockButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
- variant?: string
-}
-
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children, onClick, className, variant, ...props }: MockButtonProps) => (
- <button
- type="button"
- data-testid="button-content"
- data-variant={variant}
- className={className}
- onClick={onClick}
- {...props}
- >
- {children}
- </button>
- ),
-}))
-
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- isOpen: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- open,
- onOpenChange,
- modal,
- children,
- }: {
- open?: boolean
- onOpenChange?: (open: boolean) => void
- modal?: boolean
- children: React.ReactNode
- }) => {
- const [internalOpen, setInternalOpen] = React.useState(open ?? false)
- const isOpen = open ?? internalOpen
- const setOpen = (nextOpen: boolean) => {
- if (open === undefined) setInternalOpen(nextOpen)
- onOpenChange?.(nextOpen)
- }
-
- return (
- <DropdownMenuContext value={{ isOpen, setOpen }}>
- <div data-testid="dropdown-menu" data-open={isOpen} data-modal={modal}>
- {children}
- </div>
- </DropdownMenuContext>
- )
- },
- DropdownMenuTrigger: ({
- children,
- onClick,
- render,
- }: {
- children?: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLElement>
- render?:
- | React.ReactElement
- | ((
- props: React.HTMLAttributes<HTMLElement> & {
- 'data-testid'?: string
- 'data-popup-open'?: string
- },
- state: { open: boolean },
- ) => React.ReactElement)
- }) => {
- const { isOpen, setOpen } = useDropdownMenuContext()
- const handleClick = (e: React.MouseEvent<HTMLElement>) => {
- onClick?.(e)
- setOpen(!isOpen)
- }
-
- if (typeof render === 'function')
- return render(
- {
- 'data-testid': 'dropdown-trigger',
- 'data-popup-open': isOpen ? '' : undefined,
- onClick: handleClick,
- },
- { open: isOpen },
- )
-
- if (render)
- return React.cloneElement(
- render,
- { 'data-testid': 'dropdown-trigger', onClick: handleClick } as Record<string, unknown>,
- children,
- )
-
- return (
- <button data-testid="dropdown-trigger" onClick={handleClick}>
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({
- children,
- popupClassName,
- }: {
- children: React.ReactNode
- popupClassName?: string
- }) => {
- const { isOpen } = useDropdownMenuContext()
- return isOpen ? (
- <div data-testid="dropdown-content" className={popupClassName}>
- {children}
- </div>
- ) : null
- },
- DropdownMenuItem: ({
- children,
- onClick,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- data-testid="dropdown-item"
- onClick={(e) => {
- onClick?.(e)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- }
-})
-
vi.mock('@/app/components/plugins/install-plugin/install-from-github', () => ({
default: ({ onClose }: { onClose: () => void }) => (
<div data-testid="github-modal">
@@ -209,6 +66,8 @@ vi.mock('@/app/components/plugins/install-plugin/install-from-local-package', ()
),
}))
+const getTrigger = (name = 'plugin.installPlugin') => screen.getByRole('button', { name })
+
describe('InstallPluginDropdown', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -217,24 +76,23 @@ describe('InstallPluginDropdown', () => {
})
it('shows all install methods when marketplace and custom installs are enabled', () => {
- const { container } = render(<InstallPluginDropdown onSwitchToMarketplaceTab={vi.fn()} />)
+ render(<InstallPluginDropdown onSwitchToMarketplaceTab={vi.fn()} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(getTrigger())
- expect(screen.getByTestId('dropdown-menu')).toHaveAttribute('data-modal', 'false')
expect(screen.getByText('plugin.installFrom')).toBeInTheDocument()
expect(screen.getByText('plugin.source.marketplace')).toBeInTheDocument()
expect(screen.getByText('plugin.source.github')).toBeInTheDocument()
expect(screen.getByText('plugin.source.local')).toBeInTheDocument()
- expect(container.querySelector('.i-custom-vender-plugin-box-sparkle-fill')).toHaveClass(
+ expect(document.querySelector('.i-custom-vender-plugin-box-sparkle-fill')).toHaveClass(
'size-4',
'shrink-0',
)
- expect(container.querySelector('.i-custom-vender-solid-general-github')).toHaveClass(
+ expect(document.querySelector('.i-custom-vender-solid-general-github')).toHaveClass(
'size-4',
'shrink-0',
)
- expect(container.querySelector('.i-custom-vender-solid-files-file-zip')).toHaveClass(
+ expect(document.querySelector('.i-custom-vender-solid-files-file-zip')).toHaveClass(
'size-4',
'shrink-0',
)
@@ -253,21 +111,20 @@ describe('InstallPluginDropdown', () => {
/>,
)
- const trigger = screen.getByTestId('dropdown-trigger')
+ const trigger = getTrigger('Install')
expect(container.querySelector('.custom-root')).toBeInTheDocument()
expect(trigger).toHaveTextContent('Install')
expect(screen.getByTestId('add-circle-fill-icon')).toHaveClass('size-4', 'shrink-0')
expect(screen.getByTestId('arrow-down-icon')).toHaveClass('ml-1', 'size-4')
expect(trigger).toHaveClass('custom-trigger')
- expect(trigger).toHaveAttribute('data-variant', 'primary')
expect(trigger).not.toHaveAttribute('data-popup-open')
fireEvent.click(trigger)
expect(trigger).toHaveClass('custom-open')
expect(trigger).toHaveAttribute('data-popup-open', '')
- expect(screen.getByTestId('dropdown-content')).toHaveClass('custom-popup')
+ expect(screen.getByRole('menu')).toHaveClass('custom-popup')
})
it('can hide the trigger arrow for compact integrations placement', () => {
@@ -279,7 +136,7 @@ describe('InstallPluginDropdown', () => {
/>,
)
- const trigger = screen.getByTestId('dropdown-trigger')
+ const trigger = getTrigger('Install')
expect(trigger).toHaveTextContent('Install')
expect(screen.getByTestId('add-circle-fill-icon')).toHaveClass('size-4', 'shrink-0')
@@ -293,7 +150,7 @@ describe('InstallPluginDropdown', () => {
<InstallPluginDropdown disabled onSwitchToMarketplaceTab={onSwitchToMarketplaceTab} />,
)
- const trigger = screen.getByTestId('dropdown-trigger')
+ const trigger = getTrigger()
expect(trigger).toBeDisabled()
@@ -304,7 +161,7 @@ describe('InstallPluginDropdown', () => {
},
})
- expect(screen.queryByTestId('dropdown-content')).not.toBeInTheDocument()
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
expect(screen.queryByTestId('local-modal')).not.toBeInTheDocument()
expect(onSwitchToMarketplaceTab).not.toHaveBeenCalled()
})
@@ -314,7 +171,7 @@ describe('InstallPluginDropdown', () => {
render(<InstallPluginDropdown onSwitchToMarketplaceTab={vi.fn()} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(getTrigger())
expect(screen.getByText('plugin.source.marketplace')).toBeInTheDocument()
expect(screen.queryByText('plugin.source.github')).not.toBeInTheDocument()
@@ -325,7 +182,7 @@ describe('InstallPluginDropdown', () => {
const onSwitchToMarketplaceTab = vi.fn()
render(<InstallPluginDropdown onSwitchToMarketplaceTab={onSwitchToMarketplaceTab} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getByText('plugin.source.marketplace'))
expect(onSwitchToMarketplaceTab).toHaveBeenCalledTimes(1)
@@ -334,7 +191,7 @@ describe('InstallPluginDropdown', () => {
it('opens the github installer when github is selected', async () => {
render(<InstallPluginDropdown onSwitchToMarketplaceTab={vi.fn()} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getByText('plugin.source.github'))
expect(await screen.findByTestId('github-modal')).toBeInTheDocument()
@@ -343,7 +200,7 @@ describe('InstallPluginDropdown', () => {
it('opens the local package installer when a file is selected', () => {
const { container } = render(<InstallPluginDropdown onSwitchToMarketplaceTab={vi.fn()} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getByText('plugin.source.local'))
fireEvent.change(container.querySelector('input[type="file"]')!, {
target: {
@@ -360,7 +217,7 @@ describe('InstallPluginDropdown', () => {
render(<InstallPluginDropdown onSwitchToMarketplaceTab={vi.fn()} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getByText('plugin.source.local'))
expect(clickSpy).toHaveBeenCalledTimes(1)
@@ -370,7 +227,7 @@ describe('InstallPluginDropdown', () => {
it('closes the github installer when the modal requests close', async () => {
render(<InstallPluginDropdown onSwitchToMarketplaceTab={vi.fn()} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getByText('plugin.source.github'))
fireEvent.click(await screen.findByTestId('close-github-modal'))
@@ -380,7 +237,7 @@ describe('InstallPluginDropdown', () => {
it('closes the local package installer when the modal requests close', () => {
const { container } = render(<InstallPluginDropdown onSwitchToMarketplaceTab={vi.fn()} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(getTrigger())
fireEvent.click(screen.getByText('plugin.source.local'))
fireEvent.change(container.querySelector('input[type="file"]')!, {
target: {
diff --git a/web/app/components/plugins/plugin-page/filter-management/__tests__/category-filter.spec.tsx b/web/app/components/plugins/plugin-page/filter-management/__tests__/category-filter.spec.tsx
index 0b369931faa..59c404ac046 100644
--- a/web/app/components/plugins/plugin-page/filter-management/__tests__/category-filter.spec.tsx
+++ b/web/app/components/plugins/plugin-page/filter-management/__tests__/category-filter.spec.tsx
@@ -2,8 +2,6 @@ import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
vi.mock('@langgenius/dify-ui/cn', () => ({
cn: (...args: unknown[]) => args.filter(Boolean).join(' '),
}))
@@ -57,7 +55,7 @@ describe('CategoriesFilter', () => {
const mockOnChange = vi.fn()
render(<CategoriesFilter value={['tool']} onChange={mockOnChange} />)
- const trigger = screen.getByTestId('popover-trigger')
+ const trigger = screen.getByRole('button', { name: /Tool/ })
const clearSvg = trigger.querySelector('svg')
fireEvent.click(clearSvg!)
expect(mockOnChange).toHaveBeenCalledWith([])
@@ -65,7 +63,7 @@ describe('CategoriesFilter', () => {
it('should render category options in dropdown', () => {
render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
- fireEvent.click(screen.getByTestId('popover-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'plugin.allCategories' }))
expect(screen.getByText('Tool'))!.toBeInTheDocument()
expect(screen.getByText('Model'))!.toBeInTheDocument()
@@ -76,7 +74,7 @@ describe('CategoriesFilter', () => {
const mockOnChange = vi.fn()
render(<CategoriesFilter value={[]} onChange={mockOnChange} />)
- fireEvent.click(screen.getByTestId('popover-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'plugin.allCategories' }))
fireEvent.click(screen.getByText('Tool'))
expect(mockOnChange).toHaveBeenCalledWith(['tool'])
})
@@ -85,7 +83,7 @@ describe('CategoriesFilter', () => {
const mockOnChange = vi.fn()
render(<CategoriesFilter value={['tool']} onChange={mockOnChange} />)
- fireEvent.click(screen.getByTestId('popover-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: /Tool/ }))
const toolElements = screen.getAllByText('Tool')
fireEvent.click(toolElements[toolElements.length - 1]!)
expect(mockOnChange).toHaveBeenCalledWith([])
@@ -94,7 +92,7 @@ describe('CategoriesFilter', () => {
it('should filter categories by search text', () => {
render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
- fireEvent.click(screen.getByTestId('popover-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'plugin.allCategories' }))
fireEvent.change(screen.getByPlaceholderText('plugin.searchCategories'), {
target: { value: 'mod' },
})
diff --git a/web/app/components/plugins/plugin-page/filter-management/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-page/filter-management/__tests__/index.spec.tsx
index 8483db4af0c..6143709bd67 100644
--- a/web/app/components/plugins/plugin-page/filter-management/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-page/filter-management/__tests__/index.spec.tsx
@@ -1,1006 +1,70 @@
import type { FilterState } from '../index'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { createContext, useContext } from 'react'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-// ==================== Imports (after mocks) ====================
-import CategoriesFilter from '../category-filter'
-// Import real components
+import { fireEvent, render, screen } from '@testing-library/react'
import FilterManagement from '../index'
-import SearchBox from '../search-box'
-import TagFilter from '../tag-filter'
-// ==================== Mock Setup ====================
-
-// Mock initial filters from context
-let mockInitFilters: FilterState = {
+let initialFilters: FilterState = {
categories: [],
tags: [],
searchQuery: '',
}
vi.mock('../../context', () => ({
- usePluginPageContext: (selector: (v: { filters: FilterState }) => FilterState) =>
- selector({ filters: mockInitFilters }),
+ usePluginPageContext: (selector: (state: { filters: FilterState }) => unknown) =>
+ selector({ filters: initialFilters }),
}))
-// Mock categories data
-const mockCategories = [
- { name: 'model', label: 'Models' },
- { name: 'tool', label: 'Tools' },
- { name: 'extension', label: 'Extensions' },
- { name: 'agent', label: 'Agents' },
-]
-
-const mockCategoriesMap: Record<string, { name: string; label: string }> = {
- model: { name: 'model', label: 'Models' },
- tool: { name: 'tool', label: 'Tools' },
- extension: { name: 'extension', label: 'Extensions' },
- agent: { name: 'agent', label: 'Agents' },
-}
-
-// Mock tags data
-const mockTags = [
- { name: 'agent', label: 'Agent' },
- { name: 'rag', label: 'RAG' },
- { name: 'search', label: 'Search' },
- { name: 'image', label: 'Image' },
-]
-
-const mockTagsMap: Record<string, { name: string; label: string }> = {
- agent: { name: 'agent', label: 'Agent' },
- rag: { name: 'rag', label: 'RAG' },
- search: { name: 'search', label: 'Search' },
- image: { name: 'image', label: 'Image' },
-}
-
vi.mock('../../../hooks', () => ({
useCategories: () => ({
- categories: mockCategories,
- categoriesMap: mockCategoriesMap,
+ categories: [{ name: 'model', label: 'Models' }],
+ categoriesMap: { model: { name: 'model', label: 'Models' } },
}),
useTags: () => ({
- tags: mockTags,
- tagsMap: mockTagsMap,
- getTagLabel: (name: string) => mockTagsMap[name]?.label || name,
+ tags: [{ name: 'agent', label: 'Agent' }],
+ getTagLabel: (name: string) => ({ agent: 'Agent' })[name] ?? name,
}),
}))
-type MockPopoverContextValue = {
- open: boolean
- onOpenChange?: (open: boolean) => void
-}
-
-const MockPopoverContext = createContext<MockPopoverContextValue>({
- open: false,
-})
-
-vi.mock('@langgenius/dify-ui/popover', () => ({
- Popover: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <MockPopoverContext.Provider value={{ open, onOpenChange }}>
- <div data-testid="portal-container" data-open={open}>
- {children}
- </div>
- </MockPopoverContext.Provider>
- ),
- PopoverTrigger: ({
- children,
- render,
- className,
- }: {
- children?: React.ReactNode
- render?: React.ReactNode
- className?: string
- }) => {
- const { open, onOpenChange } = useContext(MockPopoverContext)
- return (
- <button
- type="button"
- data-testid="portal-trigger"
- onClick={() => onOpenChange?.(!open)}
- className={className}
- >
- {render ?? children}
- </button>
- )
- },
- PopoverContent: ({ children, className }: { children: React.ReactNode; className?: string }) => {
- const { open } = useContext(MockPopoverContext)
- if (!open) return null
- return (
- <div data-testid="portal-content" className={className}>
- {children}
- </div>
- )
- },
-}))
-
-// ==================== Test Utilities ====================
-
-const createFilterState = (overrides: Partial<FilterState> = {}): FilterState => ({
- categories: [],
- tags: [],
- searchQuery: '',
- ...overrides,
-})
-
-const renderFilterManagement = (
- onFilterChange = vi.fn(),
- props?: Partial<React.ComponentProps<typeof FilterManagement>>,
-) => {
- const result = render(<FilterManagement onFilterChange={onFilterChange} {...props} />)
- return { ...result, onFilterChange }
-}
-
-// ==================== search-box.tsx Tests ====================
-describe('SearchBox Component', () => {
+describe('FilterManagement', () => {
beforeEach(() => {
- vi.clearAllMocks()
+ initialFilters = { categories: [], tags: [], searchQuery: '' }
})
- describe('Rendering', () => {
- it('should render input with correct placeholder', () => {
- // Arrange & Act
- render(<SearchBox searchQuery="" onChange={vi.fn()} />)
-
- // Assert
- // Assert
- expect(screen.getByPlaceholderText('plugin.search'))!.toBeInTheDocument()
- })
+ it('renders filters from the plugin page state', () => {
+ initialFilters = { categories: ['model'], tags: ['agent'], searchQuery: 'search' }
- it('should render with provided searchQuery value', () => {
- // Arrange & Act
- render(<SearchBox searchQuery="test query" onChange={vi.fn()} />)
+ render(<FilterManagement onFilterChange={vi.fn()} />)
- // Assert
- // Assert
- expect(screen.getByDisplayValue('test query'))!.toBeInTheDocument()
- })
-
- it('should render search icon', () => {
- // Arrange & Act
- const { container } = render(<SearchBox searchQuery="" onChange={vi.fn()} />)
-
- // Assert - Input should have showLeftIcon which renders search icon
- const wrapper = container.querySelector('.w-\\[200px\\]')
- expect(wrapper)!.toBeInTheDocument()
- })
+ expect(screen.getByRole('button', { name: /Models/ })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /Agent/ })).toBeInTheDocument()
+ expect(screen.getByDisplayValue('search')).toBeInTheDocument()
})
- describe('User Interactions', () => {
- it('should call onChange when input value changes', () => {
- // Arrange
- const handleChange = vi.fn()
- render(<SearchBox searchQuery="" onChange={handleChange} />)
-
- // Act
- fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
- target: { value: 'new search' },
- })
+ it('emits the complete filter state when search changes', () => {
+ const onFilterChange = vi.fn()
+ initialFilters = { categories: ['model'], tags: ['agent'], searchQuery: '' }
+ render(<FilterManagement onFilterChange={onFilterChange} />)
- // Assert
- expect(handleChange).toHaveBeenCalledWith('new search')
+ fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
+ target: { value: 'new query' },
})
- it('should call onChange with empty string when cleared', () => {
- // Arrange
- const handleChange = vi.fn()
- render(<SearchBox searchQuery="existing" onChange={handleChange} />)
-
- // Act
- fireEvent.change(screen.getByDisplayValue('existing'), {
- target: { value: '' },
- })
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith('')
- })
-
- it('should handle rapid typing', () => {
- // Arrange
- const handleChange = vi.fn()
- render(<SearchBox searchQuery="" onChange={handleChange} />)
- const input = screen.getByPlaceholderText('plugin.search')
-
- // Act
- fireEvent.change(input, { target: { value: 'a' } })
- fireEvent.change(input, { target: { value: 'ab' } })
- fireEvent.change(input, { target: { value: 'abc' } })
-
- // Assert
- expect(handleChange).toHaveBeenCalledTimes(3)
- expect(handleChange).toHaveBeenLastCalledWith('abc')
+ expect(onFilterChange).toHaveBeenCalledWith({
+ categories: ['model'],
+ tags: ['agent'],
+ searchQuery: 'new query',
})
})
- describe('Edge Cases', () => {
- it('should handle special characters', () => {
- // Arrange
- const handleChange = vi.fn()
- render(<SearchBox searchQuery="" onChange={handleChange} />)
-
- // Act
- fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
- target: { value: '!@#$%^&*()' },
- })
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith('!@#$%^&*()')
- })
-
- it('should handle unicode characters', () => {
- // Arrange
- const handleChange = vi.fn()
- render(<SearchBox searchQuery="" onChange={handleChange} />)
-
- // Act
- fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
- target: { value: '中文搜索 🔍' },
- })
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith('中文搜索 🔍')
- })
-
- it('should handle very long input', () => {
- // Arrange
- const handleChange = vi.fn()
- const longText = 'a'.repeat(500)
- render(<SearchBox searchQuery="" onChange={handleChange} />)
-
- // Act
- fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
- target: { value: longText },
- })
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith(longText)
- })
- })
-})
+ it('hides optional filters', () => {
+ render(<FilterManagement hideCategoryFilter hideTagFilter onFilterChange={vi.fn()} />)
-// ==================== category-filter.tsx Tests ====================
-describe('CategoriesFilter Component', () => {
- beforeEach(() => {
- vi.clearAllMocks()
+ expect(screen.queryByRole('button')).not.toBeInTheDocument()
+ expect(screen.getByPlaceholderText('plugin.search')).toBeInTheDocument()
})
- describe('Rendering', () => {
- it('should render with "All Categories" text when no selection', () => {
- // Arrange & Act
- render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
-
- // Assert
- // Assert
- expect(screen.getByText('plugin.allCategories'))!.toBeInTheDocument()
- })
-
- it('should render dropdown arrow when no selection', () => {
- // Arrange & Act
- const { container } = render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
-
- // Assert - Arrow icon should be visible
- const arrowIcon = container.querySelector('svg')
- expect(arrowIcon)!.toBeInTheDocument()
- })
-
- it('should render selected category labels', () => {
- // Arrange & Act
- render(<CategoriesFilter value={['model']} onChange={vi.fn()} />)
-
- // Assert
- // Assert
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- })
-
- it('should show clear button when categories are selected', () => {
- // Arrange & Act
- const { container } = render(<CategoriesFilter value={['model']} onChange={vi.fn()} />)
-
- // Assert - Close icon should be visible
- const closeIcon = container.querySelector('[class*="cursor-pointer"]')
- expect(closeIcon)!.toBeInTheDocument()
- })
-
- it('should show count badge for more than 2 selections', () => {
- // Arrange & Act
- render(<CategoriesFilter value={['model', 'tool', 'extension']} onChange={vi.fn()} />)
-
- // Assert
- // Assert
- expect(screen.getByText('+1'))!.toBeInTheDocument()
- })
- })
-
- describe('Dropdown Behavior', () => {
- it('should open dropdown on trigger click', async () => {
- // Arrange
- render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('portal-content'))!.toBeInTheDocument()
- })
- })
-
- it('should display category options in dropdown', async () => {
- // Arrange
- render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
-
- // Assert
- await waitFor(() => {
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- expect(screen.getByText('Tools'))!.toBeInTheDocument()
- expect(screen.getByText('Extensions'))!.toBeInTheDocument()
- expect(screen.getByText('Agents'))!.toBeInTheDocument()
- })
- })
-
- it('should have search input in dropdown', async () => {
- // Arrange
- render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
-
- // Assert
- await waitFor(() => {
- expect(screen.getByPlaceholderText('plugin.searchCategories'))!.toBeInTheDocument()
- })
- })
- })
-
- describe('Selection Behavior', () => {
- it('should call onChange when category is selected', async () => {
- // Arrange
- const handleChange = vi.fn()
- render(<CategoriesFilter value={[]} onChange={handleChange} />)
-
- // Act - Open dropdown and click category
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('Models'))
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith(['model'])
- })
-
- it('should deselect when clicking selected category', async () => {
- // Arrange
- const handleChange = vi.fn()
- render(<CategoriesFilter value={['model']} onChange={handleChange} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- // Multiple "Models" texts exist - one in trigger, one in dropdown
- const allModels = screen.getAllByText('Models')
- expect(allModels.length).toBeGreaterThan(1)
- })
- // Click the one in the dropdown (inside portal-content)
- const portalContent = screen.getByTestId('portal-content')
- const modelsInDropdown = portalContent.querySelector('.system-sm-medium')!
- fireEvent.click(modelsInDropdown.parentElement!)
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith([])
- })
-
- it('should add to selection when clicking unselected category', async () => {
- // Arrange
- const handleChange = vi.fn()
- render(<CategoriesFilter value={['model']} onChange={handleChange} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- expect(screen.getByText('Tools'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('Tools'))
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith(['model', 'tool'])
- })
-
- it('should clear all selections when clear button is clicked', () => {
- // Arrange
- const handleChange = vi.fn()
- const { container } = render(
- <CategoriesFilter value={['model', 'tool']} onChange={handleChange} />,
- )
-
- // Act - Find and click the close icon
- const closeIcon = container.querySelector('.text-text-quaternary')
- expect(closeIcon)!.toBeInTheDocument()
- fireEvent.click(closeIcon!)
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith([])
- })
- })
-
- describe('Search Functionality', () => {
- it('should filter categories based on search text', async () => {
- // Arrange
- render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- expect(screen.getByPlaceholderText('plugin.searchCategories'))!.toBeInTheDocument()
- })
- fireEvent.change(screen.getByPlaceholderText('plugin.searchCategories'), {
- target: { value: 'mod' },
- })
-
- // Assert
- // Assert
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- expect(screen.queryByText('Extensions')).not.toBeInTheDocument()
- })
-
- it('should be case insensitive', async () => {
- // Arrange
- render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- expect(screen.getByPlaceholderText('plugin.searchCategories'))!.toBeInTheDocument()
- })
- fireEvent.change(screen.getByPlaceholderText('plugin.searchCategories'), {
- target: { value: 'MOD' },
- })
-
- // Assert
- // Assert
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- })
- })
-
- describe('Checkbox State', () => {
- it('should show checked checkbox for selected categories', async () => {
- // Arrange
- render(<CategoriesFilter value={['model']} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
-
- await waitFor(() => {
- expect(screen.getByRole('checkbox', { name: 'Models' })).toHaveAttribute(
- 'aria-checked',
- 'true',
- )
- })
- })
-
- it('should show unchecked checkbox for unselected categories', async () => {
- // Arrange
- render(<CategoriesFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
-
- await waitFor(() => {
- expect(screen.getByRole('checkbox', { name: 'Models' })).toHaveAttribute(
- 'aria-checked',
- 'false',
- )
- })
- })
- })
-})
-
-// ==================== tag-filter.tsx Tests ====================
-describe('TagFilter Component', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- describe('Rendering', () => {
- it('should render with "Tags" text when no selection', () => {
- // Arrange & Act
- render(<TagFilter value={[]} onChange={vi.fn()} />)
-
- // Assert
- // Assert
- expect(screen.getByText('common.tag.tags'))!.toBeInTheDocument()
- })
-
- it('should render selected tag labels', () => {
- // Arrange & Act
- render(<TagFilter value={['agent']} onChange={vi.fn()} />)
-
- // Assert
- // Assert
- expect(screen.getByText('Agent'))!.toBeInTheDocument()
- })
+ it('renders a right-side slot', () => {
+ render(<FilterManagement onFilterChange={vi.fn()} rightSlot={<span>Sort controls</span>} />)
- it('should show count badge for more than 2 selections', () => {
- // Arrange & Act
- render(<TagFilter value={['agent', 'rag', 'search']} onChange={vi.fn()} />)
-
- // Assert
- // Assert
- expect(screen.getByText('+1'))!.toBeInTheDocument()
- })
-
- it('should show clear button when tags are selected', () => {
- // Arrange & Act
- const { container } = render(<TagFilter value={['agent']} onChange={vi.fn()} />)
-
- // Assert
- const closeIcon = container.querySelector('.text-text-quaternary')
- expect(closeIcon)!.toBeInTheDocument()
- })
- })
-
- describe('Dropdown Behavior', () => {
- it('should open dropdown on trigger click', async () => {
- // Arrange
- render(<TagFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
-
- // Assert
- await waitFor(() => {
- expect(screen.getByTestId('portal-content'))!.toBeInTheDocument()
- })
- })
-
- it('should display tag options in dropdown', async () => {
- // Arrange
- render(<TagFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
-
- // Assert
- await waitFor(() => {
- expect(screen.getByText('Agent'))!.toBeInTheDocument()
- expect(screen.getByText('RAG'))!.toBeInTheDocument()
- expect(screen.getByText('Search'))!.toBeInTheDocument()
- expect(screen.getByText('Image'))!.toBeInTheDocument()
- })
- })
- })
-
- describe('Selection Behavior', () => {
- it('should call onChange when tag is selected', async () => {
- // Arrange
- const handleChange = vi.fn()
- render(<TagFilter value={[]} onChange={handleChange} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- expect(screen.getByText('Agent'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('Agent'))
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith(['agent'])
- })
-
- it('should deselect when clicking selected tag', async () => {
- // Arrange
- const handleChange = vi.fn()
- render(<TagFilter value={['agent']} onChange={handleChange} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- // Find the Agent option in dropdown
- const agentOptions = screen.getAllByText('Agent')
- fireEvent.click(agentOptions[agentOptions.length - 1]!)
- })
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith([])
- })
-
- it('should add to selection when clicking unselected tag', async () => {
- // Arrange
- const handleChange = vi.fn()
- render(<TagFilter value={['agent']} onChange={handleChange} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- expect(screen.getByText('RAG'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('RAG'))
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith(['agent', 'rag'])
- })
-
- it('should clear all selections when clear button is clicked', () => {
- // Arrange
- const handleChange = vi.fn()
- const { container } = render(<TagFilter value={['agent', 'rag']} onChange={handleChange} />)
-
- // Act
- const closeIcon = container.querySelector('.text-text-quaternary')
- fireEvent.click(closeIcon!)
-
- // Assert
- expect(handleChange).toHaveBeenCalledWith([])
- })
- })
-
- describe('Search Functionality', () => {
- it('should filter tags based on search text', async () => {
- // Arrange
- render(<TagFilter value={[]} onChange={vi.fn()} />)
-
- // Act
- fireEvent.click(screen.getByTestId('portal-trigger'))
- await waitFor(() => {
- expect(screen.getByPlaceholderText('pluginTags.searchTags'))!.toBeInTheDocument()
- })
- fireEvent.change(screen.getByPlaceholderText('pluginTags.searchTags'), {
- target: { value: 'rag' },
- })
-
- // Assert
- // Assert
- expect(screen.getByText('RAG'))!.toBeInTheDocument()
- expect(screen.queryByText('Image')).not.toBeInTheDocument()
- })
- })
-})
-
-// ==================== index.tsx (FilterManagement) Tests ====================
-describe('FilterManagement Component', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockInitFilters = createFilterState()
- })
-
- describe('Rendering', () => {
- it('should render all filter components', () => {
- // Arrange & Act
- renderFilterManagement()
-
- // Assert - All three filters should be present
- // Assert - All three filters should be present
- expect(screen.getByText('plugin.allCategories'))!.toBeInTheDocument()
- expect(screen.getByText('common.tag.tags'))!.toBeInTheDocument()
- expect(screen.getByPlaceholderText('plugin.search'))!.toBeInTheDocument()
- })
-
- it('should hide category filter when scoped to a fixed category', () => {
- // Arrange & Act
- renderFilterManagement(vi.fn(), { hideCategoryFilter: true })
-
- // Assert
- expect(screen.queryByText('plugin.allCategories'))!.not.toBeInTheDocument()
- expect(screen.getByText('common.tag.tags'))!.toBeInTheDocument()
- expect(screen.getByPlaceholderText('plugin.search'))!.toBeInTheDocument()
- })
-
- it('should hide tag filter when scoped category does not support tags', () => {
- // Arrange & Act
- renderFilterManagement(vi.fn(), { hideTagFilter: true })
-
- // Assert
- expect(screen.getByText('plugin.allCategories'))!.toBeInTheDocument()
- expect(screen.queryByText('common.tag.tags'))!.not.toBeInTheDocument()
- expect(screen.getByPlaceholderText('plugin.search'))!.toBeInTheDocument()
- })
- })
-
- describe('Initial State from Context', () => {
- it('should initialize with empty filters', () => {
- // Arrange
- mockInitFilters = createFilterState()
-
- // Act
- renderFilterManagement()
-
- // Assert
- // Assert
- expect(screen.getByText('plugin.allCategories'))!.toBeInTheDocument()
- expect(screen.getByText('common.tag.tags'))!.toBeInTheDocument()
- expect(screen.getByPlaceholderText('plugin.search'))!.toHaveValue('')
- })
-
- it('should initialize with pre-selected categories', () => {
- // Arrange
- mockInitFilters = createFilterState({ categories: ['model'] })
-
- // Act
- renderFilterManagement()
-
- // Assert
- // Assert
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- })
-
- it('should initialize with pre-selected tags', () => {
- // Arrange
- mockInitFilters = createFilterState({ tags: ['agent'] })
-
- // Act
- renderFilterManagement()
-
- // Assert
- // Assert
- expect(screen.getByText('Agent'))!.toBeInTheDocument()
- })
-
- it('should initialize with search query', () => {
- // Arrange
- mockInitFilters = createFilterState({ searchQuery: 'initial search' })
-
- // Act
- renderFilterManagement()
-
- // Assert
- // Assert
- expect(screen.getByDisplayValue('initial search'))!.toBeInTheDocument()
- })
- })
-
- describe('Filter Interactions', () => {
- it('should call onFilterChange when category is selected', async () => {
- // Arrange
- const onFilterChange = vi.fn()
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act - Open categories dropdown and select
- const triggers = screen.getAllByTestId('portal-trigger')
- fireEvent.click(triggers[0]!) // Categories filter trigger
-
- await waitFor(() => {
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('Models'))
-
- // Assert
- expect(onFilterChange).toHaveBeenCalledWith({
- categories: ['model'],
- tags: [],
- searchQuery: '',
- })
- })
-
- it('should call onFilterChange when tag is selected', async () => {
- // Arrange
- const onFilterChange = vi.fn()
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act - Open tags dropdown and select
- const triggers = screen.getAllByTestId('portal-trigger')
- fireEvent.click(triggers[1]!) // Tags filter trigger
-
- await waitFor(() => {
- expect(screen.getByText('Agent'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('Agent'))
-
- // Assert
- expect(onFilterChange).toHaveBeenCalledWith({
- categories: [],
- tags: ['agent'],
- searchQuery: '',
- })
- })
-
- it('should call onFilterChange when search query changes', () => {
- // Arrange
- const onFilterChange = vi.fn()
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act
- fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
- target: { value: 'test query' },
- })
-
- // Assert
- expect(onFilterChange).toHaveBeenCalledWith({
- categories: [],
- tags: [],
- searchQuery: 'test query',
- })
- })
- })
-
- describe('State Management', () => {
- it('should accumulate filter changes', async () => {
- // Arrange
- const onFilterChange = vi.fn()
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act 1 - Select a category
- const triggers = screen.getAllByTestId('portal-trigger')
- fireEvent.click(triggers[0]!)
- await waitFor(() => {
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('Models'))
-
- expect(onFilterChange).toHaveBeenLastCalledWith({
- categories: ['model'],
- tags: [],
- searchQuery: '',
- })
-
- // Close dropdown by clicking trigger again
- fireEvent.click(triggers[0]!)
-
- // Act 2 - Select a tag (state should include previous category)
- fireEvent.click(triggers[1]!)
- await waitFor(() => {
- expect(screen.getByText('Agent'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('Agent'))
-
- // Assert - Both category and tag should be in the state
- expect(onFilterChange).toHaveBeenLastCalledWith({
- categories: ['model'],
- tags: ['agent'],
- searchQuery: '',
- })
- })
-
- it('should preserve other filters when updating one', () => {
- // Arrange
- mockInitFilters = createFilterState({
- categories: ['model'],
- tags: ['agent'],
- })
- const onFilterChange = vi.fn()
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act - Change only search query
- fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
- target: { value: 'new search' },
- })
-
- // Assert - Other filters should be preserved
- expect(onFilterChange).toHaveBeenCalledWith({
- categories: ['model'],
- tags: ['agent'],
- searchQuery: 'new search',
- })
- })
- })
-
- describe('Integration Tests', () => {
- it('should handle complete filter workflow', async () => {
- // Arrange
- const onFilterChange = vi.fn()
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act 1 - Select categories
- const triggers = screen.getAllByTestId('portal-trigger')
- fireEvent.click(triggers[0]!)
- await waitFor(() => {
- expect(screen.getByText('Models'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('Models'))
- fireEvent.click(triggers[0]!) // Close
-
- // Act 2 - Select tags
- fireEvent.click(triggers[1]!)
- await waitFor(() => {
- expect(screen.getByText('RAG'))!.toBeInTheDocument()
- })
- fireEvent.click(screen.getByText('RAG'))
- fireEvent.click(triggers[1]!) // Close
-
- // Act 3 - Enter search
- fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
- target: { value: 'gpt' },
- })
-
- // Assert - Final state should include all filters
- expect(onFilterChange).toHaveBeenLastCalledWith({
- categories: ['model'],
- tags: ['rag'],
- searchQuery: 'gpt',
- })
- })
-
- it('should handle filter clearing', async () => {
- // Arrange
- mockInitFilters = createFilterState({
- categories: ['model'],
- tags: ['agent'],
- searchQuery: 'test',
- })
- const onFilterChange = vi.fn()
- const { container } = render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act - Clear search
- fireEvent.change(screen.getByDisplayValue('test'), {
- target: { value: '' },
- })
-
- // Assert
- expect(onFilterChange).toHaveBeenLastCalledWith({
- categories: ['model'],
- tags: ['agent'],
- searchQuery: '',
- })
-
- // Act - Clear categories (click clear button)
- const closeIcons = container.querySelectorAll('.text-text-quaternary')
- fireEvent.click(closeIcons[0]!) // First close icon is for categories
-
- // Assert
- expect(onFilterChange).toHaveBeenLastCalledWith({
- categories: [],
- tags: ['agent'],
- searchQuery: '',
- })
- })
- })
-
- describe('Edge Cases', () => {
- it('should handle empty initial state', () => {
- // Arrange
- mockInitFilters = createFilterState()
- const onFilterChange = vi.fn()
-
- // Act
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Assert - Should render without errors
- // Assert - Should render without errors
- expect(screen.getByText('plugin.allCategories'))!.toBeInTheDocument()
- })
-
- it('should handle multiple rapid filter changes', () => {
- // Arrange
- const onFilterChange = vi.fn()
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act - Rapid search input changes
- const searchInput = screen.getByPlaceholderText('plugin.search')
- fireEvent.change(searchInput, { target: { value: 'a' } })
- fireEvent.change(searchInput, { target: { value: 'ab' } })
- fireEvent.change(searchInput, { target: { value: 'abc' } })
-
- // Assert
- expect(onFilterChange).toHaveBeenCalledTimes(3)
- expect(onFilterChange).toHaveBeenLastCalledWith(
- expect.objectContaining({ searchQuery: 'abc' }),
- )
- })
-
- it('should handle special characters in search', () => {
- // Arrange
- const onFilterChange = vi.fn()
- render(<FilterManagement onFilterChange={onFilterChange} />)
-
- // Act
- fireEvent.change(screen.getByPlaceholderText('plugin.search'), {
- target: { value: '!@#$%^&*()' },
- })
-
- // Assert
- expect(onFilterChange).toHaveBeenCalledWith(
- expect.objectContaining({ searchQuery: '!@#$%^&*()' }),
- )
- })
+ expect(screen.getByText('Sort controls')).toBeInTheDocument()
})
})
diff --git a/web/app/components/plugins/plugin-page/filter-management/__tests__/tag-filter.spec.tsx b/web/app/components/plugins/plugin-page/filter-management/__tests__/tag-filter.spec.tsx
index 854354e35e2..850011bc8ba 100644
--- a/web/app/components/plugins/plugin-page/filter-management/__tests__/tag-filter.spec.tsx
+++ b/web/app/components/plugins/plugin-page/filter-management/__tests__/tag-filter.spec.tsx
@@ -18,8 +18,6 @@ vi.mock('../../../hooks', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
describe('TagFilter', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -38,12 +36,12 @@ describe('TagFilter', () => {
expect(screen.getByText('+1')).toBeInTheDocument()
})
- it('filters options by search text and toggles tag selection', () => {
+ it('filters options by search text and toggles tag selection', async () => {
const onChange = vi.fn()
render(<TagFilter value={['agent']} onChange={onChange} />)
- fireEvent.click(screen.getByTestId('popover-trigger'))
- const portal = screen.getByTestId('popover-content')
+ fireEvent.click(screen.getByRole('button', { name: /Agent/ }))
+ const portal = await screen.findByRole('dialog')
fireEvent.change(screen.getByPlaceholderText('pluginTags.searchTags'), {
target: { value: 'ra' },
@@ -61,18 +59,18 @@ describe('TagFilter', () => {
const onChange = vi.fn()
render(<TagFilter value={['agent']} onChange={onChange} />)
- const trigger = screen.getByTestId('popover-trigger')
+ const trigger = screen.getByRole('button', { name: /Agent/ })
fireEvent.click(trigger.querySelector('.i-ri-close-circle-fill')!)
expect(onChange).toHaveBeenCalledWith([])
})
- it('removes a selected tag when clicking the same option again', () => {
+ it('removes a selected tag when clicking the same option again', async () => {
const onChange = vi.fn()
render(<TagFilter value={['agent']} onChange={onChange} />)
- fireEvent.click(screen.getByTestId('popover-trigger'))
- fireEvent.click(within(screen.getByTestId('popover-content')).getByText('Agent'))
+ fireEvent.click(screen.getByRole('button', { name: /Agent/ }))
+ fireEvent.click(within(await screen.findByRole('dialog')).getByText('Agent'))
expect(onChange).toHaveBeenCalledWith([])
})
diff --git a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx b/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
index db94bb50309..83398241363 100644
--- a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
@@ -17,33 +17,6 @@ const mockSystemFeatures = {
const render = (ui: ReactElement) =>
renderWithConsoleQuery(ui, { systemFeatures: mockSystemFeatures })
-let mockDialogOnOpenChange: ((open: boolean) => void) | undefined
-
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) => {
- mockDialogOnOpenChange = onOpenChange
- return open === false ? null : <>{children}</>
- },
- DialogContent: ({ children, className }: { children: React.ReactNode; className?: string }) => (
- <div data-testid="modal" className={className}>
- {children}
- </div>
- ),
- DialogCloseButton: () => (
- <button data-testid="modal-close" onClick={() => mockDialogOnOpenChange?.(false)}>
- Close
- </button>
- ),
-}))
-
// Mock OptionCard component
vi.mock('@/app/components/workflow/nodes/_base/components/option-card', () => ({
default: ({
@@ -280,7 +253,7 @@ describe('reference-setting-modal', () => {
// Assert
// Assert
- expect(screen.getByTestId('modal-close'))!.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Close' }))!.toBeInTheDocument()
})
it('should disable permission controls with settings permissions tooltip beside titles when RBAC is enabled', () => {
@@ -381,7 +354,7 @@ describe('reference-setting-modal', () => {
// Act
render(<ReferenceSettingModal {...defaultProps} onHide={onHide} />)
- fireEvent.click(screen.getByTestId('modal-close'))
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }))
// Assert
expect(onHide).toHaveBeenCalledTimes(1)
@@ -843,7 +816,7 @@ describe('reference-setting-modal', () => {
// Assert - modal should be visible
// Assert - modal should be visible
- expect(screen.getByTestId('modal'))!.toBeInTheDocument()
+ expect(screen.getByRole('dialog'))!.toBeInTheDocument()
})
})
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/index.spec.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/index.spec.tsx
index e27c4ccabbb..29e1d4aed0d 100644
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/index.spec.tsx
@@ -88,126 +88,11 @@ vi.mock('@/service/use-plugins', () => ({
}),
}))
-// Mock popover component for ToolPicker and StrategyPicker
-let mockPopoverOpen = false
-let forcePopoverContentVisible = false // Allow tests to force content visibility
-let mockPopoverOnOpenChange: ((open: boolean) => void) | undefined
-vi.mock('@langgenius/dify-ui/popover', () => ({
- Popover: ({
- children,
- open = false,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) => {
- mockPopoverOpen = open
- mockPopoverOnOpenChange = onOpenChange
- return (
- <div data-testid="popover" data-open={open}>
- {children}
- </div>
- )
- },
- PopoverTrigger: ({
- children,
- render,
- onClick,
- className,
- }: {
- children?: React.ReactNode
- render?: React.ReactNode
- onClick?: (e: React.MouseEvent) => void
- className?: string
- }) => (
- <div
- data-testid="popover-trigger"
- role="button"
- aria-label="popover trigger"
- tabIndex={0}
- onClick={(e) => {
- onClick?.(e)
- if (!onClick) mockPopoverOnOpenChange?.(!mockPopoverOpen)
- }}
- onKeyDown={(e) => {
- if ((e.key === 'Enter' || e.key === ' ') && !onClick)
- mockPopoverOnOpenChange?.(!mockPopoverOpen)
- }}
- className={className}
- >
- {render ?? children}
- </div>
- ),
- PopoverContent: ({
- children,
- className,
- popupClassName,
- }: {
- children: React.ReactNode
- className?: string
- popupClassName?: string
- }) => {
- if (!mockPopoverOpen && !forcePopoverContentVisible) return null
- return (
- <div
- data-testid="popover-content"
- className={[className, popupClassName].filter(Boolean).join(' ')}
- >
- {children}
- </div>
- )
- },
-}))
-
-// Mock TimePicker component - simplified stateless mock
-vi.mock('@/app/components/base/date-and-time-picker/time-picker', () => ({
- default: ({
- value,
- onChange,
- onClear,
- renderTrigger,
- }: {
- value: { format: (f: string) => string }
- onChange: (v: unknown) => void
- onClear: () => void
- title?: string
- renderTrigger: (
- props: React.HTMLAttributes<HTMLElement>,
- state: { open: boolean },
- params: { inputElem: React.ReactNode; onClick: () => void },
- ) => React.ReactNode
- }) => {
- const inputElem = <span data-testid="time-input">{value.format('HH:mm')}</span>
-
- return (
- <div data-testid="time-picker">
- {renderTrigger({}, { open: false }, { inputElem, onClick: () => {} })}
- <div data-testid="time-picker-dropdown">
- <button
- data-testid="time-picker-set"
- onClick={() => {
- onChange(dayjs().hour(10).minute(30))
- }}
- >
- Set 10:30
- </button>
- <button
- data-testid="time-picker-clear"
- onClick={() => {
- onClear()
- }}
- >
- Clear
- </button>
- </div>
- </div>
- )
- },
-}))
-
// Mock utils from date-and-time-picker
-vi.mock('@/app/components/base/date-and-time-picker/utils/dayjs', () => ({
+vi.mock('@/app/components/base/date-and-time-picker/utils/dayjs', async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import('@/app/components/base/date-and-time-picker/utils/dayjs')
+ >()),
convertTimezoneToOffsetStr: (tz: string) => {
if (tz === 'America/New_York') return 'GMT-5'
if (tz === 'Asia/Shanghai') return 'GMT+8'
@@ -390,9 +275,6 @@ const renderWithQueryClient = (ui: React.ReactElement) => {
describe('auto-update-setting', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockPopoverOpen = false
- mockPopoverOnOpenChange = undefined
- forcePopoverContentVisible = false
mockPluginsData.plugins = []
})
@@ -862,7 +744,6 @@ describe('auto-update-setting', () => {
it('should render search box and tabs when isShow is true', () => {
// Arrange
- mockPopoverOpen = true
// Act
render(<ToolPicker {...defaultProps} isShow={true} />)
@@ -873,7 +754,6 @@ describe('auto-update-setting', () => {
it('should show NoDataPlaceholder when no plugins and no search query', () => {
// Arrange
- mockPopoverOpen = true
mockPluginsData.plugins = []
// Act
@@ -915,7 +795,6 @@ describe('auto-update-setting', () => {
it('should filter out non-marketplace plugins', () => {
// Arrange
- mockPopoverOpen = true
// Act
renderWithQueryClient(<ToolPicker {...defaultProps} isShow={true} />)
@@ -926,7 +805,6 @@ describe('auto-update-setting', () => {
it('should filter by search query', () => {
// Arrange
- mockPopoverOpen = true
// Act
renderWithQueryClient(<ToolPicker {...defaultProps} isShow={true} />)
@@ -947,15 +825,14 @@ describe('auto-update-setting', () => {
// Act
render(<ToolPicker {...defaultProps} onShowChange={onShowChange} />)
- fireEvent.click(screen.getByTestId('popover-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'Select Plugins' }))
// Assert
- expect(onShowChange).toHaveBeenCalledWith(true)
+ expect(onShowChange).toHaveBeenCalledWith(true, expect.any(Object))
})
it('should call onChange when plugin is selected', () => {
// Arrange
- mockPopoverOpen = true
mockPluginsData.plugins = [
createMockPluginDetail({
plugin_id: 'test-plugin',
@@ -977,7 +854,6 @@ describe('auto-update-setting', () => {
it('should unselect plugin when already selected', () => {
// Arrange
- mockPopoverOpen = true
mockPluginsData.plugins = [
createMockPluginDetail({
plugin_id: 'test-plugin',
@@ -1128,7 +1004,6 @@ describe('auto-update-setting', () => {
// Assert
expect(screen.getByText('plugin.autoUpdate.updateTime')).toBeInTheDocument()
- expect(screen.getByTestId('time-picker')).toBeInTheDocument()
})
it('should hide time picker and plugins selection when strategy is disabled', () => {
@@ -1142,7 +1017,6 @@ describe('auto-update-setting', () => {
// Assert
expect(screen.queryByText('plugin.autoUpdate.updateTime')).not.toBeInTheDocument()
- expect(screen.queryByTestId('time-picker')).not.toBeInTheDocument()
})
it('should show plugins picker when mode is not update_all', () => {
@@ -1284,46 +1158,6 @@ describe('auto-update-setting', () => {
)
})
- it('should call onChange with updated time when time changes', () => {
- // Arrange
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- // Click time picker trigger
- fireEvent.click(screen.getByRole('button', { name: /GMT-5/ }))
-
- // Set time
- fireEvent.click(screen.getByRole('button', { name: 'Set 10:30' }))
-
- // Assert
- expect(onChange).toHaveBeenCalled()
- })
-
- it('should call onChange with 0 when time is cleared', () => {
- // Arrange
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- // Click time picker trigger
- fireEvent.click(screen.getByRole('button', { name: /GMT-5/ }))
-
- // Clear time
- fireEvent.click(screen.getByRole('button', { name: 'Clear' }))
-
- // Assert
- expect(onChange).toHaveBeenCalled()
- })
-
it('should call onChange with include_plugins when in partial mode', () => {
// Arrange
const onChange = vi.fn()
@@ -1390,20 +1224,6 @@ describe('auto-update-setting', () => {
})
describe('Callback Memoization', () => {
- it('minuteFilter should filter to 15 minute intervals', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // The minuteFilter is passed to TimePicker internally
- // We verify the component renders correctly
- expect(screen.getByTestId('time-picker')).toBeInTheDocument()
- })
-
it('handleChange should preserve other config values', () => {
// Arrange
const onChange = vi.fn()
@@ -1523,20 +1343,6 @@ describe('auto-update-setting', () => {
expect(screen.getByText('plugin.autoUpdate.updateSettings')).toBeInTheDocument()
})
- it('should handle null timezone gracefully', () => {
- // This tests the timezone! non-null assertion in the component
- // The mock provides a valid timezone, so the component should work
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert - should render without errors
- expect(screen.getByTestId('time-picker')).toBeInTheDocument()
- })
-
it('should render timezone offset correctly', () => {
// Arrange
const payload = createMockAutoUpdateConfig({
@@ -1630,7 +1436,7 @@ describe('auto-update-setting', () => {
)
// Assert - initially disabled
- expect(screen.queryByTestId('time-picker')).not.toBeInTheDocument()
+ expect(screen.queryByText('plugin.autoUpdate.updateTime')).not.toBeInTheDocument()
// Simulate enabling updates
currentPayload = createMockAutoUpdateConfig({
@@ -1641,7 +1447,7 @@ describe('auto-update-setting', () => {
rerender(<AutoUpdateSetting payload={currentPayload} onChange={onChange} />)
// Assert - time picker and plugins visible
- expect(screen.getByTestId('time-picker')).toBeInTheDocument()
+ expect(screen.getByText('plugin.autoUpdate.updateTime')).toBeInTheDocument()
expect(screen.getByText('plugin.autoUpdate.operation.select')).toBeInTheDocument()
})
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/plugins-picker.spec.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/plugins-picker.spec.tsx
index 36a378ad8df..4199da53a6f 100644
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/plugins-picker.spec.tsx
+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/plugins-picker.spec.tsx
@@ -28,10 +28,6 @@ vi.mock('@/service/use-plugins', () => ({
useInstalledPluginList: () => mockInstalledPluginList,
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children }: { children: React.ReactNode }) => <button>{children}</button>,
-}))
-
vi.mock('../no-plugin-selected', () => ({
default: ({ updateMode }: { updateMode: AUTO_UPDATE_MODE }) => (
<div data-testid="no-plugin-selected">{updateMode}</div>
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsx
index d48d19c1c65..bbd2e0afab6 100644
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsx
+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsx
@@ -19,56 +19,6 @@ vi.mock('@/app/components/base/loading', () => ({
default: () => <div data-testid="loading">loading</div>,
}))
-vi.mock('@langgenius/dify-ui/popover', async () => {
- const React = await import('react')
- const PopoverContext = React.createContext({
- open: false,
- setOpen: (_open: boolean) => {},
- })
-
- const Popover = ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <PopoverContext.Provider
- value={{ open: !!open, setOpen: (nextOpen: boolean) => onOpenChange?.(nextOpen) }}
- >
- {children}
- </PopoverContext.Provider>
- )
-
- const PopoverTrigger = ({ render }: { render: React.ReactNode }) => {
- const { open, setOpen } = React.useContext(PopoverContext)
- return <div onClick={() => setOpen(!open)}>{render}</div>
- }
-
- const PopoverContent = ({
- children,
- className,
- }: {
- children: React.ReactNode
- className?: string
- }) => {
- const { open } = React.useContext(PopoverContext)
- return open ? (
- <div data-testid="popover-content" className={className}>
- {children}
- </div>
- ) : null
- }
-
- return {
- Popover,
- PopoverTrigger,
- PopoverContent,
- }
-})
-
vi.mock('@/app/components/plugins/marketplace/search-box', () => ({
default: ({
search,
@@ -151,7 +101,7 @@ describe('ToolPicker', () => {
const onShowChange = vi.fn()
render(
<ToolPicker
- trigger={<span>trigger</span>}
+ trigger={<button type="button">trigger</button>}
value={[]}
onChange={vi.fn()}
isShow={false}
@@ -161,7 +111,7 @@ describe('ToolPicker', () => {
fireEvent.click(screen.getByText('trigger'))
- expect(onShowChange).toHaveBeenCalledWith(true)
+ expect(onShowChange).toHaveBeenCalledWith(true, expect.any(Object))
})
it('renders loading content while installed plugins are loading', () => {
diff --git a/web/app/components/plugins/update-plugin/__tests__/from-market-place.spec.tsx b/web/app/components/plugins/update-plugin/__tests__/from-market-place.spec.tsx
index 73cd65d24e9..3ad658c82d5 100644
--- a/web/app/components/plugins/update-plugin/__tests__/from-market-place.spec.tsx
+++ b/web/app/components/plugins/update-plugin/__tests__/from-market-place.spec.tsx
@@ -28,13 +28,6 @@ vi.mock('@/context/workspace-state', async () => {
}))
})
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DialogCloseButton: () => <button>close dialog</button>,
-}))
-
vi.mock('@/app/components/base/badge/index', () => ({
__esModule: true,
BadgeState: {
@@ -43,22 +36,6 @@ vi.mock('@/app/components/base/badge/index', () => ({
default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- disabled,
- }: {
- children: React.ReactNode
- onClick?: () => void
- disabled?: boolean
- }) => (
- <button disabled={disabled} onClick={onClick}>
- {children}
- </button>
- ),
-}))
-
vi.mock('@langgenius/dify-ui/toast', () => ({
toast: {
error: mockToastError,
diff --git a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx
index b9904207354..96c0a18d85c 100644
--- a/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/conversion.spec.tsx
@@ -60,14 +60,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
toast: mockToast,
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children, onClick, ...props }: Record<string, unknown>) => (
- <button onClick={onClick as () => void} {...props}>
- {children as string}
- </button>
- ),
-}))
-
vi.mock('../screenshot', () => ({
default: () => <div data-testid="screenshot" />,
}))
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
index 874ccc2bfd6..873d1763446 100644
--- 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
@@ -16,27 +16,6 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, open }: { children: React.ReactNode; open?: boolean }) =>
- open === false ? null : <>{children}</>,
- DialogContent: ({ children, className }: { children: React.ReactNode; className?: string }) => (
- <div data-testid="modal" className={className}>
- {children}
- </div>
- ),
- DialogTitle: ({ children, className }: { children: React.ReactNode; className?: string }) => (
- <h2 className={className}>{children}</h2>
- ),
-}))
-
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ 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
@@ -78,7 +57,7 @@ describe('PublishAsKnowledgePipelineModal', () => {
it('should render modal with title', () => {
render(<PublishAsKnowledgePipelineModal {...defaultProps} />)
- expect(screen.getByTestId('modal')).toBeInTheDocument()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
expect(screen.getByText('pipeline.common.publishAs')).toBeInTheDocument()
})
diff --git a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
index fd93558bb17..f046124474e 100644
--- a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
@@ -1,4 +1,3 @@
-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'
@@ -107,44 +106,6 @@ vi.mock('@/app/components/app/create-from-dsl-modal/uploader', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- onClick,
- disabled,
- className,
- variant,
- loading,
- }: {
- children: React.ReactNode
- onClick?: () => void
- disabled?: boolean
- className?: string
- variant?: string
- loading?: boolean
- }) => (
- <button
- onClick={onClick}
- disabled={disabled}
- className={className}
- data-variant={variant}
- data-loading={loading}
- >
- {children}
- </button>
- ),
-}))
-
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- Dialog: ({ children, open }: PropsWithChildren<{ open?: boolean }>) =>
- open === false ? null : <>{children}</>,
- DialogContent: ({ children, className }: PropsWithChildren<{ className?: string }>) => (
- <div data-testid="modal" className={className}>
- {children}
- </div>
- ),
-}))
-
vi.mock('@/app/components/workflow/constants', () => ({
WORKFLOW_DATA_UPDATE: 'WORKFLOW_DATA_UPDATE',
}))
@@ -310,34 +271,6 @@ describe('UpdateDSLModal', () => {
})
})
- describe('edge cases', () => {
- it('should handle missing onImport callback', () => {
- const props = {
- onCancel: mockOnCancel,
- onBackup: mockOnBackup,
- }
-
- render(<UpdateDSLModal {...props} />)
-
- expect(screen.getByTestId('modal')).toBeInTheDocument()
- })
-
- it('should render import button with primary destructive variant', () => {
- render(<UpdateDSLModal {...defaultProps} />)
-
- const importButton = screen.getByText('workflow.common.overwriteAndImport')
- expect(importButton).toHaveAttribute('data-variant', 'primary')
- })
-
- it('should render backup button with secondary variant', () => {
- render(<UpdateDSLModal {...defaultProps} />)
-
- const backupButtonText = screen.getByText('workflow.common.backupCurrentDraft')
- const backupButton = backupButtonText.closest('button')
- expect(backupButton).toHaveAttribute('data-variant', 'secondary')
- })
- })
-
describe('import flow', () => {
it('should call importDSL when import button is clicked with file content', async () => {
render(<UpdateDSLModal {...defaultProps} />)
@@ -718,13 +651,8 @@ describe('UpdateDSLModal', () => {
{ timeout: 1000 },
)
- const cancelButtons = screen.getAllByText('app.newApp.Cancel')
- const errorModalCancelButton = cancelButtons.find(
- (btn) => btn.getAttribute('data-variant') === 'secondary',
- )
- if (errorModalCancelButton) {
- fireEvent.click(errorModalCancelButton)
- }
+ const cancelButtons = screen.getAllByRole('button', { name: 'app.newApp.Cancel' })
+ fireEvent.click(cancelButtons.at(-1)!)
await waitFor(() => {
expect(screen.queryByText('app.newApp.appCreateDSLErrorTitle')).not.toBeInTheDocument()
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
index dfe95376db3..ea916849896 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
@@ -36,54 +36,6 @@ const triggerHotkey = (hotkey: string) => {
})
}
-vi.mock('@langgenius/dify-ui/popover', async () => await import('@/__mocks__/base-ui-popover'))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children, onClick, disabled, variant, className }: Record<string, unknown>) => (
- <button
- onClick={onClick as (() => void) | undefined}
- disabled={disabled as boolean | undefined}
- data-variant={variant as string | undefined}
- className={className as string | undefined}
- >
- {children as React.ReactNode}
- </button>
- ),
-}))
-vi.mock('@langgenius/dify-ui/alert-dialog', () => ({
- AlertDialog: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) =>
- open ? (
- <div role="alertdialog">
- {children}
- <button data-testid="alert-dialog-close" onClick={() => onOpenChange?.(false)}>
- Close
- </button>
- </div>
- ) : null,
- AlertDialogActions: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- AlertDialogCancelButton: ({ children }: { children: React.ReactNode }) => (
- <button>{children}</button>
- ),
- AlertDialogConfirmButton: ({ children, onClick, disabled }: Record<string, unknown>) => (
- <button
- onClick={onClick as (() => void) | undefined}
- disabled={disabled as boolean | undefined}
- >
- {children as React.ReactNode}
- </button>
- ),
- AlertDialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- AlertDialogDescription: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- AlertDialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
const mockPush = vi.fn()
vi.mock('@/next/navigation', () => ({
useParams: () => ({ datasetId: 'test-dataset-id' }),
@@ -348,7 +300,7 @@ describe('publisher', () => {
it('should render portal element in closed state by default', () => {
renderWithQueryClient(<Publisher />)
- expect(screen.getByTestId('popover')).toHaveAttribute('data-open', 'false')
+ expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByText('workflow.common.publishUpdate')).not.toBeInTheDocument()
})
@@ -900,7 +852,7 @@ describe('publisher', () => {
expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()
})
- fireEvent.click(screen.getByTestId('alert-dialog-close'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
await waitFor(() => {
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
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
index afa24f487aa..caf958a996a 100644
--- 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
@@ -11,46 +11,6 @@ const render = (ui: React.ReactElement) => {
return renderWithConsoleState(ui, { wrapper })
}
-vi.mock('@langgenius/dify-ui/alert-dialog', () => ({
- AlertDialog: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) =>
- open ? (
- <div role="alertdialog">
- {children}
- <button data-testid="alert-dialog-close" onClick={() => onOpenChange?.(false)}>
- Close
- </button>
- </div>
- ) : null,
- AlertDialogActions: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
- AlertDialogCancelButton: ({ children }: { children?: React.ReactNode }) => (
- <button>{children}</button>
- ),
- AlertDialogConfirmButton: ({
- children,
- onClick,
- disabled,
- }: {
- children?: React.ReactNode
- onClick?: () => void
- disabled?: boolean
- }) => (
- <button onClick={onClick} disabled={disabled}>
- {children}
- </button>
- ),
- AlertDialogContent: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
- AlertDialogDescription: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
- AlertDialogTitle: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
-}))
-
const mockPublishWorkflow = vi.fn().mockResolvedValue({ created_at: '2024-01-01T00:00:00Z' })
const mockPublishAsCustomizedPipeline = vi.fn().mockResolvedValue({})
const toastMocks = vi.hoisted(() => ({
@@ -137,19 +97,6 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ 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/divider', () => ({
default: () => <hr />,
}))
@@ -459,7 +406,7 @@ describe('Popup', () => {
render(<Popup />)
- fireEvent.click(screen.getByTestId('alert-dialog-close'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
expect(hideConfirm).toHaveBeenCalledTimes(1)
})
diff --git a/web/app/components/tools/labels/__tests__/selector.spec.tsx b/web/app/components/tools/labels/__tests__/selector.spec.tsx
index 3bd54c3c5c3..f4a5ca0eb70 100644
--- a/web/app/components/tools/labels/__tests__/selector.spec.tsx
+++ b/web/app/components/tools/labels/__tests__/selector.spec.tsx
@@ -2,71 +2,6 @@ import { act, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import LabelSelector from '../selector'
-vi.mock('@langgenius/dify-ui/popover', async () => {
- const React = await import('react')
- const PopoverContext = React.createContext({
- open: false,
- setOpen: (_open: boolean) => {},
- })
-
- const Popover = ({
- children,
- open: controlledOpen,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) => {
- const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false)
- const isControlled = controlledOpen !== undefined
- const open = isControlled ? !!controlledOpen : uncontrolledOpen
- const setOpen = (nextOpen: boolean) => {
- if (!isControlled) setUncontrolledOpen(nextOpen)
- onOpenChange?.(nextOpen)
- }
-
- return <PopoverContext.Provider value={{ open, setOpen }}>{children}</PopoverContext.Provider>
- }
-
- const PopoverTrigger = ({
- children,
- className,
- render,
- }: {
- children?: React.ReactNode
- className?: string
- render?: React.ReactNode
- }) => {
- const { open, setOpen } = React.useContext(PopoverContext)
- if (render) {
- return <div onClick={() => setOpen(!open)}>{render}</div>
- }
-
- return (
- <button type="button" className={className} onClick={() => setOpen(!open)}>
- {children}
- </button>
- )
- }
-
- const PopoverContent = ({
- children,
- ...props
- }: React.HTMLAttributes<HTMLDivElement> & { children?: React.ReactNode }) => {
- const { open } = React.useContext(PopoverContext)
- if (!open) return null
-
- return <div {...props}>{children}</div>
- }
-
- return {
- Popover,
- PopoverTrigger,
- PopoverContent,
- }
-})
-
// Mock useTags hook with controlled test data
const mockTags = [
{ name: 'agent', label: 'Agent' },
diff --git a/web/app/components/tools/mcp/detail/__tests__/operation-dropdown.spec.tsx b/web/app/components/tools/mcp/detail/__tests__/operation-dropdown.spec.tsx
index d7b3f3627bd..4342113f3b3 100644
--- a/web/app/components/tools/mcp/detail/__tests__/operation-dropdown.spec.tsx
+++ b/web/app/components/tools/mcp/detail/__tests__/operation-dropdown.spec.tsx
@@ -2,118 +2,6 @@ import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import OperationDropdown from '../operation-dropdown'
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- isOpen: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) => {
- const [internalOpen, setInternalOpen] = React.useState(open ?? false)
- const isOpen = open ?? internalOpen
- const setOpen = (nextOpen: boolean) => {
- if (open === undefined) setInternalOpen(nextOpen)
- onOpenChange?.(nextOpen)
- }
-
- return (
- <DropdownMenuContext value={{ isOpen, setOpen }}>
- <div data-testid="dropdown-menu" data-open={isOpen}>
- {children}
- </div>
- </DropdownMenuContext>
- )
- },
- DropdownMenuTrigger: ({
- children,
- render,
- onClick,
- }: {
- children: React.ReactNode
- render?: React.ReactElement
- onClick?: React.MouseEventHandler<HTMLElement>
- }) => {
- const { isOpen, setOpen } = useDropdownMenuContext()
- const handleClick = (e: React.MouseEvent<HTMLElement>) => {
- onClick?.(e)
- setOpen(!isOpen)
- }
-
- if (render)
- return React.cloneElement(
- render,
- { 'data-testid': 'dropdown-trigger', onClick: handleClick } as Record<string, unknown>,
- children,
- )
-
- return (
- <button data-testid="dropdown-trigger" onClick={handleClick}>
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({
- children,
- className,
- popupClassName,
- }: {
- children: React.ReactNode
- className?: string
- popupClassName?: string
- }) => {
- const { isOpen } = useDropdownMenuContext()
- return isOpen ? (
- <div
- data-testid="dropdown-content"
- className={[className, popupClassName].filter(Boolean).join(' ')}
- >
- {children}
- </div>
- ) : null
- },
- DropdownMenuItem: ({
- children,
- onClick,
- className,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- className?: string
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- data-testid="dropdown-item"
- className={className}
- onClick={(e) => {
- onClick?.(e)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- }
-})
-
describe('OperationDropdown', () => {
const defaultProps = {
onEdit: vi.fn(),
@@ -145,7 +33,7 @@ describe('OperationDropdown', () => {
it('should open dropdown when trigger is clicked', async () => {
render(<OperationDropdown {...defaultProps} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
expect(screen.getByText('tools.mcp.operation.edit')).toBeInTheDocument()
expect(screen.getByText('tools.mcp.operation.remove')).toBeInTheDocument()
@@ -155,17 +43,17 @@ describe('OperationDropdown', () => {
const onOpenChange = vi.fn()
render(<OperationDropdown {...defaultProps} onOpenChange={onOpenChange} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
- expect(onOpenChange).toHaveBeenCalledWith(true)
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ expect(onOpenChange).toHaveBeenCalledWith(true, expect.any(Object))
})
it('should close dropdown when trigger is clicked again', async () => {
const onOpenChange = vi.fn()
render(<OperationDropdown {...defaultProps} onOpenChange={onOpenChange} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
- expect(onOpenChange).toHaveBeenLastCalledWith(false)
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ expect(onOpenChange).toHaveBeenLastCalledWith(false, expect.any(Object))
})
})
@@ -174,7 +62,7 @@ describe('OperationDropdown', () => {
const onEdit = vi.fn()
render(<OperationDropdown {...defaultProps} onEdit={onEdit} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
fireEvent.click(screen.getByText('tools.mcp.operation.edit'))
expect(onEdit).toHaveBeenCalledTimes(1)
})
@@ -183,7 +71,7 @@ describe('OperationDropdown', () => {
const onRemove = vi.fn()
render(<OperationDropdown {...defaultProps} onRemove={onRemove} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
fireEvent.click(screen.getByText('tools.mcp.operation.remove'))
expect(onRemove).toHaveBeenCalledTimes(1)
})
@@ -192,20 +80,20 @@ describe('OperationDropdown', () => {
const onOpenChange = vi.fn()
render(<OperationDropdown {...defaultProps} onOpenChange={onOpenChange} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
onOpenChange.mockClear()
fireEvent.click(screen.getByText('tools.mcp.operation.edit'))
- expect(onOpenChange).toHaveBeenCalledWith(false)
+ expect(onOpenChange).toHaveBeenCalledWith(false, expect.any(Object))
})
it('should close dropdown after remove is clicked', () => {
const onOpenChange = vi.fn()
render(<OperationDropdown {...defaultProps} onOpenChange={onOpenChange} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
onOpenChange.mockClear()
fireEvent.click(screen.getByText('tools.mcp.operation.remove'))
- expect(onOpenChange).toHaveBeenCalledWith(false)
+ expect(onOpenChange).toHaveBeenCalledWith(false, expect.any(Object))
})
})
@@ -213,7 +101,7 @@ describe('OperationDropdown', () => {
it('should have correct dropdown width', () => {
render(<OperationDropdown {...defaultProps} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
const dropdown = document.querySelector('.w-\\[160px\\]')
expect(dropdown).toBeInTheDocument()
})
@@ -221,8 +109,8 @@ describe('OperationDropdown', () => {
it('should render dropdown content through the shared popup shell', () => {
render(<OperationDropdown {...defaultProps} />)
- fireEvent.click(screen.getByTestId('dropdown-trigger'))
- expect(screen.getByTestId('dropdown-content')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ expect(screen.getByRole('menu')).toBeInTheDocument()
})
})
diff --git a/web/app/components/tools/workflow-tool/__tests__/configure-button.spec.tsx b/web/app/components/tools/workflow-tool/__tests__/configure-button.spec.tsx
index f4785651839..3f71d9926d9 100644
--- a/web/app/components/tools/workflow-tool/__tests__/configure-button.spec.tsx
+++ b/web/app/components/tools/workflow-tool/__tests__/configure-button.spec.tsx
@@ -7,8 +7,6 @@ import WorkflowToolConfigureButton from '../configure-button'
import { WorkflowToolDrawer } from '../index'
import MethodSelector from '../method-selector'
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
// Mock Next.js navigation
const mockPush = vi.fn()
vi.mock('@/next/navigation', () => ({
@@ -1316,11 +1314,11 @@ describe('MethodSelector', () => {
// Act
render(<MethodSelector {...props} />)
- await user.click(screen.getByTestId('popover-trigger'))
+ await user.click(screen.getByRole('button'))
// Assert
// Assert
- expect(screen.getByTestId('popover-content'))!.toBeInTheDocument()
+ expect(screen.getByText('tools.createTool.toolInput.methodParameterTip')).toBeInTheDocument()
})
it('should call onChange with llm when parameter option clicked', async () => {
@@ -1334,7 +1332,7 @@ describe('MethodSelector', () => {
// Act
render(<MethodSelector {...props} />)
- await user.click(screen.getByTestId('popover-trigger'))
+ await user.click(screen.getByRole('button'))
const paramOption = screen.getAllByText('tools.createTool.toolInput.methodParameter')[0]
await user.click(paramOption!)
@@ -1354,7 +1352,7 @@ describe('MethodSelector', () => {
// Act
render(<MethodSelector {...props} />)
- await user.click(screen.getByTestId('popover-trigger'))
+ await user.click(screen.getByRole('button'))
const settingOption = screen.getByText('tools.createTool.toolInput.methodSetting')
await user.click(settingOption)
@@ -1373,51 +1371,17 @@ describe('MethodSelector', () => {
// Act
render(<MethodSelector {...props} />)
+ const trigger = screen.getByRole('button')
// First click - open
- await user.click(screen.getByTestId('popover-trigger'))
- expect(screen.getByTestId('popover-content'))!.toBeInTheDocument()
+ await user.click(trigger)
+ expect(screen.getByText('tools.createTool.toolInput.methodParameterTip')).toBeInTheDocument()
// Second click - close
- await user.click(screen.getByTestId('popover-trigger'))
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
- })
- })
-
- // Props Tests (REQUIRED)
- describe('Props', () => {
- it('should show check icon for selected llm value', async () => {
- // Arrange
- const user = userEvent.setup()
- const props = {
- value: 'llm',
- onChange: vi.fn(),
- }
-
- // Act
- render(<MethodSelector {...props} />)
- await user.click(screen.getByTestId('popover-trigger'))
-
- // Assert - the first option (llm) should have a check icon container
- const content = screen.getByTestId('popover-content')
- expect(content)!.toBeInTheDocument()
- })
-
- it('should show check icon for selected form value', async () => {
- // Arrange
- const user = userEvent.setup()
- const props = {
- value: 'form',
- onChange: vi.fn(),
- }
-
- // Act
- render(<MethodSelector {...props} />)
- await user.click(screen.getByTestId('popover-trigger'))
-
- // Assert
- const content = screen.getByTestId('popover-content')
- expect(content)!.toBeInTheDocument()
+ await user.click(trigger)
+ expect(
+ screen.queryByText('tools.createTool.toolInput.methodParameterTip'),
+ ).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/workflow-app/components/workflow-onboarding-modal/__tests__/index.spec.tsx b/web/app/components/workflow-app/components/workflow-onboarding-modal/__tests__/index.spec.tsx
index 465b5c1b640..44546519cc1 100644
--- a/web/app/components/workflow-app/components/workflow-onboarding-modal/__tests__/index.spec.tsx
+++ b/web/app/components/workflow-app/components/workflow-onboarding-modal/__tests__/index.spec.tsx
@@ -1,33 +1,8 @@
-import type { ReactNode } from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BlockEnum } from '@/app/components/workflow/types'
import WorkflowOnboardingModal from '../index'
-vi.mock('@/app/components/workflow/block-selector', () => ({
- default: ({
- open,
- onSelect,
- trigger,
- }: {
- open?: boolean
- onSelect: (type: BlockEnum, config?: Record<string, unknown>) => void
- trigger?: ((open: boolean) => ReactNode) | ReactNode
- }) => (
- <div>
- {typeof trigger === 'function' ? trigger(Boolean(open)) : trigger}
- {open && (
- <button
- type="button"
- onClick={() => onSelect(BlockEnum.TriggerWebhook, { config: 'test' })}
- >
- Select Trigger Webhook
- </button>
- )}
- </div>
- ),
-}))
-
describe('WorkflowOnboardingModal', () => {
it('only renders while onboarding is open', () => {
const props = { onClose: vi.fn(), onSelectStartNode: vi.fn() }
@@ -50,20 +25,6 @@ describe('WorkflowOnboardingModal', () => {
expect(onSelectStartNode).toHaveBeenCalledWith(BlockEnum.Start)
})
-
- it('forwards trigger configuration', async () => {
- const user = userEvent.setup()
- const onSelectStartNode = vi.fn()
- render(
- <WorkflowOnboardingModal isShow onClose={vi.fn()} onSelectStartNode={onSelectStartNode} />,
- )
-
- await user.click(screen.getByText('workflow.onboarding.trigger'))
- await user.click(screen.getByRole('button', { name: 'Select Trigger Webhook' }))
-
- expect(onSelectStartNode).toHaveBeenCalledWith(BlockEnum.TriggerWebhook, { config: 'test' })
- })
-
it('closes from the dialog control', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
diff --git a/web/app/components/workflow-app/components/workflow-onboarding-modal/__tests__/start-node-selection-panel.spec.tsx b/web/app/components/workflow-app/components/workflow-onboarding-modal/__tests__/start-node-selection-panel.spec.tsx
index 8c91753401b..68ce6dd783e 100644
--- a/web/app/components/workflow-app/components/workflow-onboarding-modal/__tests__/start-node-selection-panel.spec.tsx
+++ b/web/app/components/workflow-app/components/workflow-onboarding-modal/__tests__/start-node-selection-panel.spec.tsx
@@ -1,37 +1,7 @@
-import type { ReactNode } from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { BlockEnum } from '@/app/components/workflow/types'
import StartNodeSelectionPanel from '../start-node-selection-panel'
-vi.mock('@/app/components/workflow/block-selector', () => ({
- default: ({
- open,
- onOpenChange,
- onSelect,
- trigger,
- }: {
- open: boolean
- onOpenChange: (open: boolean) => void
- onSelect: (type: BlockEnum) => void
- trigger: (() => ReactNode) | ReactNode
- }) => (
- <div>
- {typeof trigger === 'function' ? trigger() : trigger}
- {open && (
- <div>
- <button type="button" onClick={() => onSelect(BlockEnum.TriggerSchedule)}>
- Select Schedule
- </button>
- <button type="button" onClick={() => onOpenChange(false)}>
- Close selector
- </button>
- </div>
- )}
- </div>
- ),
-}))
-
describe('StartNodeSelectionPanel', () => {
it('selects a user input start node', async () => {
const user = userEvent.setup()
@@ -44,32 +14,4 @@ describe('StartNodeSelectionPanel', () => {
expect(onSelectUserInput).toHaveBeenCalledTimes(1)
})
-
- it('selects a trigger start node and closes the selector', async () => {
- const user = userEvent.setup()
- const onSelectTrigger = vi.fn()
- render(
- <StartNodeSelectionPanel onSelectUserInput={vi.fn()} onSelectTrigger={onSelectTrigger} />,
- )
-
- await user.click(screen.getByText('workflow.onboarding.trigger'))
- await user.click(screen.getByRole('button', { name: 'Select Schedule' }))
-
- expect(onSelectTrigger).toHaveBeenCalledWith(BlockEnum.TriggerSchedule, undefined)
- expect(screen.queryByRole('button', { name: 'Select Schedule' })).not.toBeInTheDocument()
- })
-
- it('closes the trigger selector without selecting a node', async () => {
- const user = userEvent.setup()
- const onSelectTrigger = vi.fn()
- render(
- <StartNodeSelectionPanel onSelectUserInput={vi.fn()} onSelectTrigger={onSelectTrigger} />,
- )
-
- await user.click(screen.getByText('workflow.onboarding.trigger'))
- await user.click(screen.getByRole('button', { name: 'Close selector' }))
-
- expect(onSelectTrigger).not.toHaveBeenCalled()
- expect(screen.queryByRole('button', { name: 'Select Schedule' })).not.toBeInTheDocument()
- })
})
diff --git a/web/app/components/workflow/__tests__/custom-edge.spec.tsx b/web/app/components/workflow/__tests__/custom-edge.spec.tsx
index eaff72bfe0c..d7a61199c20 100644
--- a/web/app/components/workflow/__tests__/custom-edge.spec.tsx
+++ b/web/app/components/workflow/__tests__/custom-edge.spec.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
import { Position } from 'reactflow'
import { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'
import CustomEdge from '../custom-edge'
@@ -7,7 +7,6 @@ import { BlockEnum, NodeRunningStatus } from '../types'
const mockUseAvailableBlocks = vi.hoisted(() => vi.fn())
const mockUseNodesInteractions = vi.hoisted(() => vi.fn())
-const mockBlockSelector = vi.hoisted(() => vi.fn())
const mockGradientRender = vi.hoisted(() => vi.fn())
vi.mock('reactflow', () => ({
@@ -59,30 +58,6 @@ vi.mock('../hooks/use-nodes-interactions', async (importOriginal) => {
}
})
-vi.mock('@/app/components/workflow/block-selector', () => ({
- __esModule: true,
- default: (props: {
- open: boolean
- onOpenChange: (open: boolean) => void
- onSelect: (nodeType: string, pluginDefaultValue?: Record<string, unknown>) => void
- availableBlocksTypes: string[]
- }) => {
- mockBlockSelector(props)
- return (
- <button
- type="button"
- data-testid="block-selector"
- onClick={() => {
- props.onOpenChange(true)
- props.onSelect('llm', { provider: 'openai' })
- }}
- >
- {props.availableBlocksTypes.join(',')}
- </button>
- )
- },
-}))
-
vi.mock('@/app/components/workflow/custom-edge-linear-gradient-render', () => ({
__esModule: true,
default: (props: { id: string; startColor: string; stopColor: string }) => {
@@ -106,7 +81,7 @@ describe('CustomEdge', () => {
})
})
- it('should render a gradient edge and insert a node between the source and target', () => {
+ it('should render a gradient edge and its real insert-node trigger', () => {
render(
<CustomEdge
id="edge-1"
@@ -149,27 +124,12 @@ describe('CustomEdge', () => {
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-stroke', 'url(#edge-1)')
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-opacity', '0.3')
expect(screen.getByTestId('base-edge')).toHaveAttribute('data-dasharray', '8 8')
- expect(screen.getByTestId('block-selector')).toHaveTextContent('llm')
- expect(screen.getByTestId('block-selector').parentElement).toHaveStyle({
+ const addBlockTrigger = screen.getByRole('button', { name: 'workflow.common.addBlock' })
+ expect(addBlockTrigger.parentElement).toHaveStyle({
transform: 'translate(-50%, -50%) translate(24px, 48px)',
opacity: '0.7',
zIndex: '1001',
})
-
- fireEvent.click(screen.getByTestId('block-selector'))
-
- expect(mockHandleNodeAdd).toHaveBeenCalledWith(
- {
- nodeType: 'llm',
- pluginDefaultValue: { provider: 'openai' },
- },
- {
- prevNodeId: 'source-node',
- prevNodeSourceHandle: 'source',
- nextNodeId: 'target-node',
- nextNodeTargetHandle: 'target',
- },
- )
})
it('should prefer the running stroke color when the edge is selected', () => {
@@ -258,7 +218,9 @@ describe('CustomEdge', () => {
'data-stroke',
'var(--color-workflow-link-line-normal)',
)
- expect(screen.getByTestId('block-selector').parentElement).toHaveStyle({
+ expect(
+ screen.getByRole('button', { name: 'workflow.common.addBlock' }).parentElement,
+ ).toHaveStyle({
opacity: '0',
pointerEvents: 'none',
})
diff --git a/web/app/components/workflow/comment/comment-input.spec.tsx b/web/app/components/workflow/comment/comment-input.spec.tsx
index 8d498d3fc63..0ec7cdcd4cb 100644
--- a/web/app/components/workflow/comment/comment-input.spec.tsx
+++ b/web/app/components/workflow/comment/comment-input.spec.tsx
@@ -40,11 +40,6 @@ vi.mock('@/context/account-state', async () => {
return createAccountStateModuleMock(() => mockConsoleState)
})
-vi.mock('@langgenius/dify-ui/avatar', () => ({
- Avatar: ({ name }: { name: string }) => <div data-testid="avatar">{name}</div>,
- default: ({ name }: { name: string }) => <div data-testid="avatar">{name}</div>,
-}))
-
vi.mock('./mention-input', () => ({
MentionInput: ((props: MentionInputProps) => {
mentionInputProps = props
diff --git a/web/app/components/workflow/comment/mention-input.spec.tsx b/web/app/components/workflow/comment/mention-input.spec.tsx
index 70cda743c4d..0483112c6f2 100644
--- a/web/app/components/workflow/comment/mention-input.spec.tsx
+++ b/web/app/components/workflow/comment/mention-input.spec.tsx
@@ -46,10 +46,6 @@ vi.mock('../store', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/avatar', () => ({
- Avatar: ({ name }: { name: string }) => <div data-testid="mention-avatar">{name}</div>,
-}))
-
const mentionUsers: UserProfile[] = [
{
id: 'user-2',
diff --git a/web/app/components/workflow/comment/thread.spec.tsx b/web/app/components/workflow/comment/thread.spec.tsx
index bc8866cbb15..124d5ea96b9 100644
--- a/web/app/components/workflow/comment/thread.spec.tsx
+++ b/web/app/components/workflow/comment/thread.spec.tsx
@@ -1,5 +1,6 @@
import type { WorkflowCommentDetail } from '@/app/components/workflow/comment/types'
import { fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { render } from '@/test/console/render'
import { CommentThread } from './thread'
@@ -66,45 +67,6 @@ vi.mock('@/app/components/base/inline-delete-confirm', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/avatar', () => ({
- Avatar: ({ name }: { name: string }) => <div data-testid="avatar">{name}</div>,
- AvatarRoot: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="avatar-root">{children}</div>
- ),
- AvatarImage: ({ alt }: { alt: string }) => <div data-testid="avatar-image">{alt}</div>,
- AvatarFallback: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="avatar-fallback">{children}</div>
- ),
-}))
-
-vi.mock('@langgenius/dify-ui/dropdown-menu', () => ({
- DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DropdownMenuTrigger: ({ children, ...props }: React.ComponentProps<'button'>) => (
- <button type="button" {...props}>
- {children}
- </button>
- ),
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- TooltipTrigger: ({
- children,
- render,
- ...props
- }: React.ComponentProps<'button'> & { children?: React.ReactNode; render?: React.ReactNode }) => {
- if (render) return <>{render}</>
-
- return (
- <button type="button" {...props}>
- {children}
- </button>
- )
- },
- TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
-}))
-
vi.mock('./mention-input', () => ({
MentionInput: ({
placeholder,
@@ -264,6 +226,7 @@ describe('CommentThread', () => {
})
it('supports editing and direct deleting an existing reply', async () => {
+ const user = userEvent.setup()
const onReplyEdit = vi.fn()
const onReplyDeleteDirect = vi.fn()
@@ -276,18 +239,20 @@ describe('CommentThread', () => {
/>,
)
- fireEvent.click(screen.getByText('workflow.comments.actions.editReply'))
- fireEvent.click(screen.getByText('submit-workflow.comments.placeholder.editReply'))
+ await user.click(screen.getByLabelText('workflow.comments.aria.replyActions'))
+ await user.click(await screen.findByText('workflow.comments.actions.editReply'))
+ await user.click(screen.getByText('submit-workflow.comments.placeholder.editReply'))
await waitFor(() => {
expect(onReplyEdit).toHaveBeenCalledWith('reply-1', 'first reply', ['user-2'])
})
await waitFor(() => {
- expect(screen.getByText('workflow.comments.actions.deleteReply')).toBeInTheDocument()
+ expect(screen.getByLabelText('workflow.comments.aria.replyActions')).toBeInTheDocument()
})
- fireEvent.click(screen.getByText('workflow.comments.actions.deleteReply'))
- fireEvent.click(screen.getByTestId('confirm-delete-reply'))
+ await user.click(screen.getByLabelText('workflow.comments.aria.replyActions'))
+ await user.click(await screen.findByText('workflow.comments.actions.deleteReply'))
+ await user.click(screen.getByTestId('confirm-delete-reply'))
expect(onReplyDeleteDirect).toHaveBeenCalledWith('reply-1')
})
diff --git a/web/app/components/workflow/header/__tests__/test-run-menu-helpers.spec.tsx b/web/app/components/workflow/header/__tests__/test-run-menu-helpers.spec.tsx
index 09bc35a15f9..de2e8c94238 100644
--- a/web/app/components/workflow/header/__tests__/test-run-menu-helpers.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/test-run-menu-helpers.spec.tsx
@@ -1,5 +1,5 @@
-import type * as React from 'react'
import type { TriggerOption } from '../test-run-menu'
+import { DropdownMenu, DropdownMenuContent } from '@langgenius/dify-ui/dropdown-menu'
import { fireEvent, render, renderHook, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { TriggerType } from '../test-run-menu'
@@ -10,53 +10,6 @@ import {
useShortcutMenu,
} from '../test-run-menu-helpers'
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- open: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div>{children}</div>
- </DropdownMenuContext>
- ),
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => {
- const { open } = useDropdownMenuContext()
- return open ? <div>{children}</div> : null
- },
- DropdownMenuItem: ({
- children,
- onClick,
- className,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- className?: string
- }) => (
- <button type="button" className={className} onClick={onClick}>
- {children}
- </button>
- ),
- }
-})
-
const createOption = (overrides: Partial<TriggerOption> = {}): TriggerOption => ({
id: 'user-input',
type: TriggerType.UserInput,
@@ -79,7 +32,13 @@ describe('test-run-menu helpers', () => {
expect(getNormalizedShortcutKey(new KeyboardEvent('keydown', { key: '`' }))).toBe('~')
expect(getNormalizedShortcutKey(new KeyboardEvent('keydown', { key: '1' }))).toBe('1')
- render(<OptionRow option={option} shortcutKey="1" onSelect={onSelect} />)
+ render(
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <OptionRow option={option} shortcutKey="1" onSelect={onSelect} />
+ </DropdownMenuContent>
+ </DropdownMenu>,
+ )
expect(screen.getByText('1')).toBeInTheDocument()
diff --git a/web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx b/web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx
index e5dd454346a..cfbd49b1cb7 100644
--- a/web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx
@@ -5,104 +5,6 @@ import { act } from 'react'
import * as React from 'react'
import TestRunMenu, { TriggerType } from '../test-run-menu'
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- open: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div>{children}</div>
- </DropdownMenuContext>
- ),
- DropdownMenuTrigger: ({
- children,
- render,
- }: {
- children: React.ReactNode
- render?: React.ReactElement<{ children?: React.ReactNode }>
- }) => {
- const { open, setOpen } = useDropdownMenuContext()
-
- if (render) {
- return React.cloneElement(
- render,
- { onClick: () => setOpen(!open) } as Record<string, unknown>,
- children ?? render.props.children,
- )
- }
-
- return (
- <button type="button" onClick={() => setOpen(!open)}>
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => {
- const { open } = useDropdownMenuContext()
- return open ? <div>{children}</div> : null
- },
- DropdownMenuGroup: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DropdownMenuLabel: ({
- children,
- className,
- }: {
- children: React.ReactNode
- className?: string
- }) => <div className={className}>{children}</div>,
- DropdownMenuGroupLabel: ({
- children,
- className,
- }: {
- children: React.ReactNode
- className?: string
- }) => <div className={className}>{children}</div>,
- DropdownMenuSeparator: ({ className }: { className?: string }) => (
- <div className={className} data-testid="dropdown-separator" />
- ),
- DropdownMenuItem: ({
- children,
- onClick,
- className,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- className?: string
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- className={className}
- onClick={(event) => {
- onClick?.(event)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- }
-})
-
const createOption = (overrides: Partial<TriggerOption> = {}): TriggerOption => ({
id: 'user-input',
type: TriggerType.UserInput,
diff --git a/web/app/components/workflow/header/__tests__/version-history-button.spec.tsx b/web/app/components/workflow/header/__tests__/version-history-button.spec.tsx
index 791db282d43..d3e10a79f23 100644
--- a/web/app/components/workflow/header/__tests__/version-history-button.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/version-history-button.spec.tsx
@@ -1,4 +1,5 @@
import { act, fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { VersionHistoryButton } from '../version-history-button'
let mockTheme: 'light' | 'dark' = 'light'
@@ -29,12 +30,6 @@ vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
}
})
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- TooltipTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,
- TooltipContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
describe('VersionHistoryButton', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -66,9 +61,10 @@ describe('VersionHistoryButton', () => {
})
it('should render the tooltip popup content on hover', async () => {
+ const user = userEvent.setup()
render(<VersionHistoryButton onClick={vi.fn()} />)
- fireEvent.mouseEnter(screen.getByRole('button'))
+ await user.hover(screen.getByRole('button'))
expect(await screen.findByText('workflow.common.versionHistory')).toBeInTheDocument()
})
diff --git a/web/app/components/workflow/header/__tests__/view-history.spec.tsx b/web/app/components/workflow/header/__tests__/view-history.spec.tsx
index e2b4553fef3..46233c0ecfd 100644
--- a/web/app/components/workflow/header/__tests__/view-history.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/view-history.spec.tsx
@@ -69,33 +69,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
},
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button {...props}>{children}</button>
- ),
-}))
-
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children?: React.ReactNode }) => <>{children}</>,
- TooltipTrigger: ({
- children,
- render,
- }: {
- children?: React.ReactNode
- render?: React.ReactElement
- }) => {
- if (render && React.isValidElement(render)) {
- const renderElement = render as React.ReactElement<{ children?: React.ReactNode }>
- return React.cloneElement(renderElement, renderElement.props, children)
- }
-
- return <>{children}</>
- },
- TooltipContent: ({ children }: { children?: React.ReactNode }) => <>{children}</>,
-}))
-
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
vi.mock('../../utils', async () => {
const actual = await vi.importActual<typeof import('../../utils')>('../../utils')
return {
diff --git a/web/app/components/workflow/header/checklist/__tests__/index.spec.tsx b/web/app/components/workflow/header/checklist/__tests__/index.spec.tsx
index e79c66da2ef..0bc22b8c819 100644
--- a/web/app/components/workflow/header/checklist/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/header/checklist/__tests__/index.spec.tsx
@@ -1,6 +1,5 @@
-import type { ReactNode } from 'react'
import type { ChecklistItem } from '../../../hooks/use-checklist'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { BlockEnum } from '../../../types'
import WorkflowChecklist from '../index'
@@ -27,14 +26,6 @@ let mockChecklistItems: ChecklistItem[] = [
const mockHandleNodeSelect = vi.fn()
const mockSetOpenInlineAgentPanelNodeId = vi.fn()
-type PopoverProps = {
- children: ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
-}
-
-let latestOnOpenChange: PopoverProps['onOpenChange']
-
vi.mock('reactflow', () => ({
useEdges: () => [],
}))
@@ -73,24 +64,6 @@ vi.mock('../../../hooks-store/store', () => ({
}),
}))
-vi.mock('@langgenius/dify-ui/popover', () => ({
- Popover: ({ children, onOpenChange }: PopoverProps) => {
- latestOnOpenChange = onOpenChange
- return <div data-testid="popover">{children}</div>
- },
- PopoverTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,
- PopoverContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- PopoverTitle: ({ children, className }: { children: ReactNode; className?: string }) => (
- <h2 className={className}>{children}</h2>
- ),
- PopoverDescription: ({ children, className }: { children: ReactNode; className?: string }) => (
- <p className={className}>{children}</p>
- ),
- PopoverClose: ({ children, className }: { children: ReactNode; className?: string }) => (
- <button className={className}>{children}</button>
- ),
-}))
-
vi.mock('../plugin-group', () => ({
ChecklistPluginGroup: ({ items }: { items: Array<{ title: string }> }) => (
<div data-testid="plugin-group">{items.map((item) => item.title).join(',')}</div>
@@ -114,7 +87,6 @@ vi.mock('../node-group', () => ({
describe('WorkflowChecklist', () => {
beforeEach(() => {
vi.clearAllMocks()
- latestOnOpenChange = undefined
mockChecklistItems = [
{
id: 'plugin-1',
@@ -135,22 +107,26 @@ describe('WorkflowChecklist', () => {
]
})
- it('should split checklist items into plugin and node groups and delegate clicks to node selection by default', () => {
+ it('should split checklist items into plugin and node groups and delegate clicks to node selection by default', async () => {
+ const user = userEvent.setup()
render(<WorkflowChecklist disabled={false} />)
expect(screen.getByText('2')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'workflow.panel.checklist' }))
expect(screen.getByTestId('plugin-group')).toHaveTextContent('Missing Plugin')
- fireEvent.click(screen.getByTestId('node-group-Broken Node'))
+ await user.click(screen.getByTestId('node-group-Broken Node'))
expect(mockHandleNodeSelect).toHaveBeenCalledWith('node-1')
expect(mockSetOpenInlineAgentPanelNodeId).not.toHaveBeenCalled()
})
- it('should use the custom item click handler when provided', () => {
+ it('should use the custom item click handler when provided', async () => {
+ const user = userEvent.setup()
const onItemClick = vi.fn()
render(<WorkflowChecklist disabled={false} onItemClick={onItemClick} />)
- fireEvent.click(screen.getByTestId('node-group-Broken Node'))
+ await user.click(screen.getByRole('button', { name: 'workflow.panel.checklist' }))
+ await user.click(screen.getByTestId('node-group-Broken Node'))
expect(onItemClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'node-1' }))
expect(mockHandleNodeSelect).not.toHaveBeenCalled()
@@ -166,25 +142,26 @@ describe('WorkflowChecklist', () => {
}
render(<WorkflowChecklist disabled={false} />)
+ await user.click(screen.getByRole('button', { name: 'workflow.panel.checklist' }))
await user.click(screen.getByTestId('node-group-Inline Agent'))
expect(mockHandleNodeSelect).toHaveBeenCalledWith('node-1')
expect(mockSetOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('node-1')
})
- it('should render the resolved state when there are no checklist warnings', () => {
+ it('should render the resolved state when there are no checklist warnings', async () => {
+ const user = userEvent.setup()
mockChecklistItems = []
render(<WorkflowChecklist disabled={false} />)
+ await user.click(screen.getByRole('button', { name: 'workflow.panel.checklist' }))
expect(screen.getByText(/checklistResolved/i)).toBeInTheDocument()
})
it('should ignore popover open changes when the checklist is disabled', () => {
render(<WorkflowChecklist disabled={true} />)
- latestOnOpenChange?.(true)
-
expect(screen.getByText('2').closest('button')).toBeDisabled()
})
})
diff --git a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
index 03430534151..42e84c81360 100644
--- a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
+++ b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
@@ -4,7 +4,7 @@ import {
DropdownMenuContent,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { useHooksStore } from '@/app/components/workflow/hooks-store'
@@ -16,35 +16,8 @@ import { useAvailableBlocks } from '../../hooks/use-available-blocks'
import { useNodesInteractions } from '../../hooks/use-nodes-interactions'
import { useNodeMetaData } from '../../hooks/use-nodes-meta-data'
import { useIsChatMode, useNodesReadOnly } from '../../hooks/use-workflow'
-import { ChangeBlockMenuTrigger } from '../change-block-menu-trigger'
import { NodeActionsDropdownContent } from '../dropdown-content'
-vi.mock('@/app/components/workflow/block-selector', () => ({
- default: ({
- trigger,
- onSelect,
- availableBlocksTypes,
- showStartTab,
- ignoreNodeIds,
- forceEnableStartTab,
- allowUserInputSelection,
- isolateKeyboardEvents,
- }: any) => (
- <div>
- <div>{typeof trigger === 'function' ? trigger({}, { open: false }) : trigger}</div>
- <div>{`available:${(availableBlocksTypes || []).join(',')}`}</div>
- <div>{`show-start:${String(showStartTab)}`}</div>
- <div>{`ignore:${(ignoreNodeIds || []).join(',')}`}</div>
- <div>{`force-start:${String(forceEnableStartTab)}`}</div>
- <div>{`allow-start:${String(allowUserInputSelection)}`}</div>
- <div>{`isolate-keyboard:${String(isolateKeyboardEvents)}`}</div>
- <button type="button" onClick={() => onSelect(BlockEnum.HttpRequest)}>
- select-http
- </button>
- </div>
- ),
-}))
-
vi.mock('../../hooks/use-available-blocks', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../hooks/use-available-blocks')>()
@@ -179,89 +152,6 @@ describe('node actions menu details', () => {
mockUseAllWorkflowTools.mockReturnValue({ data: [] } as any)
})
- it('should select a replacement block through ChangeBlockMenuTrigger', async () => {
- const user = userEvent.setup()
- render(
- <ChangeBlockMenuTrigger
- nodeId="node-1"
- nodeData={{ type: BlockEnum.Code } as any}
- sourceHandle="source"
- />,
- )
-
- await user.click(screen.getByText('select-http'))
-
- expect(screen.getByText('available:http-request')).toBeInTheDocument()
- expect(screen.getByText('show-start:true')).toBeInTheDocument()
- expect(screen.getByText('ignore:')).toBeInTheDocument()
- expect(screen.getByText('force-start:false')).toBeInTheDocument()
- expect(screen.getByText('allow-start:false')).toBeInTheDocument()
- expect(screen.getByText('isolate-keyboard:true')).toBeInTheDocument()
- expect(handleNodeChange).toHaveBeenCalledWith(
- 'node-1',
- BlockEnum.HttpRequest,
- 'source',
- undefined,
- )
- })
-
- it('should expose trigger and start-node specific block selector options', () => {
- mockUseAvailableBlocks.mockReturnValueOnce({
- getAvailableBlocks: vi.fn(() => ({
- availablePrevBlocks: [],
- availableNextBlocks: [BlockEnum.HttpRequest],
- })),
- availablePrevBlocks: [],
- availableNextBlocks: [BlockEnum.HttpRequest],
- } as ReturnType<typeof useAvailableBlocks>)
- mockUseIsChatMode.mockReturnValueOnce(true)
- mockUseHooksStore.mockImplementationOnce((selector: any) =>
- selector({ configsMap: { flowType: FlowType.appFlow } }),
- )
- mockUseNodes.mockReturnValueOnce([] as any)
-
- const { rerender } = render(
- <ChangeBlockMenuTrigger
- nodeId="trigger-node"
- nodeData={{ type: BlockEnum.TriggerWebhook } as any}
- sourceHandle="source"
- />,
- )
-
- expect(screen.getByText('available:http-request')).toBeInTheDocument()
- expect(screen.getByText('show-start:true')).toBeInTheDocument()
- expect(screen.getByText('ignore:trigger-node')).toBeInTheDocument()
- expect(screen.getByText('allow-start:true')).toBeInTheDocument()
-
- mockUseAvailableBlocks.mockReturnValueOnce({
- getAvailableBlocks: vi.fn(() => ({
- availablePrevBlocks: [BlockEnum.Code],
- availableNextBlocks: [],
- })),
- availablePrevBlocks: [BlockEnum.Code],
- availableNextBlocks: [],
- } as ReturnType<typeof useAvailableBlocks>)
- mockUseHooksStore.mockImplementationOnce((selector: any) =>
- selector({ configsMap: { flowType: FlowType.ragPipeline } }),
- )
- mockUseNodes.mockReturnValueOnce([
- { id: 'start', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } as any },
- ] as any)
-
- rerender(
- <ChangeBlockMenuTrigger
- nodeId="start-node"
- nodeData={{ type: BlockEnum.Start } as any}
- sourceHandle="source"
- />,
- )
-
- expect(screen.getByText('available:code')).toBeInTheDocument()
- expect(screen.getByText('show-start:false')).toBeInTheDocument()
- expect(screen.getByText('ignore:start-node')).toBeInTheDocument()
- expect(screen.getByText('force-start:true')).toBeInTheDocument()
- })
-
it('should run, copy, duplicate, delete, and expose the help link', async () => {
const user = userEvent.setup()
const { store } = renderDropdownContent()
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
index 6d13e22f62e..30d69e86ad5 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
@@ -174,59 +174,6 @@ vi.mock('@/next/link', () => ({
</a>
),
}))
-vi.mock('@langgenius/dify-ui/popover', async () => {
- const React = await import('react')
- const PopoverContext = React.createContext({
- open: false,
- setOpen: (_open: boolean) => {},
- })
-
- const Popover = ({
- children,
- open: controlledOpen,
- onOpenChange,
- }: {
- children: React.ReactNode
- open?: boolean
- onOpenChange?: (open: boolean) => void
- }) => {
- const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false)
- const isControlled = controlledOpen !== undefined
- const open = isControlled ? !!controlledOpen : uncontrolledOpen
- const setOpen = (nextOpen: boolean) => {
- if (!isControlled) setUncontrolledOpen(nextOpen)
- onOpenChange?.(nextOpen)
- }
-
- return <PopoverContext value={{ open, setOpen }}>{children}</PopoverContext>
- }
-
- const PopoverTrigger = ({ render }: { render: React.ReactNode }) => {
- const { open, setOpen } = React.use(PopoverContext)
- return (
- <div data-testid="agent-strategy-trigger" onClick={() => setOpen(!open)}>
- {render}
- </div>
- )
- }
-
- const PopoverContent = ({ children }: { children: React.ReactNode }) => {
- const { open } = React.use(PopoverContext)
- return open ? <div data-testid="agent-strategy-popover">{children}</div> : null
- }
-
- return {
- Popover,
- PopoverTrigger,
- PopoverContent,
- }
-})
-
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- TooltipTrigger: ({ render }: { render: ReactNode }) => <div>{render}</div>,
- TooltipContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
const createStrategyDetail = (
name: string,
@@ -285,7 +232,11 @@ describe('AgentStrategySelector', () => {
render(<AgentStrategySelector onChange={vi.fn()} />)
- await user.click(screen.getByTestId('agent-strategy-trigger'))
+ await user.click(
+ screen
+ .getByText(/(?:^|\.)nodes\.agent\.strategy\.selectTip(?=$|:)/)
+ .closest('[aria-haspopup]')!,
+ )
expect(screen.getByText('alpha')).toBeInTheDocument()
expect(screen.getByText('beta')).toBeInTheDocument()
@@ -315,7 +266,11 @@ describe('AgentStrategySelector', () => {
render(<AgentStrategySelector onChange={onChange} />)
- await user.click(screen.getByTestId('agent-strategy-trigger'))
+ await user.click(
+ screen
+ .getByText(/(?:^|\.)nodes\.agent\.strategy\.selectTip(?=$|:)/)
+ .closest('[aria-haspopup]')!,
+ )
await user.click(screen.getByRole('button', { name: 'select-alpha' }))
expect(onChange).toHaveBeenCalledWith({
@@ -326,10 +281,11 @@ describe('AgentStrategySelector', () => {
plugin_unique_identifier: 'provider/alpha',
meta: { version: '1.0.0' },
})
- expect(screen.queryByTestId('agent-strategy-popover')).not.toBeInTheDocument()
+ expect(screen.queryByTestId('tools-list')).not.toBeInTheDocument()
})
- it('renders the plugin-not-installed warning for external strategies', () => {
+ it('renders the plugin-not-installed warning for external strategies', async () => {
+ const user = userEvent.setup()
mocks.useStrategyInfo.mockReturnValue({
strategyStatus: {
plugin: {
@@ -354,7 +310,11 @@ describe('AgentStrategySelector', () => {
/>,
)
- expect(screen.getByText(/(?:^|\.)nodes\.agent\.pluginNotInstalled(?=$|:)/)).toBeInTheDocument()
+ await user.hover(document.querySelector('[data-base-ui-tooltip-trigger]')!)
+
+ expect(
+ await screen.findByText(/(?:^|\.)nodes\.agent\.pluginNotInstalled(?=$|:)/),
+ ).toBeInTheDocument()
expect(
screen.getByText(/(?:^|\.)nodes\.agent\.pluginNotInstalledDesc(?=$|:)/),
).toBeInTheDocument()
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsx
index 31ff755bfcf..ecfd4c09cc2 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsx
@@ -12,6 +12,8 @@ type MockHooksState = {
}
type MockStoreState = {
+ dataSourceList: unknown[]
+ nodes: unknown[]
shouldAutoOpenStartNodeSelector: boolean
setShouldAutoOpenStartNodeSelector?: (open: boolean) => void
setHasSelectedStartNode?: (selected: boolean) => void
@@ -32,6 +34,8 @@ const {
isReadOnly: false,
}
const mockStoreState: MockStoreState = {
+ dataSourceList: [],
+ nodes: [],
shouldAutoOpenStartNodeSelector: false,
setShouldAutoOpenStartNodeSelector: undefined,
setHasSelectedStartNode: undefined,
@@ -54,13 +58,6 @@ type HandleProps = {
onClick?: () => void
}
-type BlockSelectorProps = {
- open?: boolean
- onOpenChange?: (open: boolean) => void
- onSelect?: (type: BlockEnum, pluginDefaultValue?: { pluginId: string }) => void
- triggerClassName?: string
-}
-
vi.mock('reactflow', () => ({
Handle: ({ id, className, children, onClick }: HandleProps) => (
<div
@@ -76,33 +73,9 @@ vi.mock('reactflow', () => ({
Left: 'left',
Right: 'right',
},
-}))
-
-vi.mock('@/app/components/workflow/block-selector', () => ({
- default: ({ open = false, onOpenChange, onSelect, triggerClassName }: BlockSelectorProps) => (
- <div>
- <button
- type="button"
- className={triggerClassName}
- data-popup-open={open ? '' : undefined}
- onClick={(e) => {
- e.stopPropagation()
- onOpenChange?.(!open)
- }}
- >
- add-node
- </button>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation()
- onSelect?.(BlockEnum.Answer, { pluginId: 'plugin-1' })
- }}
- >
- select-node
- </button>
- </div>
- ),
+ useStoreApi: () => ({
+ getState: () => ({ getNodes: () => [] }),
+ }),
}))
vi.mock('../../../../hooks/use-available-blocks', async (importOriginal) => {
@@ -147,6 +120,36 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
+vi.mock('@/app/components/workflow/hooks-store', () => ({
+ useHooksStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ configsMap: { flowType: 'app-flow' },
+ availableNodesMetaData: { nodes: [] },
+ }),
+}))
+
+vi.mock('@/service/use-plugins', () => ({
+ useFeaturedToolsRecommendations: () => ({ plugins: [], isLoading: false }),
+ useFeaturedTriggersRecommendations: () => ({ plugins: [], isLoading: false }),
+}))
+
+vi.mock('@/service/use-triggers', () => ({
+ useAllTriggerPlugins: () => ({ data: [] }),
+ useInvalidateAllTriggerPlugins: () => vi.fn(),
+}))
+
+vi.mock('@/service/use-tools', () => ({
+ useAllBuiltInTools: () => ({ data: [] }),
+ useAllCustomTools: () => ({ data: [] }),
+ useAllWorkflowTools: () => ({ data: [] }),
+ useAllMCPTools: () => ({ data: [] }),
+ useInvalidateAllBuiltInTools: () => vi.fn(),
+}))
+
+vi.mock('@/app/components/plugins/marketplace/query', () => ({
+ useMarketplacePlugins: () => ({ data: undefined }),
+}))
+
const createNodeData = (overrides: Partial<CommonNodeType> = {}): CommonNodeType => ({
type: BlockEnum.Code,
title: 'Node',
@@ -155,9 +158,8 @@ const createNodeData = (overrides: Partial<CommonNodeType> = {}): CommonNodeType
...overrides,
})
-const getAddNodeButton = () => screen.getByRole('button', { name: 'add-node' })
-const queryAddNodeButton = () => screen.queryByRole('button', { name: 'add-node' })
-const getSelectNodeButton = () => screen.getByRole('button', { name: 'select-node' })
+const getAddNodeButton = () => screen.getByRole('button', { name: 'workflow.common.addBlock' })
+const queryAddNodeButton = () => screen.queryByRole('button', { name: 'workflow.common.addBlock' })
const renderTargetHandle = (dataOverrides: Partial<CommonNodeType> = {}) => {
return render(
@@ -203,7 +205,7 @@ describe('node-handle', () => {
// Target-side tests cover selector visibility, connection locking, and status rendering.
describe('NodeTargetHandle', () => {
- it('should toggle the target add trigger and select the next node', () => {
+ it('should toggle the target add trigger', () => {
renderTargetHandle()
const handle = screen.getByTestId('handle-target-handle')
@@ -223,19 +225,6 @@ describe('node-handle', () => {
fireEvent.click(handle)
expect(addNodeButton).not.toHaveAttribute('data-popup-open')
-
- fireEvent.click(getSelectNodeButton())
-
- expect(mockHandleNodeAdd).toHaveBeenCalledWith(
- {
- nodeType: BlockEnum.Answer,
- pluginDefaultValue: { pluginId: 'plugin-1' },
- },
- {
- nextNodeId: 'target-node',
- nextNodeTargetHandle: 'target-handle',
- },
- )
})
it('should not render the target add trigger when the handle is already connected', () => {
@@ -266,7 +255,7 @@ describe('node-handle', () => {
// Source-side tests cover selector opening paths, previous-node selection, and status styling.
describe('NodeSourceHandle', () => {
- it('should toggle the source add trigger and select the previous node', () => {
+ it('should toggle the source add trigger', () => {
renderSourceHandle()
const handle = screen.getByTestId('handle-source-handle')
@@ -279,19 +268,6 @@ describe('node-handle', () => {
expect(addNodeButton).toHaveAttribute('data-popup-open')
expect(addNodeButton).toHaveClass('pointer-events-none')
- fireEvent.click(getSelectNodeButton())
-
- expect(mockHandleNodeAdd).toHaveBeenCalledWith(
- {
- nodeType: BlockEnum.Answer,
- pluginDefaultValue: { pluginId: 'plugin-1' },
- },
- {
- prevNodeId: 'source-node',
- prevNodeSourceHandle: 'source-handle',
- },
- )
-
fireEvent.click(handle)
expect(addNodeButton).not.toHaveAttribute('data-popup-open')
diff --git a/web/app/components/workflow/nodes/_base/components/next-step/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/_base/components/next-step/__tests__/index.spec.tsx
index 6298dd450a5..51f2ef085fd 100644
--- a/web/app/components/workflow/nodes/_base/components/next-step/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/next-step/__tests__/index.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import type { Edge, Node } from '@/app/components/workflow/types'
import { screen } from '@testing-library/react'
import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
@@ -11,12 +10,6 @@ import { useToolIcon } from '../../../../../hooks/use-tool-icon'
import { useNodesReadOnly } from '../../../../../hooks/use-workflow'
import NextStep from '../index'
-vi.mock('@/app/components/workflow/block-selector', () => ({
- default: ({ trigger }: { trigger: ReactNode }) => {
- return <div data-testid="next-step-block-selector">{trigger}</div>
- },
-}))
-
vi.mock('../../../../../hooks/use-available-blocks', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../../../hooks/use-available-blocks')>()
diff --git a/web/app/components/workflow/nodes/_base/components/next-step/__tests__/operator.spec.tsx b/web/app/components/workflow/nodes/_base/components/next-step/__tests__/operator.spec.tsx
index 6462a10c694..eae00f53d9d 100644
--- a/web/app/components/workflow/nodes/_base/components/next-step/__tests__/operator.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/next-step/__tests__/operator.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import type { CommonNodeType } from '@/app/components/workflow/types'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -8,89 +7,6 @@ import { useAvailableBlocks } from '../../../../../hooks/use-available-blocks'
import { useNodesInteractions } from '../../../../../hooks/use-nodes-interactions'
import Operator from '../operator'
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- open: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div>{children}</div>
- </DropdownMenuContext>
- ),
- DropdownMenuTrigger: ({
- children,
- render,
- }: {
- children: ReactNode
- render?: React.ReactElement<{ children?: ReactNode }>
- }) => {
- const { open, setOpen } = useDropdownMenuContext()
- if (render) {
- return React.cloneElement(
- render,
- { onClick: () => setOpen(!open) } as Record<string, unknown>,
- children ?? render.props.children,
- )
- }
-
- return (
- <button type="button" onClick={() => setOpen(!open)}>
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({ children }: { children: ReactNode }) => {
- const { open } = useDropdownMenuContext()
- return open ? <div>{children}</div> : null
- },
- }
-})
-
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({
- children,
- className,
- onClick,
- }: {
- children: ReactNode
- className?: string
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- }) => (
- <button type="button" className={className} onClick={onClick}>
- {children}
- </button>
- ),
-}))
-
-vi.mock('@/app/components/workflow/block-selector', () => ({
- default: ({ trigger, onSelect }: { trigger: ReactNode; onSelect: (type: BlockEnum) => void }) => (
- <div>
- {trigger}
- <button type="button" onClick={() => onSelect(BlockEnum.HttpRequest)}>
- select-http
- </button>
- </div>
- ),
-}))
-
vi.mock('../../../../../hooks/use-available-blocks', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../../../hooks/use-available-blocks')>()
@@ -161,21 +77,6 @@ describe('NextStep operator', () => {
expect(screen.getByText('common.operation.delete')).toBeInTheDocument()
})
- it('changes the next-step block through the nested selector trigger', async () => {
- const user = userEvent.setup()
- render(<TestHarness />)
-
- await user.click(screen.getAllByRole('button')[0]!)
- await user.click(screen.getByText('select-http'))
-
- expect(mockHandleNodeChange).toHaveBeenCalledWith(
- 'node-1',
- BlockEnum.HttpRequest,
- 'source',
- undefined,
- )
- })
-
it('disconnects and deletes the next step from the menu', async () => {
const user = userEvent.setup()
render(<TestHarness />)
diff --git a/web/app/components/workflow/nodes/assigner/components/__tests__/operation-selector.spec.tsx b/web/app/components/workflow/nodes/assigner/components/__tests__/operation-selector.spec.tsx
index 4c2d7c4a011..63813c8a461 100644
--- a/web/app/components/workflow/nodes/assigner/components/__tests__/operation-selector.spec.tsx
+++ b/web/app/components/workflow/nodes/assigner/components/__tests__/operation-selector.spec.tsx
@@ -4,85 +4,6 @@ import { VarType } from '@/app/components/workflow/types'
import { WriteMode } from '../../types'
import OperationSelector from '../operation-selector'
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- open: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div>{children}</div>
- </DropdownMenuContext>
- ),
- DropdownMenuTrigger: ({
- children,
- className,
- disabled,
- }: {
- children: React.ReactNode
- className?: string
- disabled?: boolean
- }) => {
- const { open, setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- className={className}
- disabled={disabled}
- onClick={() => !disabled && setOpen(!open)}
- >
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => {
- const { open } = useDropdownMenuContext()
- return open ? <div>{children}</div> : null
- },
- DropdownMenuGroup: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DropdownMenuGroupLabel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DropdownMenuSeparator: () => <div data-testid="dropdown-separator" />,
- DropdownMenuItem: ({
- children,
- onClick,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- onClick={(event) => {
- onClick?.(event)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- }
-})
-
describe('assigner/operation-selector', () => {
it('shows numeric write modes and emits the selected operation', async () => {
const user = userEvent.setup()
diff --git a/web/app/components/workflow/nodes/data-source-empty/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/data-source-empty/__tests__/index.spec.tsx
index 8bde043261a..565c19c6321 100644
--- a/web/app/components/workflow/nodes/data-source-empty/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/data-source-empty/__tests__/index.spec.tsx
@@ -1,8 +1,5 @@
-import type { ComponentProps, ReactNode } from 'react'
-import type { OnSelectBlock } from '@/app/components/workflow/types'
+import type { ComponentProps } from 'react'
import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { BlockEnum } from '@/app/components/workflow/types'
import DataSourceEmptyNode from '../index'
const mockUseReplaceDataSourceNode = vi.hoisted(() => vi.fn())
@@ -11,29 +8,6 @@ vi.mock('../hooks', () => ({
useReplaceDataSourceNode: mockUseReplaceDataSourceNode,
}))
-vi.mock('@/app/components/workflow/block-selector', () => ({
- default: ({ onSelect, trigger }: { onSelect: OnSelectBlock; trigger: ReactNode }) => (
- <div>
- {trigger}
- <button
- type="button"
- onClick={() =>
- onSelect(BlockEnum.DataSource, {
- plugin_id: 'plugin-id',
- provider_type: 'local_file',
- provider_name: 'file',
- datasource_name: 'local-file',
- datasource_label: 'Local File',
- title: 'Local File',
- })
- }
- >
- select data source
- </button>
- </div>
- ),
-}))
-
type DataSourceEmptyNodeProps = ComponentProps<typeof DataSourceEmptyNode>
const createNodeProps = (): DataSourceEmptyNodeProps =>
@@ -69,26 +43,5 @@ describe('DataSourceEmptyNode', () => {
expect(screen.getByText('workflow.nodes.dataSource.add')).toBeInTheDocument()
expect(screen.getByText('workflow.blocks.datasource')).toBeInTheDocument()
})
-
- it('should forward block selections to the replace hook', async () => {
- const user = userEvent.setup()
- const handleReplaceNode = vi.fn()
- mockUseReplaceDataSourceNode.mockReturnValue({
- handleReplaceNode,
- })
-
- render(<DataSourceEmptyNode {...createNodeProps()} />)
-
- await user.click(screen.getByRole('button', { name: 'select data source' }))
-
- expect(handleReplaceNode).toHaveBeenCalledWith(BlockEnum.DataSource, {
- plugin_id: 'plugin-id',
- provider_type: 'local_file',
- provider_name: 'file',
- datasource_name: 'local-file',
- datasource_label: 'Local File',
- title: 'Local File',
- })
- })
})
})
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/button-style-dropdown.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/button-style-dropdown.spec.tsx
index 119099c1672..e914180c864 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/button-style-dropdown.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/button-style-dropdown.spec.tsx
@@ -1,25 +1,14 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import * as React from 'react'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { withSelectorKey } from '@/test/i18n-mock'
import { UserActionButtonType } from '../../types'
import ButtonStyleDropdown from '../button-style-dropdown'
const mockUseTranslation = vi.hoisted(() => vi.fn())
-const mockButton = vi.hoisted(() => vi.fn())
-
vi.mock('react-i18next', () => ({
useTranslation: () => mockUseTranslation(),
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: (props: { variant?: string; children?: React.ReactNode; className?: string }) => {
- mockButton(props)
- return <div data-testid={`button-${props.variant ?? 'default'}`}>{props.children}</div>
- },
-}))
-
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
describe('ButtonStyleDropdown', () => {
const onChange = vi.fn()
@@ -30,34 +19,21 @@ describe('ButtonStyleDropdown', () => {
})
})
- it('should map the current style to the trigger button and update the selected style', () => {
+ it('should open the style picker and update the selected style', async () => {
+ const user = userEvent.setup()
render(
<ButtonStyleDropdown text="Approve" data={UserActionButtonType.Ghost} onChange={onChange} />,
)
- expect(mockButton).toHaveBeenCalledWith(
- expect.objectContaining({
- variant: 'ghost',
- }),
- )
- expect(screen.getByTestId('popover'))!.toHaveAttribute('data-open', 'false')
-
- fireEvent.click(screen.getByTestId('popover-trigger'))
- expect(screen.getByTestId('popover'))!.toHaveAttribute('data-open', 'true')
- expect(screen.getByText('nodes.humanInput.userActions.chooseStyle'))!.toBeInTheDocument()
-
- fireEvent.click(screen.getByTestId('button-primary').parentElement as HTMLElement)
- fireEvent.click(screen.getByTestId('button-secondary').parentElement as HTMLElement)
- fireEvent.click(screen.getByTestId('button-secondary-accent').parentElement as HTMLElement)
- fireEvent.click(screen.getAllByTestId('button-ghost')[1]!.parentElement as HTMLElement)
+ await user.click(screen.getByRole('button'))
+ expect(screen.getByText('nodes.humanInput.userActions.chooseStyle')).toBeInTheDocument()
+ await user.click(screen.getAllByRole('button', { name: 'Approve' })[0]!)
- expect(onChange).toHaveBeenNthCalledWith(1, UserActionButtonType.Primary)
- expect(onChange).toHaveBeenNthCalledWith(2, UserActionButtonType.Default)
- expect(onChange).toHaveBeenNthCalledWith(3, UserActionButtonType.Accent)
- expect(onChange).toHaveBeenNthCalledWith(4, UserActionButtonType.Ghost)
+ expect(onChange).toHaveBeenCalledWith(UserActionButtonType.Primary)
})
- it('should keep the dropdown closed in readonly mode', () => {
+ it('should keep the dropdown closed in readonly mode', async () => {
+ const user = userEvent.setup()
render(
<ButtonStyleDropdown
text="Approve"
@@ -67,44 +43,9 @@ describe('ButtonStyleDropdown', () => {
/>,
)
- expect(mockButton).toHaveBeenCalledWith(
- expect.objectContaining({
- variant: 'secondary',
- }),
- )
-
- fireEvent.click(screen.getByTestId('popover-trigger'))
+ await user.click(screen.getByRole('button'))
- expect(screen.getByTestId('popover'))!.toHaveAttribute('data-open', 'false')
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
+ expect(screen.queryByText('nodes.humanInput.userActions.chooseStyle')).not.toBeInTheDocument()
expect(onChange).not.toHaveBeenCalled()
})
-
- it('should map the accent style to the secondary-accent trigger button', () => {
- render(
- <ButtonStyleDropdown text="Approve" data={UserActionButtonType.Accent} onChange={onChange} />,
- )
-
- expect(mockButton).toHaveBeenCalledWith(
- expect.objectContaining({
- variant: 'secondary-accent',
- }),
- )
- })
-
- it('should map the primary style to the primary trigger button', () => {
- render(
- <ButtonStyleDropdown
- text="Approve"
- data={UserActionButtonType.Primary}
- onChange={onChange}
- />,
- )
-
- expect(mockButton).toHaveBeenCalledWith(
- expect.objectContaining({
- variant: 'primary',
- }),
- )
- })
})
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.spec.tsx
index 7cde62207e4..230cc9a70a8 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.spec.tsx
@@ -36,14 +36,6 @@ vi.mock('@/app/components/base/badge', () => ({
default: ({ children }: { children?: ReactNode }) => <div data-testid="badge">{children}</div>,
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: ({ children, variant }: { children?: ReactNode; variant?: string }) => (
- <button type="button" data-testid={`action-${variant}`}>
- {children}
- </button>
- ),
-}))
-
vi.mock('@/app/components/base/chat/chat/answer/human-input-content/utils', () => ({
getButtonStyle: (...args: unknown[]) => mockGetButtonStyle(...args),
}))
@@ -139,7 +131,7 @@ describe('FormContentPreview', () => {
expect(screen.getByTestId('variable-path'))!.toHaveTextContent('#Classifier.answer#')
expect(screen.getByTestId('note'))!.toHaveTextContent('Classifier')
expect(screen.getByText(/Can't find note:/))!.toHaveTextContent('missing_field')
- expect(screen.getByTestId('action-primary'))!.toHaveTextContent('Approve')
+ expect(screen.getByRole('button', { name: 'Approve' })).toBeInTheDocument()
expect(screen.getByText('nodes.humanInput.editor.previewTip'))!.toBeInTheDocument()
})
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/user-action.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/user-action.spec.tsx
index 92b87ad42e2..f6c07d2c778 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/user-action.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/user-action.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import { fireEvent, render, screen } from '@testing-library/react'
import { withSelectorKey } from '@/test/i18n-mock'
import { UserActionButtonType } from '../../types'
@@ -28,14 +27,6 @@ vi.mock('@/app/components/base/input', () => ({
),
}))
-vi.mock('@langgenius/dify-ui/button', () => ({
- Button: (props: { children?: ReactNode; onClick?: () => void }) => (
- <button type="button" onClick={props.onClick}>
- {props.children}
- </button>
- ),
-}))
-
vi.mock('@langgenius/dify-ui/toast', () => ({
__esModule: true,
toast: {
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/index.spec.tsx
index babafbc8f6d..4a158d5b558 100644
--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/__tests__/index.spec.tsx
@@ -28,14 +28,6 @@ vi.mock('@/service/use-common', () => ({
useMembers: () => mockUseMembers(),
}))
-vi.mock('@langgenius/dify-ui/switch', () => ({
- Switch: (props: { checked: boolean; onCheckedChange: (value: boolean) => void }) => (
- <button type="button" onClick={() => props.onCheckedChange(!props.checked)}>
- toggle-workspace
- </button>
- ),
-}))
-
vi.mock('../member-selector', () => ({
__esModule: true,
default: ({ onSelect }: { onSelect: (id: string) => void }) => (
@@ -116,7 +108,7 @@ describe('Recipient', () => {
fireEvent.click(screen.getByText('add-email-member'))
fireEvent.click(screen.getByText('delete-member'))
fireEvent.click(screen.getByText('delete-external'))
- fireEvent.click(screen.getByText('toggle-workspace'))
+ fireEvent.click(screen.getByRole('switch'))
expect(onChange).toHaveBeenNthCalledWith(1, {
whole_workspace: false,
diff --git a/web/app/components/workflow/nodes/iteration/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/iteration/__tests__/integration.spec.tsx
index 76a0712b8b4..af9d480276b 100644
--- a/web/app/components/workflow/nodes/iteration/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/iteration/__tests__/integration.spec.tsx
@@ -1,4 +1,3 @@
-import type { ReactNode } from 'react'
import type { IterationNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
import { toast } from '@langgenius/dify-ui/toast'
@@ -6,7 +5,6 @@ import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ErrorHandleMode } from '@/app/components/workflow/types'
import { BlockEnum, VarType } from '../../../types'
-import AddBlock from '../add-block'
import Node from '../node'
import Panel from '../panel'
import useConfig from '../use-config'
@@ -34,36 +32,6 @@ vi.mock('reactflow', async () => {
}
})
-vi.mock('@/app/components/workflow/block-selector', () => ({
- __esModule: true,
- default: ({
- trigger,
- onSelect,
- availableBlocksTypes = [],
- disabled,
- }: {
- trigger?:
- | ReactNode
- | ((props: React.HTMLAttributes<HTMLElement>, state: { open: boolean }) => ReactNode)
- onSelect?: (type: BlockEnum) => void
- availableBlocksTypes?: BlockEnum[]
- disabled?: boolean
- }) => (
- <div>
- {trigger ? (
- <div>{typeof trigger === 'function' ? trigger({}, { open: false }) : trigger}</div>
- ) : null}
- <button
- type="button"
- disabled={disabled}
- onClick={() => onSelect?.(availableBlocksTypes[0] ?? BlockEnum.Code)}
- >
- select-block
- </button>
- </div>
- ),
-}))
-
vi.mock('../../iteration-start', () => ({
IterationStartNodeDumb: () => <div>iteration-start-node</div>,
}))
@@ -172,25 +140,6 @@ describe('iteration path', () => {
mockUseConfig.mockReturnValue(createConfigResult())
})
- it('should add the next block from the iteration start node', async () => {
- const user = userEvent.setup()
-
- render(<AddBlock iterationNodeId="iteration-node" iterationNodeData={createData()} />)
-
- await user.click(screen.getByRole('button', { name: 'select-block' }))
-
- expect(mockHandleNodeAdd).toHaveBeenCalledWith(
- {
- nodeType: BlockEnum.Code,
- pluginDefaultValue: undefined,
- },
- {
- prevNodeId: 'start-node',
- prevNodeSourceHandle: 'source',
- },
- )
- })
-
it('should render candidate iteration nodes and show the parallel warning once', () => {
render(
<Node
@@ -205,7 +154,7 @@ describe('iteration path', () => {
)
expect(screen.getByText('iteration-start-node')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'select-block' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'workflow.common.addBlock' })).toBeInTheDocument()
expect(screen.getByTestId('iteration-background-iteration-node')).toBeInTheDocument()
expect(mockHandleNodeIterationRerender).toHaveBeenCalledWith('iteration-node')
expect(mockToastWarning).toHaveBeenCalledWith('workflow.nodes.iteration.answerNodeWarningDesc')
diff --git a/web/app/components/workflow/nodes/list-operator/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/list-operator/__tests__/panel.spec.tsx
index fb5fff72e26..8ea9185748b 100644
--- a/web/app/components/workflow/nodes/list-operator/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/list-operator/__tests__/panel.spec.tsx
@@ -9,7 +9,6 @@ import Panel from '../panel'
import { OrderBy } from '../types'
const mockUseConfig = vi.hoisted(() => vi.fn())
-const mockSwitch = vi.hoisted(() => vi.fn())
const mockVarReferencePicker = vi.hoisted(() => vi.fn())
const mockFilterCondition = vi.hoisted(() => vi.fn())
const mockExtractInput = vi.hoisted(() => vi.fn())
@@ -22,27 +21,6 @@ vi.mock('../use-config', () => ({
default: (...args: unknown[]) => mockUseConfig(...args),
}))
-vi.mock('@langgenius/dify-ui/switch', () => ({
- Switch: (props: {
- checked?: boolean
- disabled?: boolean
- onCheckedChange: (value: boolean) => void
- }) => {
- mockSwitch(props)
- return (
- <button
- type="button"
- role="switch"
- aria-checked={props.checked}
- disabled={props.disabled}
- onClick={() => props.onCheckedChange(!props.checked)}
- >
- {props.disabled ? 'switch:disabled' : 'switch:enabled'}
- </button>
- )
- },
-}))
-
vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
__esModule: true,
default: (props: { readonly: boolean; value: string[]; onChange: (value: string[]) => void }) => {
@@ -294,8 +272,8 @@ describe('list-operator/panel', () => {
screen.queryByRole('button', { name: 'workflow.nodes.listFilter.asc:idle' }),
).not.toBeInTheDocument()
expect(screen.getAllByRole('switch')).toHaveLength(3)
- expect(screen.getAllByRole('switch').every((button) => button.hasAttribute('disabled'))).toBe(
- true,
- )
+ expect(
+ screen.getAllByRole('switch').every((control) => control.hasAttribute('data-disabled')),
+ ).toBe(true)
})
})
diff --git a/web/app/components/workflow/nodes/list-operator/components/__tests__/limit-config.spec.tsx b/web/app/components/workflow/nodes/list-operator/components/__tests__/limit-config.spec.tsx
index e92dbcde8a1..dfa8caded83 100644
--- a/web/app/components/workflow/nodes/list-operator/components/__tests__/limit-config.spec.tsx
+++ b/web/app/components/workflow/nodes/list-operator/components/__tests__/limit-config.spec.tsx
@@ -2,12 +2,6 @@ import type { Limit } from '../../types'
import { fireEvent, render, screen } from '@testing-library/react'
import LimitConfig from '../limit-config'
-type MockSwitchProps = {
- checked: boolean
- onCheckedChange: (value: boolean) => void
- disabled?: boolean
-}
-
type MockSliderProps = {
label: string
value: number
@@ -17,23 +11,8 @@ type MockSliderProps = {
readonly: boolean
}
-const mockSwitch = vi.fn<(props: MockSwitchProps) => void>()
const mockSlider = vi.fn<(props: MockSliderProps) => void>()
-vi.mock('@langgenius/dify-ui/switch', () => ({
- Switch: (props: MockSwitchProps) => {
- mockSwitch(props)
- return (
- <button
- type="button"
- onClick={() => !props.disabled && props.onCheckedChange(!props.checked)}
- >
- {`switch:${props.checked}`}
- </button>
- )
- },
-}))
-
vi.mock('@/app/components/workflow/nodes/_base/components/field', () => ({
default: ({
title,
@@ -77,7 +56,7 @@ describe('list-operator/limit-config', () => {
expect(screen.getByText('workflow.nodes.listFilter.limit'))!.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'slider:10:false' })).not.toBeInTheDocument()
- fireEvent.click(screen.getByRole('button', { name: 'switch:false' }))
+ fireEvent.click(screen.getByRole('switch'))
expect(handleChange).toHaveBeenCalledWith({
enabled: true,
size: 10,
@@ -107,7 +86,7 @@ describe('list-operator/limit-config', () => {
size: 7,
})
- fireEvent.click(screen.getByRole('button', { name: 'switch:true' }))
+ fireEvent.click(screen.getByRole('switch'))
expect(handleChange).toHaveBeenCalledTimes(1)
})
})
diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-importer.spec.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-importer.spec.tsx
index 0dde441aaab..a36def95985 100644
--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-importer.spec.tsx
+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-importer.spec.tsx
@@ -36,59 +36,6 @@ vi.mock('../error-message', () => ({
default: ({ message }: { message: string }) => <div data-testid="error-message">{message}</div>,
}))
-vi.mock('@langgenius/dify-ui/popover', async () => {
- const ReactModule = await vi.importActual<typeof import('react')>('react')
-
- const PopoverContext = ReactModule.createContext<{
- open: boolean
- onOpenChange?: (open: boolean) => void
- } | null>(null)
-
- const PopoverTrigger = ReactModule.forwardRef<
- HTMLButtonElement,
- React.ButtonHTMLAttributes<HTMLButtonElement>
- >(({ children, onClick, ...props }, ref) => {
- const context = ReactModule.useContext(PopoverContext)
-
- return (
- <button
- ref={ref}
- type="button"
- {...props}
- onClick={(event) => {
- onClick?.(event)
- context?.onOpenChange?.(!context.open)
- }}
- >
- {children}
- </button>
- )
- })
-
- PopoverTrigger.displayName = 'PopoverTrigger'
-
- return {
- Popover: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <PopoverContext.Provider value={{ open, onOpenChange }}>{children}</PopoverContext.Provider>
- ),
- PopoverTrigger,
- PopoverContent: ({ children }: { children: React.ReactNode }) => {
- const context = ReactModule.useContext(PopoverContext)
- if (!context?.open) return null
-
- return <div data-testid="popover-content">{children}</div>
- },
- }
-})
-
describe('JsonImporter', () => {
const mockOnSubmit = vi.fn()
const mockUpdateBtnWidth = vi.fn()
@@ -129,7 +76,7 @@ describe('JsonImporter', () => {
screen.getByRole('button', { name: /(?:^|\.)nodes\.llm\.jsonSchema\.import(?=$|:)/ }),
)
- expect(screen.getByTestId('popover-content')).toBeInTheDocument()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
expect(mockEmit).not.toHaveBeenCalled()
})
@@ -185,16 +132,15 @@ describe('JsonImporter', () => {
it('shows the parser error when JSON.parse throws an Error', async () => {
const user = userEvent.setup()
- const parseSpy = vi.spyOn(JSON, 'parse').mockImplementationOnce(() => {
- throw new Error('Malformed JSON payload')
- })
-
render(<JsonImporter onSubmit={mockOnSubmit} updateBtnWidth={mockUpdateBtnWidth} />)
await user.click(
screen.getByRole('button', { name: /(?:^|\.)nodes\.llm\.jsonSchema\.import(?=$|:)/ }),
)
fireEvent.change(screen.getByLabelText('json-editor'), { target: { value: '{"foo":1}' } })
+ const parseSpy = vi.spyOn(JSON, 'parse').mockImplementation(() => {
+ throw new Error('Malformed JSON payload')
+ })
await user.click(screen.getByRole('button', { name: /(?:^|\.)operation\.submit(?=$|:)/ }))
expect(screen.getByTestId('error-message')).toHaveTextContent('Malformed JSON payload')
@@ -205,16 +151,15 @@ describe('JsonImporter', () => {
it('falls back to the default invalid JSON message when JSON.parse throws a non-Error value', async () => {
const user = userEvent.setup()
- const parseSpy = vi
- .spyOn(JSON, 'parse')
- .mockImplementationOnce(() => throwUnknown(Object.create(null)))
-
render(<JsonImporter onSubmit={mockOnSubmit} updateBtnWidth={mockUpdateBtnWidth} />)
await user.click(
screen.getByRole('button', { name: /(?:^|\.)nodes\.llm\.jsonSchema\.import(?=$|:)/ }),
)
fireEvent.change(screen.getByLabelText('json-editor'), { target: { value: '{"foo":1}' } })
+ const parseSpy = vi
+ .spyOn(JSON, 'parse')
+ .mockImplementation(() => throwUnknown(Object.create(null)))
await user.click(screen.getByRole('button', { name: /(?:^|\.)operation\.submit(?=$|:)/ }))
expect(screen.getByTestId('error-message')).toHaveTextContent('Invalid JSON')
@@ -235,13 +180,13 @@ describe('JsonImporter', () => {
await user.click(screen.getByRole('button', { name: /(?:^|\.)operation\.submit(?=$|:)/ }))
expect(mockOnSubmit).toHaveBeenCalledWith({ foo: 'bar' })
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: /(?:^|\.)nodes\.llm\.jsonSchema\.import(?=$|:)/ }),
)
await user.click(screen.getByRole('button', { name: /(?:^|\.)operation\.cancel(?=$|:)/ }))
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
index f1907000932..0b9b5c91004 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
@@ -73,14 +73,6 @@ vi.mock(
}),
)
-vi.mock('@langgenius/dify-ui/dialog', () => ({
- __esModule: true,
- Dialog: ({ children, open }: { children: ReactNode; open?: boolean }) =>
- open !== false ? <div data-testid="base-modal">{children}</div> : null,
- DialogContent: ({ children }: { children: ReactNode }) => <>{children}</>,
- DialogTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
-
vi.mock('@/app/components/workflow/nodes/_base/components/collapse', () => ({
FieldCollapse: ({ title, children }: { title: ReactNode; children: ReactNode }) => (
<div>
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.branches.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.branches.spec.tsx
deleted file mode 100644
index a4dc26649aa..00000000000
--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.branches.spec.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import ImportFromTool from '../import-from-tool'
-
-vi.mock('../../../../../block-selector', () => ({
- __esModule: true,
- default: ({ onSelect }: { onSelect: (type: string, toolInfo?: unknown) => void }) => (
- <div>
- <button type="button" onClick={() => onSelect('tool', undefined)}>
- select-missing-tool
- </button>
- <button
- type="button"
- onClick={() =>
- onSelect('tool', {
- provider_id: 'provider-1',
- provider_type: 'unsupported',
- tool_name: 'search',
- })
- }
- >
- select-unsupported-tool
- </button>
- </div>
- ),
-}))
-
-vi.mock('@/service/use-tools', () => ({
- useAllBuiltInTools: () => ({ data: [] }),
- useAllCustomTools: () => ({ data: [] }),
- useAllWorkflowTools: () => ({ data: [] }),
-}))
-
-vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
- useLanguage: () => 'en_US',
-}))
-
-describe('parameter-extractor/extract-parameter/import-from-tool branches', () => {
- it('ignores missing and unsupported tool payloads', async () => {
- const user = userEvent.setup()
- const handleImport = vi.fn()
-
- render(<ImportFromTool onImport={handleImport} />)
-
- await user.click(screen.getByRole('button', { name: 'select-missing-tool' }))
- expect(handleImport).not.toHaveBeenCalled()
-
- await user.click(screen.getByRole('button', { name: 'select-unsupported-tool' }))
-
- expect(handleImport).toHaveBeenCalledWith([])
- })
-})
diff --git a/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx
index ac53a5a7d09..2e518462cd9 100644
--- a/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx
@@ -71,12 +71,6 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/model-selec
),
}))
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: any) => <div>{children}</div>,
- TooltipTrigger: ({ children }: any) => <>{children}</>,
- TooltipContent: ({ children }: any) => <div>{children}</div>,
-}))
-
vi.mock('@/app/components/workflow/nodes/_base/components/readonly-input-with-select-var', () => ({
default: ({ value }: any) => <div>{value}</div>,
}))
diff --git a/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
index 13dc0a03700..685bdf3a1b0 100644
--- a/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/trigger-webhook/__tests__/panel.spec.tsx
@@ -2,6 +2,7 @@ import type { WebhookTriggerNodeType } from '../types'
import type { NodePanelProps } from '@/app/components/workflow/types'
import type { PanelProps } from '@/types/workflow'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { BlockEnum } from '@/app/components/workflow/types'
import Panel from '../panel'
@@ -31,68 +32,6 @@ const {
mockIsPrivateOrLocalAddress: vi.fn((_url: string) => false),
}))
-vi.mock('@langgenius/dify-ui/select', async () => {
- const React = await import('react')
- const SelectContext = React.createContext<{
- disabled?: boolean
- onValueChange?: (value: string) => void
- }>({})
-
- return {
- Select: ({
- children,
- disabled,
- onValueChange,
- }: {
- children: React.ReactNode
- disabled?: boolean
- onValueChange?: (value: string) => void
- }) => (
- <SelectContext.Provider value={{ disabled, onValueChange }}>
- <div>{children}</div>
- </SelectContext.Provider>
- ),
- SelectLabel: () => null,
- SelectTrigger: ({ children, className }: { children: React.ReactNode; className?: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <div>
- <button
- data-testid="select-trigger"
- type="button"
- disabled={context.disabled}
- className={className}
- >
- {children}
- </button>
- <button
- data-testid="select-empty"
- type="button"
- onClick={() => context.onValueChange?.('')}
- >
- empty select value
- </button>
- </div>
- )
- },
- SelectContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- SelectItem: ({ children, value }: { children: React.ReactNode; value: string }) => {
- const context = React.useContext(SelectContext)
- return (
- <button
- data-testid={`select-${value}`}
- type="button"
- onClick={() => context.onValueChange?.(value)}
- >
- {children}
- </button>
- )
- },
- SelectItemText: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- SelectItemIndicator: () => null,
- }
-})
-
vi.mock('@langgenius/dify-ui/toast', () => ({
toast: {
success: mockToastSuccess,
@@ -305,7 +244,7 @@ describe('WebhookTriggerPanel', () => {
it('should keep the content type selector aligned with the webhook url row width', () => {
render(<Panel {...panelProps} />)
- const contentTypeTrigger = screen.getAllByTestId('select-trigger')[1]
+ const contentTypeTrigger = screen.getAllByRole('combobox')[1]
expect(contentTypeTrigger).toHaveClass('w-full')
})
@@ -348,12 +287,15 @@ describe('WebhookTriggerPanel', () => {
})
describe('Interactions', () => {
- it('should handle method, content type, table, response, and copy actions', () => {
+ it('should handle method, content type, table, response, and copy actions', async () => {
+ const user = userEvent.setup()
render(<Panel {...panelProps} />)
fireEvent.click(screen.getByTestId('copy-input'))
- fireEvent.click(screen.getByTestId('select-GET'))
- fireEvent.click(screen.getByTestId('select-text/plain'))
+ await user.click(screen.getAllByRole('combobox')[0]!)
+ await user.click(await screen.findByRole('option', { name: 'GET' }))
+ await user.click(screen.getAllByRole('combobox')[1]!)
+ await user.click(await screen.findByRole('option', { name: 'text/plain' }))
fireEvent.click(screen.getByTestId('parameter-Query Parameters'))
fireEvent.click(screen.getByTestId('header-table'))
fireEvent.click(screen.getByTestId('parameter-Request Body Parameters'))
@@ -395,15 +337,5 @@ describe('WebhookTriggerPanel', () => {
vi.runAllTimers()
vi.useRealTimers()
})
-
- it('should ignore empty method and content-type selections', () => {
- render(<Panel {...panelProps} />)
-
- fireEvent.click(screen.getAllByTestId('select-empty')[0]!)
- fireEvent.click(screen.getAllByTestId('select-empty')[1]!)
-
- expect(mockHandleMethodChange).not.toHaveBeenCalled()
- expect(mockHandleContentTypeChange).not.toHaveBeenCalled()
- })
})
})
diff --git a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/color-picker.spec.tsx b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/color-picker.spec.tsx
index a81169d006d..4b0740a1fa3 100644
--- a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/color-picker.spec.tsx
+++ b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/color-picker.spec.tsx
@@ -2,16 +2,14 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { NoteTheme } from '../../../types'
import ColorPicker from '../color-picker'
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
describe('NoteEditor ColorPicker', () => {
it('should open the palette and apply the selected theme', async () => {
const onThemeChange = vi.fn()
render(<ColorPicker theme={NoteTheme.blue} onThemeChange={onThemeChange} />)
- fireEvent.click(screen.getByTestId('popover-trigger'))
+ fireEvent.click(screen.getByRole('button'))
- const popup = screen.getByTestId('popover-content')
+ const popup = screen.getByRole('dialog')
expect(popup).toBeInTheDocument()
@@ -24,7 +22,7 @@ describe('NoteEditor ColorPicker', () => {
expect(onThemeChange).toHaveBeenCalledWith(NoteTheme.violet)
await waitFor(() => {
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})
})
diff --git a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/font-size-selector.spec.tsx b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/font-size-selector.spec.tsx
index 0a0e6c86192..010b17072fa 100644
--- a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/font-size-selector.spec.tsx
+++ b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/font-size-selector.spec.tsx
@@ -1,8 +1,6 @@
import { fireEvent, render, screen } from '@testing-library/react'
import FontSizeSelector from '../font-size-selector'
-vi.mock('@langgenius/dify-ui/popover', () => import('@/__mocks__/base-ui-popover'))
-
const { mockHandleFontSize, mockHandleOpenFontSizeSelector } = vi.hoisted(() => ({
mockHandleFontSize: vi.fn(),
mockHandleOpenFontSizeSelector: vi.fn(),
@@ -36,7 +34,7 @@ describe('NoteEditor FontSizeSelector', () => {
fireEvent.click(screen.getByText('workflow.nodes.note.editor.small'))
- expect(mockHandleOpenFontSizeSelector).toHaveBeenCalledWith(true)
+ expect(mockHandleOpenFontSizeSelector.mock.calls[0]?.[0]).toBe(true)
})
it('should select a new font size and close the popup', () => {
diff --git a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx
index f51f9e5724c..4128fa7246b 100644
--- a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx
+++ b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx
@@ -1,144 +1,7 @@
-import type { MouseEvent, MouseEventHandler, ReactElement, ReactNode } from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Operator from '../operator'
-type DropdownTriggerRenderProps = {
- className?: string
- role?: string
- 'aria-label'?: string
- onMouseDown?: MouseEventHandler<HTMLDivElement>
- onClick?: MouseEventHandler<HTMLDivElement>
-}
-
-type DropdownTriggerProps = {
- children: ReactNode
- className?: string
- render?: ReactElement<DropdownTriggerRenderProps>
- onMouseDown?: MouseEventHandler<HTMLDivElement>
- onClick?: MouseEventHandler<HTMLDivElement>
- 'aria-label'?: string
-}
-
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- open: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div>{children}</div>
- </DropdownMenuContext>
- ),
- DropdownMenuTrigger: ({
- children,
- className,
- render,
- onMouseDown,
- onClick,
- 'aria-label': ariaLabel,
- }: DropdownTriggerProps) => {
- const { open, setOpen } = useDropdownMenuContext()
- if (render) {
- const handleMouseDown = (event: MouseEvent<HTMLDivElement>) => {
- const baseUiEvent = event as MouseEvent<HTMLDivElement> & {
- preventBaseUIHandler?: () => void
- }
- baseUiEvent.preventBaseUIHandler = vi.fn()
- onMouseDown?.(baseUiEvent)
- render.props.onMouseDown?.(event)
- }
-
- const handleClick = (event: MouseEvent<HTMLDivElement>) => {
- onClick?.(event)
- render.props.onClick?.(event)
- if (!onMouseDown) setOpen(!open)
- }
-
- return (
- <div
- role={render.props.role ?? 'button'}
- aria-label={render.props['aria-label'] ?? ariaLabel}
- className={render.props.className ?? className}
- onMouseDown={handleMouseDown}
- onClick={handleClick}
- >
- {children}
- </div>
- )
- }
-
- return (
- <button
- type="button"
- aria-label={ariaLabel}
- className={className}
- onMouseDown={(event) => {
- const baseUiEvent = event as MouseEvent<HTMLButtonElement> & {
- preventBaseUIHandler?: () => void
- }
- baseUiEvent.preventBaseUIHandler = vi.fn()
- onMouseDown?.(baseUiEvent as unknown as MouseEvent<HTMLDivElement>)
- }}
- onClick={(event) => {
- onClick?.(event as unknown as MouseEvent<HTMLDivElement>)
- if (!onMouseDown) setOpen(!open)
- }}
- >
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({ children }: { children: ReactNode }) => {
- const { open } = useDropdownMenuContext()
- return open ? <div>{children}</div> : null
- },
- DropdownMenuItem: ({
- children,
- onClick,
- className,
- }: {
- children: ReactNode
- onClick?: MouseEventHandler<HTMLButtonElement>
- className?: string
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- className={className}
- onClick={(event) => {
- onClick?.(event)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- DropdownMenuSeparator: ({ className }: { className?: string }) => (
- <div className={className} data-testid="dropdown-separator" />
- ),
- }
-})
-
const renderOperator = (showAuthor = false) => {
const onCopy = vi.fn()
const onDuplicate = vi.fn()
diff --git a/web/app/components/workflow/operator/__tests__/add-block.spec.tsx b/web/app/components/workflow/operator/__tests__/add-block.spec.tsx
index c1d6f8c96b5..5cb9d0bb1d7 100644
--- a/web/app/components/workflow/operator/__tests__/add-block.spec.tsx
+++ b/web/app/components/workflow/operator/__tests__/add-block.spec.tsx
@@ -1,29 +1,13 @@
-import type { ReactElement, ReactNode } from 'react'
-import type { BlockSelectorProps } from '../../block-selector'
-import { act, screen, waitFor } from '@testing-library/react'
+import type { NodeDefault } from '../../types'
+import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { FlowType } from '@/types/common'
import { createNode } from '../../__tests__/fixtures'
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
+import { BlockClassification } from '../../block-selector/types'
import { BlockEnum } from '../../types'
import AddBlock from '../add-block'
-type BlockSelectorMockProps = {
- open: boolean
- onOpenChange: (open: boolean) => void
- disabled: boolean
- onSelect: (type: BlockEnum, pluginDefaultValue?: Record<string, unknown>) => void
- placement: string
- sideOffset: number
- alignOffset: number
- trigger: NonNullable<BlockSelectorProps['trigger']>
- popupClassName: string
- availableBlocksTypes: BlockEnum[]
- showStartTab: boolean
- isolateKeyboardEvents?: boolean
- defaultActiveTab?: unknown
-}
-type BlockSelectorTriggerRender = Exclude<NonNullable<BlockSelectorProps['trigger']>, ReactElement>
-
const {
mockHandlePaneContextmenuCancel,
mockWorkflowStoreSetState,
@@ -34,86 +18,50 @@ const {
mockHandlePaneContextmenuCancel: vi.fn(),
mockWorkflowStoreSetState: vi.fn(),
mockGenerateNewNode: vi.fn(({ type, data }: { type: string; data: Record<string, unknown> }) => ({
- newNode: {
- id: 'generated-node',
- type,
- data,
- position: {
- x: 0,
- y: 0,
- },
- },
+ newNode: { id: 'generated-node', type, data, position: { x: 0, y: 0 } },
})),
mockGetNodeCustomTypeByNodeDataType: vi.fn((type: string) => `${type}-custom`),
mockGetNodesWithSameDefaultDataType: vi.fn(
- (
- nodes: Array<{ data: { agent_node_kind?: string; type?: BlockEnum; version?: string } }>,
- type: BlockEnum,
- defaultValue: { agent_node_kind?: string; type?: BlockEnum; version?: string },
- ) => {
- const dataType = defaultValue.type ?? type
- if (dataType !== type && defaultValue.version) {
- return nodes.filter(
- (node) =>
- node.data.type === dataType &&
- node.data.version === defaultValue.version &&
- node.data.agent_node_kind === defaultValue.agent_node_kind,
- )
- }
-
- return nodes.filter((node) => node.data.type === dataType)
- },
+ (nodes: Array<{ data: { type?: BlockEnum } }>, type: BlockEnum) =>
+ nodes.filter((node) => node.data.type === type),
),
}))
-let latestBlockSelectorProps: BlockSelectorMockProps | null = null
let mockNodesReadOnly = false
let mockIsChatMode = false
-let mockTooltipOpen = false
let mockFlowType: FlowType = FlowType.appFlow
-const mockAvailableNextBlocks = [BlockEnum.Answer, BlockEnum.Code]
-const mockNodesMetaDataMap: Partial<Record<BlockEnum, { defaultValue: Record<string, unknown> }>> =
- {
- [BlockEnum.Answer]: {
- defaultValue: {
- title: 'Answer',
- desc: '',
- type: BlockEnum.Answer,
- },
- },
- }
-
-vi.mock('@/app/components/workflow/block-selector', () => ({
- default: (props: BlockSelectorMockProps) => {
- latestBlockSelectorProps = props
- const renderProps = {
- 'data-popup-open': mockTooltipOpen ? '' : undefined,
- } as unknown as Parameters<BlockSelectorTriggerRender>[0]
- const trigger =
- typeof props.trigger === 'function'
- ? props.trigger(renderProps, { open: props.open, disabled: props.disabled })
- : props.trigger
- return <div data-testid="block-selector">{trigger}</div>
+const answerBlock: NodeDefault = {
+ metaData: {
+ classification: BlockClassification.Default,
+ sort: 0,
+ type: BlockEnum.Answer,
+ title: 'Answer',
+ author: 'Dify',
+ description: 'Answer description',
},
-}))
+ defaultValue: {
+ title: 'Answer',
+ desc: '',
+ type: BlockEnum.Answer,
+ },
+ checkValid: () => ({ isValid: true }),
+}
vi.mock('../../hooks/use-available-blocks', () => ({
useAvailableBlocks: () => ({
- availableNextBlocks: mockAvailableNextBlocks,
+ availableNextBlocks: [BlockEnum.Answer],
}),
}))
vi.mock('../../hooks/use-workflow', () => ({
useIsChatMode: () => mockIsChatMode,
- useNodesReadOnly: () => ({
- nodesReadOnly: mockNodesReadOnly,
- }),
+ useNodesReadOnly: () => ({ nodesReadOnly: mockNodesReadOnly }),
}))
vi.mock('../../hooks/use-nodes-meta-data', () => ({
useNodesMetaData: () => ({
- nodesMap: mockNodesMetaDataMap,
+ nodesMap: { [BlockEnum.Answer]: answerBlock },
}),
}))
@@ -124,281 +72,126 @@ vi.mock('../../hooks/use-panel-interactions', () => ({
}))
vi.mock('../../hooks-store', () => ({
- useHooksStore: (selector: (state: { configsMap?: { flowType?: FlowType } }) => unknown) =>
- selector({ configsMap: { flowType: mockFlowType } }),
+ useHooksStore: (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ configsMap: { flowType: mockFlowType },
+ availableNodesMetaData: { nodes: [answerBlock] },
+ }),
}))
vi.mock('../../store', () => ({
- useWorkflowStore: () => ({
- setState: mockWorkflowStoreSetState,
- }),
+ useStore: (selector: (state: { dataSourceList: unknown[]; nodes: unknown[] }) => unknown) =>
+ selector({ dataSourceList: [], nodes: [] }),
+ useWorkflowStore: () => ({ setState: mockWorkflowStoreSetState }),
+}))
+
+vi.mock('../../utils', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../utils')>()
+ return {
+ ...actual,
+ generateNewNode: mockGenerateNewNode,
+ getNodeCustomTypeByNodeDataType: mockGetNodeCustomTypeByNodeDataType,
+ getNodesWithSameDefaultDataType: mockGetNodesWithSameDefaultDataType,
+ }
+})
+
+vi.mock('@/service/use-plugins', () => ({
+ useFeaturedToolsRecommendations: () => ({ plugins: [], isLoading: false }),
+ useFeaturedTriggersRecommendations: () => ({ plugins: [], isLoading: false }),
}))
-vi.mock('../../utils', () => ({
- generateNewNode: mockGenerateNewNode,
- getNodeCustomTypeByNodeDataType: mockGetNodeCustomTypeByNodeDataType,
- getNodesWithSameDefaultDataType: mockGetNodesWithSameDefaultDataType,
+vi.mock('@/service/use-triggers', () => ({
+ useAllTriggerPlugins: () => ({ data: [] }),
+ useInvalidateAllTriggerPlugins: () => vi.fn(),
}))
-vi.mock('../tip-popup', () => ({
- default: ({ children }: { children?: ReactNode }) => <>{children}</>,
+vi.mock('@/service/use-tools', () => ({
+ useAllBuiltInTools: () => ({ data: [] }),
+ useAllCustomTools: () => ({ data: [] }),
+ useAllWorkflowTools: () => ({ data: [] }),
+ useAllMCPTools: () => ({ data: [] }),
+ useInvalidateAllBuiltInTools: () => vi.fn(),
}))
-const renderWithReactFlow = (nodes: Array<ReturnType<typeof createNode>>) =>
+vi.mock('@/app/components/plugins/marketplace/query', () => ({
+ useMarketplacePlugins: () => ({ data: undefined }),
+}))
+
+const renderWithReactFlow = (nodes: Array<ReturnType<typeof createNode>> = []) =>
renderWorkflowFlowComponent(<AddBlock />, { nodes, edges: [] })
describe('AddBlock', () => {
beforeEach(() => {
vi.clearAllMocks()
- latestBlockSelectorProps = null
mockNodesReadOnly = false
mockIsChatMode = false
- mockTooltipOpen = false
mockFlowType = FlowType.appFlow
})
- // Rendering and selector configuration.
- describe('Rendering', () => {
- it('should pass the selector props for a writable app workflow', async () => {
- renderWithReactFlow([])
-
- await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())
-
- expect(screen.getByTestId('block-selector')).toBeInTheDocument()
- expect(latestBlockSelectorProps).toMatchObject({
- disabled: false,
- availableBlocksTypes: mockAvailableNextBlocks,
- showStartTab: true,
- placement: 'right-start',
- sideOffset: 4,
- alignOffset: -8,
- popupClassName: 'min-w-[256px]!',
- isolateKeyboardEvents: undefined,
- })
- expect(latestBlockSelectorProps?.defaultActiveTab).toBeUndefined()
- })
-
- it('should hide the start tab for chat mode and rag pipeline flows', async () => {
- mockIsChatMode = true
- const { unmount } = renderWithReactFlow([])
-
- await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())
-
- expect(latestBlockSelectorProps?.showStartTab).toBe(false)
-
- mockIsChatMode = false
- mockFlowType = FlowType.ragPipeline
- unmount()
- renderWithReactFlow([])
-
- expect(latestBlockSelectorProps?.showStartTab).toBe(false)
- })
-
- it.each([BlockEnum.Start, BlockEnum.TriggerWebhook])(
- 'should keep the normal default tab when a %s node already exists',
- async (type) => {
- renderWithReactFlow([
- createNode({ id: 'entry-node', position: { x: 0, y: 0 }, data: { type } }),
- ])
-
- await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())
-
- expect(latestBlockSelectorProps?.showStartTab).toBe(true)
- expect(latestBlockSelectorProps?.defaultActiveTab).toBeUndefined()
- },
- )
-
- it('should pass keyboard isolation to the selector when requested by the caller', async () => {
- renderWorkflowFlowComponent(<AddBlock isolateKeyboardEvents />, { nodes: [], edges: [] })
-
- await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())
-
- expect(latestBlockSelectorProps?.isolateKeyboardEvents).toBe(true)
- })
-
- it('should keep the read-only trigger focusable', async () => {
- mockNodesReadOnly = true
-
- renderWithReactFlow([])
-
- const trigger = screen.getByRole('button')
- expect(trigger).toHaveAttribute('aria-disabled', 'true')
-
- trigger.focus()
- expect(trigger).toHaveFocus()
- })
-
- it('should derive the active trigger style from Popover state instead of a composed Tooltip attribute', () => {
- mockTooltipOpen = true
-
- renderWithReactFlow([])
+ it('opens the real selector and derives trigger styling from its open state', async () => {
+ const user = userEvent.setup()
+ renderWithReactFlow()
- const trigger = screen.getByRole('button')
- expect(trigger).toHaveAttribute('data-popup-open')
- expect(trigger).not.toHaveClass('bg-state-accent-active')
+ const trigger = screen.getByRole('button', { name: 'workflow.common.addBlock' })
+ expect(trigger).not.toHaveAttribute('data-popup-open')
- act(() => {
- latestBlockSelectorProps?.onOpenChange(true)
- })
+ await user.click(trigger)
- expect(trigger).toHaveClass('bg-state-accent-active')
- })
+ expect(trigger).toHaveAttribute('data-popup-open')
+ expect(trigger).toHaveClass('bg-state-accent-active')
+ expect(screen.getByRole('dialog', { name: 'workflow.common.addBlock' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Answer' })).toBeInTheDocument()
})
- // User interactions that bridge selector state and workflow state.
- describe('User Interactions', () => {
- it('should cancel the pane context menu when the selector closes', async () => {
- renderWithReactFlow([])
-
- await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())
-
- act(() => {
- latestBlockSelectorProps?.onOpenChange(false)
- })
-
- expect(mockHandlePaneContextmenuCancel).toHaveBeenCalledTimes(1)
- })
+ it('keeps the disabled trigger focusable without opening the selector', async () => {
+ const user = userEvent.setup()
+ mockNodesReadOnly = true
+ renderWithReactFlow()
- it('should create a candidate node with an incremented title when a block is selected', async () => {
- renderWithReactFlow([
- createNode({ id: 'node-1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Answer } }),
- createNode({ id: 'node-2', position: { x: 80, y: 0 }, data: { type: BlockEnum.Answer } }),
- ])
+ const trigger = screen.getByRole('button', { name: 'workflow.common.addBlock' })
+ expect(trigger).toHaveAttribute('aria-disabled', 'true')
- await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())
+ trigger.focus()
+ expect(trigger).toHaveFocus()
+ await user.click(trigger)
+ expect(
+ screen.queryByRole('dialog', { name: 'workflow.common.addBlock' }),
+ ).not.toBeInTheDocument()
+ })
- act(() => {
- latestBlockSelectorProps?.onSelect(BlockEnum.Answer, { pluginId: 'plugin-1' })
- })
+ it('closes the selector through the real trigger and cancels the pane menu', async () => {
+ const user = userEvent.setup()
+ renderWithReactFlow()
- expect(mockGetNodeCustomTypeByNodeDataType).toHaveBeenCalledWith(BlockEnum.Answer)
- expect(mockGenerateNewNode).toHaveBeenCalledWith({
- type: 'answer-custom',
- data: {
- title: 'Answer 3',
- desc: '',
- type: BlockEnum.Answer,
- pluginId: 'plugin-1',
- _isCandidate: true,
- },
- position: {
- x: 0,
- y: 0,
- },
- })
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
- candidateNode: expect.objectContaining({
- id: 'generated-node',
- type: 'answer-custom',
- data: {
- title: 'Answer 3',
- desc: '',
- type: BlockEnum.Answer,
- pluginId: 'plugin-1',
- _isCandidate: true,
- },
- }),
- })
- })
+ const trigger = screen.getByRole('button', { name: 'workflow.common.addBlock' })
+ await user.click(trigger)
+ await user.click(trigger)
- it('should count Agent v2 nodes by the final default data type without counting legacy Agent nodes', async () => {
- mockNodesMetaDataMap[BlockEnum.AgentV2] = {
- defaultValue: {
- title: 'Agent',
- desc: '',
- agent_node_kind: 'dify_agent',
- type: BlockEnum.Agent,
- version: '2',
- },
- }
- renderWithReactFlow([
- createNode({
- id: 'old-agent',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.Agent, version: '2' },
- }),
- createNode({
- id: 'agent-v2',
- position: { x: 80, y: 0 },
- data: { agent_node_kind: 'dify_agent', type: BlockEnum.Agent, version: '2' },
- }),
- ])
+ expect(mockHandlePaneContextmenuCancel).toHaveBeenCalledTimes(1)
+ })
- await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())
+ it('creates a candidate node after selecting a real block option', async () => {
+ const user = userEvent.setup()
+ renderWithReactFlow([
+ createNode({ id: 'node-1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Answer } }),
+ createNode({ id: 'node-2', position: { x: 80, y: 0 }, data: { type: BlockEnum.Answer } }),
+ ])
- act(() => {
- latestBlockSelectorProps?.onSelect(BlockEnum.AgentV2)
- })
+ await user.click(screen.getByRole('button', { name: 'workflow.common.addBlock' }))
+ await user.click(screen.getByRole('button', { name: 'Answer' }))
- expect(mockGetNodesWithSameDefaultDataType).toHaveBeenCalledWith(
- expect.any(Array),
- BlockEnum.AgentV2,
- {
- title: 'Agent',
- desc: '',
- agent_node_kind: 'dify_agent',
- type: BlockEnum.Agent,
- version: '2',
- },
- )
- expect(mockGenerateNewNode).toHaveBeenCalledWith({
- type: 'agent-v2-custom',
- data: {
- title: 'Agent 2',
- desc: '',
- agent_node_kind: 'dify_agent',
- type: BlockEnum.Agent,
- version: '2',
- _isCandidate: true,
- },
- position: {
- x: 0,
- y: 0,
- },
- })
+ expect(mockGenerateNewNode).toHaveBeenCalledWith({
+ type: 'answer-custom',
+ data: {
+ title: 'Answer 3',
+ desc: '',
+ type: BlockEnum.Answer,
+ _isCandidate: true,
+ },
+ position: { x: 0, y: 0 },
})
-
- it('should keep start-from-scratch Agent v2 as a candidate node before placement', async () => {
- mockNodesMetaDataMap[BlockEnum.AgentV2] = {
- defaultValue: {
- title: 'Agent',
- desc: '',
- agent_node_kind: 'dify_agent',
- type: BlockEnum.Agent,
- version: '2',
- },
- }
- renderWithReactFlow([])
-
- await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())
-
- act(() => {
- latestBlockSelectorProps?.onSelect(BlockEnum.AgentV2, {
- agent_binding: {
- binding_type: 'inline_agent',
- },
- agent_node_kind: 'dify_agent',
- version: '2',
- })
- })
-
- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
- candidateNode: expect.objectContaining({
- id: 'generated-node',
- type: 'agent-v2-custom',
- data: {
- title: 'Agent',
- desc: '',
- agent_binding: {
- binding_type: 'inline_agent',
- },
- agent_node_kind: 'dify_agent',
- type: BlockEnum.Agent,
- version: '2',
- _isCandidate: true,
- },
- }),
- })
+ expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
+ candidateNode: expect.objectContaining({ id: 'generated-node' }),
})
})
})
diff --git a/web/app/components/workflow/operator/__tests__/more-actions.spec.tsx b/web/app/components/workflow/operator/__tests__/more-actions.spec.tsx
index 48e40bd4c71..8727aa42e41 100644
--- a/web/app/components/workflow/operator/__tests__/more-actions.spec.tsx
+++ b/web/app/components/workflow/operator/__tests__/more-actions.spec.tsx
@@ -9,112 +9,12 @@ const mockToSvg = vi.fn()
const mockDownloadUrl = vi.fn()
const mockSetViewport = vi.fn()
const mockGetNodesReadOnly = vi.fn()
-const { mockDropdownContentProps, mockWorkflowState } = vi.hoisted(() => ({
- mockDropdownContentProps: vi.fn(),
+const { mockWorkflowState } = vi.hoisted(() => ({
mockWorkflowState: {
knowledgeName: '',
appName: 'Demo App',
},
}))
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- open: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div>{children}</div>
- </DropdownMenuContext>
- ),
- DropdownMenuTrigger: ({
- children,
- render,
- className,
- }: {
- children: React.ReactNode
- render?: React.ReactElement<{
- className?: string
- disabled?: boolean
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- }>
- className?: string
- }) => {
- const { open, setOpen } = useDropdownMenuContext()
- if (render) {
- return React.cloneElement(
- render,
- {
- className,
- onClick: () => setOpen(!open),
- },
- children,
- )
- }
- return (
- <button type="button" className={className} onClick={() => setOpen(!open)}>
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({
- children,
- ...positioningProps
- }: {
- children: React.ReactNode
- placement?: string
- sideOffset?: number
- alignOffset?: number
- popupClassName?: string
- }) => {
- mockDropdownContentProps(positioningProps)
- const { open } = useDropdownMenuContext()
- return open ? <div>{children}</div> : null
- },
- DropdownMenuItem: ({
- children,
- onClick,
- className,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- className?: string
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- className={className}
- onClick={(event) => {
- onClick?.(event)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- DropdownMenuSeparator: ({ className }: { className?: string }) => (
- <div className={className} data-testid="dropdown-separator" />
- ),
- }
-})
vi.mock('html-to-image', () => ({
toPng: (...args: unknown[]) => mockToPng(...args),
@@ -182,15 +82,6 @@ describe('MoreActions', () => {
document.body.appendChild(viewport)
})
- it('opens the menu to the right of the workflow control bar', () => {
- render(<MoreActions />)
-
- expect(mockDropdownContentProps).toHaveBeenCalledWith({
- placement: 'right-end',
- popupClassName: 'min-w-[180px]',
- })
- })
-
it('opens the menu and exports the current view as png', async () => {
const user = userEvent.setup()
diff --git a/web/app/components/workflow/panel/comments-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/comments-panel/__tests__/index.spec.tsx
index fbd7286f182..fda61b5595c 100644
--- a/web/app/components/workflow/panel/comments-panel/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/panel/comments-panel/__tests__/index.spec.tsx
@@ -94,24 +94,6 @@ vi.mock('@/app/components/base/user-avatar-list', () => ({
UserAvatarList: () => <div data-testid="user-avatar-list" />,
}))
-vi.mock('@langgenius/dify-ui/switch', () => ({
- Switch: ({
- checked,
- onCheckedChange,
- }: {
- checked: boolean
- onCheckedChange: (value: boolean) => void
- }) => (
- <button
- type="button"
- data-testid="show-resolved-switch"
- onClick={() => onCheckedChange(!checked)}
- >
- toggle
- </button>
- ),
-}))
-
describe('CommentsPanel', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -152,7 +134,7 @@ describe('CommentsPanel', () => {
render(<CommentsPanel />)
fireEvent.click(screen.getByLabelText('workflow.comments.aria.filterComments'))
- fireEvent.click(screen.getByTestId('show-resolved-switch'))
+ fireEvent.click(screen.getByRole('switch'))
expect(mockSetShowResolvedComments).toHaveBeenCalledWith(false)
})
diff --git a/web/app/components/workflow/run/agent-log/__tests__/agent-log-nav-more.spec.tsx b/web/app/components/workflow/run/agent-log/__tests__/agent-log-nav-more.spec.tsx
index 5c4380f8856..1c660887fc9 100644
--- a/web/app/components/workflow/run/agent-log/__tests__/agent-log-nav-more.spec.tsx
+++ b/web/app/components/workflow/run/agent-log/__tests__/agent-log-nav-more.spec.tsx
@@ -3,82 +3,6 @@ import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import AgentLogNavMore from '../agent-log-nav-more'
-vi.mock('@langgenius/dify-ui/dropdown-menu', async () => {
- const React = await import('react')
- const DropdownMenuContext = React.createContext<{
- open: boolean
- setOpen: (open: boolean) => void
- } | null>(null)
-
- const useDropdownMenuContext = () => {
- const context = React.use(DropdownMenuContext)
- if (!context) throw new Error('DropdownMenu components must be wrapped in DropdownMenu')
- return context
- }
-
- return {
- DropdownMenu: ({
- children,
- open,
- onOpenChange,
- }: {
- children: React.ReactNode
- open: boolean
- onOpenChange?: (open: boolean) => void
- }) => (
- <DropdownMenuContext value={{ open, setOpen: onOpenChange ?? vi.fn() }}>
- <div>{children}</div>
- </DropdownMenuContext>
- ),
- DropdownMenuTrigger: ({
- children,
- render,
- }: {
- children: React.ReactNode
- render?: React.ReactElement
- }) => {
- const { open, setOpen } = useDropdownMenuContext()
-
- if (render)
- return React.cloneElement(
- render,
- { onClick: () => setOpen(!open) } as Record<string, unknown>,
- children,
- )
-
- return (
- <button type="button" onClick={() => setOpen(!open)}>
- {children}
- </button>
- )
- },
- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => {
- const { open } = useDropdownMenuContext()
- return open ? <div>{children}</div> : null
- },
- DropdownMenuItem: ({
- children,
- onClick,
- }: {
- children: React.ReactNode
- onClick?: React.MouseEventHandler<HTMLButtonElement>
- }) => {
- const { setOpen } = useDropdownMenuContext()
- return (
- <button
- type="button"
- onClick={(event) => {
- onClick?.(event)
- setOpen(false)
- }}
- >
- {children}
- </button>
- )
- },
- }
-})
-
const createLogItem = (
overrides: Partial<AgentLogItemWithChildren> = {},
): AgentLogItemWithChildren => ({
diff --git a/web/docs/test.md b/web/docs/test.md
index 27923700e17..3d41ca31b24 100644
--- a/web/docs/test.md
+++ b/web/docs/test.md
@@ -83,7 +83,7 @@ Keep the production code that owns or transforms the asserted behavior real. Moc
- External SDKs and expensive providers.
- Independently tested child boundaries that do not own or transform the asserted behavior and whose setup would otherwise dominate the owner test.
-Mocks must preserve the public contract needed by the test. Do not replace Dify UI or legacy base primitives with semantically inaccurate stubs just to make a test easier.
+Mocks must preserve the public contract needed by the test. Do not mock interactive Dify UI primitives or feature-owned wrappers around them. Keep their semantic roles, state attributes, portals, focus behavior, and `render(props, state)` contract real; mock only service or external-data boundaries needed to reach the scenario.
- Never make real network requests.
- Reset shared mock state before each test that mutates it.
diff --git a/web/features/deployments/shared/components/__tests__/title-tooltip.spec.tsx b/web/features/deployments/shared/components/__tests__/title-tooltip.spec.tsx
index 131771e5daa..6f9abf66b68 100644
--- a/web/features/deployments/shared/components/__tests__/title-tooltip.spec.tsx
+++ b/web/features/deployments/shared/components/__tests__/title-tooltip.spec.tsx
@@ -1,14 +1,8 @@
-import type { ReactNode } from 'react'
-import { fireEvent, render, screen } from '@testing-library/react'
-import { describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it } from 'vitest'
import { TitleTooltip } from '../title-tooltip'
-vi.mock('@langgenius/dify-ui/tooltip', () => ({
- Tooltip: ({ children }: { children: ReactNode }) => <div data-testid="tooltip">{children}</div>,
- TooltipTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,
- TooltipContent: ({ children }: { children: ReactNode }) => <div role="tooltip">{children}</div>,
-}))
-
function setElementSize(
element: HTMLElement,
{
@@ -38,7 +32,8 @@ describe('TitleTooltip', () => {
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument()
})
- it('shows duplicate content when the trigger is truncated', () => {
+ it('shows duplicate content when the trigger is truncated', async () => {
+ const user = userEvent.setup()
render(
<TitleTooltip content="Long deployment name">
<p>Long deployment name</p>
@@ -47,22 +42,23 @@ describe('TitleTooltip', () => {
const trigger = screen.getByText('Long deployment name')
setElementSize(trigger, { clientWidth: 80, scrollWidth: 160 })
- fireEvent.pointerOver(trigger)
+ await user.hover(trigger)
- expect(screen.getByRole('tooltip')).toHaveTextContent('Long deployment name')
+ await waitFor(() => {
+ expect(screen.getAllByText('Long deployment name')).toHaveLength(2)
+ })
})
- it('shows content that adds information beyond the trigger text', () => {
+ it('shows content that adds information beyond the trigger text', async () => {
+ const user = userEvent.setup()
render(
<TitleTooltip content="Disabled until an initial release exists">
<button type="button">Deploy</button>
</TitleTooltip>,
)
- fireEvent.pointerOver(screen.getByRole('button', { name: 'Deploy' }))
+ await user.hover(screen.getByRole('button', { name: 'Deploy' }))
- expect(screen.getByRole('tooltip')).toHaveTextContent(
- 'Disabled until an initial release exists',
- )
+ expect(await screen.findByText('Disabled until an initial release exists')).toBeInTheDocument()
})
})