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): exercise snippet and marketplace owners with real state (#44724)

Stephen Zhou2d78a7846dec
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-view.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-view.spec.tsx
index 536a55d822e..7eeb3319b45 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-view.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/__tests__/selector-view.spec.tsx
@@ -1,124 +1,130 @@
-import type { TriggerSubscription } from '@/app/components/workflow/block-selector/types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { TriggerCredentialType } from '@/app/components/workflow/block-selector/types'
-import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { useState } from 'react'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
+import { usePluginStore } from '../../store'
import { SubscriptionSelectorView } from '../selector-view'
-let mockSubscriptions: TriggerSubscription[] = []
-const mockRefetch = vi.fn()
-const { mockDelete } = vi.hoisted(() => ({ mockDelete: vi.fn().mockResolvedValue({}) }))
-
-vi.mock('../use-subscription-list', () => ({
- useSubscriptionList: () => ({ subscriptions: mockSubscriptions, refetch: mockRefetch }),
-}))
-
-vi.mock('@/service/use-triggers', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/use-triggers')>()),
- useTriggerProviderInfo: () => ({ data: { supported_creation_methods: [] } }),
- useTriggerOAuthConfig: () => ({ data: undefined, refetch: vi.fn() }),
- useInitiateTriggerOAuth: () => ({ mutate: vi.fn() }),
-}))
-
+const requests = vi.hoisted(() => ({ list: vi.fn(), remove: vi.fn() }))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleClient: withConsoleClientResponses(actual.consoleClient, {
- 'workspaces.current.triggerProvider.bySubscriptionId.subscriptions.delete.post': mockDelete,
+ 'workspaces.current.triggerProvider.byProvider.subscriptions.list.get': requests.list,
+ 'workspaces.current.triggerProvider.bySubscriptionId.subscriptions.delete.post':
+ requests.remove,
}),
}
})
-vi.mock('@/app/notifications', async (importOriginal) => ({
- ...(await importOriginal()),
- 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(),
- }),
-}))
-
-const createSubscription = (overrides: Partial<TriggerSubscription> = {}): TriggerSubscription => ({
+const subscription = {
id: 'sub-1',
name: 'Subscription One',
provider: 'provider-1',
- credential_type: TriggerCredentialType.ApiKey,
+ credential_type: 'api-key',
credentials: {},
endpoint: 'https://example.com',
parameters: {},
properties: {},
workflows_in_use: 0,
- ...overrides,
-})
-
+}
+function Caller({ initiallySelected = false }) {
+ const [selected, setSelected] = useState(initiallySelected ? subscription : { id: '', name: '' })
+ return (
+ <>
+ <output aria-label="Selected subscription">
+ {selected.id ? `${selected.id}: ${selected.name}` : 'None'}
+ </output>
+ <SubscriptionSelectorView selectedId={selected.id} onSelect={setSelected} />
+ </>
+ )
+}
+function renderSelector(initiallySelected = false) {
+ // The area's singleton store is seeded before mount and reset by vitest.setup.ts.
+ usePluginStore.setState({
+ detail: {
+ id: 'plugin-1',
+ plugin_id: 'plugin-1',
+ name: 'Trigger',
+ plugin_unique_identifier: 'plugin-1@1',
+ provider: 'provider-1',
+ declaration: {},
+ },
+ })
+ const queryClient = createConsoleQueryClient()
+ queryClient.setQueryData(
+ consoleQuery.workspaces.current.triggerProvider.byProvider.info.get.queryKey({
+ input: { params: { provider: 'provider-1' } },
+ }),
+ {
+ author: 'Dify',
+ plugin_id: 'plugin-1',
+ plugin_unique_identifier: 'plugin-1@1',
+ name: 'Trigger',
+ label: { en_US: 'Trigger' },
+ description: { en_US: 'Trigger provider' },
+ supported_creation_methods: [],
+ events: [],
+ subscription_schema: [],
+ subscription_constructor: null,
+ },
+ )
+ return renderWithConsoleQuery(<Caller initiallySelected={initiallySelected} />, { queryClient })
+}
beforeEach(() => {
- vi.clearAllMocks()
- mockSubscriptions = [createSubscription()]
+ requests.list.mockReset().mockResolvedValue([subscription])
+ requests.remove.mockReset().mockResolvedValue({})
})
-describe('SubscriptionSelectorView', () => {
- it('should call onSelect when a subscription is clicked', async () => {
- const user = userEvent.setup()
- const onSelect = vi.fn()
-
- render(<SubscriptionSelectorView onSelect={onSelect} />)
-
- expect(screen.getByText(/pluginTrigger\.subscription\.listNum/)).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'Subscription One' }))
-
- expect(onSelect).toHaveBeenCalledWith(
- expect.objectContaining({ id: 'sub-1', name: 'Subscription One' }),
- )
- })
-
- it('should omit header when there are no subscriptions', () => {
- mockSubscriptions = []
-
- render(<SubscriptionSelectorView />)
-
- expect(screen.queryByText(/pluginTrigger\.subscription\.listNum/)).not.toBeInTheDocument()
- })
-
- it('should request selection reset after confirming delete', async () => {
- const user = userEvent.setup()
- const onSelect = vi.fn()
- render(<SubscriptionSelectorView onSelect={onSelect} />)
-
- await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
- expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
- expect(onSelect).not.toHaveBeenCalled()
-
- await user.click(
- screen.getByRole('button', {
- name: /pluginTrigger\.subscription\.list\.item\.actions\.deleteConfirm\.confirm/,
- }),
- )
-
- await waitFor(() => expect(onSelect).toHaveBeenCalledWith({ id: '', name: '' }))
- expect(mockDelete).toHaveBeenCalledWith({ params: { subscription_id: 'sub-1' } })
- })
-
- it('should close delete confirm without selection reset on cancel', async () => {
- const user = userEvent.setup()
- const onSelect = vi.fn()
- render(<SubscriptionSelectorView onSelect={onSelect} />)
-
- await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
- expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
- expect(onSelect).not.toHaveBeenCalled()
-
- await user.click(screen.getByRole('button', { name: /common\.operation\.cancel/ }))
-
- expect(onSelect).not.toHaveBeenCalled()
- expect(
- screen.queryByText(/pluginTrigger\.subscription\.list\.item\.actions\.deleteConfirm\.title/),
- ).not.toBeInTheDocument()
- })
+it('selects a subscription loaded for the current provider', async () => {
+ const user = userEvent.setup()
+ renderSelector()
+ await user.click(await screen.findByRole('button', { name: 'Subscription One' }))
+ expect(screen.getByLabelText('Selected subscription')).toHaveTextContent(
+ 'sub-1: Subscription One',
+ )
+ expect(screen.getByText(/pluginTrigger.subscription.listNum/)).toBeInTheDocument()
+ expect(requests.list).toHaveBeenCalledWith({ params: { provider: 'provider-1' } })
+})
+it('omits the header for an empty subscription response', async () => {
+ requests.list.mockResolvedValue([])
+ const { queryClient } = renderSelector()
+ await waitFor(() => expect(queryClient.isFetching()).toBe(0))
+ expect(screen.queryByText(/pluginTrigger.subscription.listNum/)).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'Subscription One' })).not.toBeInTheDocument()
+})
+it('removes the deleted subscription from the live list and clears the selection', async () => {
+ const user = userEvent.setup()
+ requests.list.mockResolvedValueOnce([subscription]).mockResolvedValue([])
+ renderSelector(true)
+ await screen.findByRole('button', { name: 'Subscription One' })
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
+ expect(screen.getByLabelText('Selected subscription')).toHaveTextContent(
+ 'sub-1: Subscription One',
+ )
+ await user.click(screen.getByRole('button', { name: /deleteConfirm.confirm/ }))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ await waitFor(() =>
+ expect(screen.queryByRole('button', { name: 'Subscription One' })).not.toBeInTheDocument(),
+ )
+ expect(screen.getByLabelText('Selected subscription')).toHaveTextContent('None')
+ expect(requests.remove).toHaveBeenCalledWith({ params: { subscription_id: 'sub-1' } })
+})
+it('keeps the selection and subscription after cancelling deletion', async () => {
+ const user = userEvent.setup()
+ renderSelector(true)
+ await screen.findByRole('button', { name: 'Subscription One' })
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ await screen.findByRole('alertdialog')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(screen.getByRole('button', { name: 'Subscription One' })).toBeInTheDocument()
+ expect(screen.getByLabelText('Selected subscription')).toHaveTextContent(
+ 'sub-1: Subscription One',
+ )
+ expect(requests.remove).not.toHaveBeenCalled()
})
diff --git a/web/app/components/tools/marketplace/__tests__/hooks.spec.ts b/web/app/components/tools/marketplace/__tests__/hooks.spec.ts
index 92a6fc14f70..e6a493e9cf7 100644
--- a/web/app/components/tools/marketplace/__tests__/hooks.spec.ts
+++ b/web/app/components/tools/marketplace/__tests__/hooks.spec.ts
@@ -1,201 +1,173 @@
-import type { ReactNode } from 'react'
-import type { Plugin } from '@/app/components/plugins/types'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import type { MarketplaceCollection } from '@dify/contracts/marketplace'
import { act, renderHook, waitFor } from '@testing-library/react'
-import { createElement } from 'react'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { SCROLL_BOTTOM_THRESHOLD } from '@/app/components/plugins/marketplace/constants'
-import { getMarketplaceListCondition } from '@/app/components/plugins/marketplace/utils'
-import { PluginCategoryEnum } from '@/app/components/plugins/types'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
import { useMarketplace } from '../hooks'
-// ==================== Mock Setup ====================
-
-const mockQueryMarketplaceCollectionsAndPlugins = vi.fn()
-const mockQueryPlugins = vi.fn()
-const mockResetQueryParams = vi.fn()
-const mockFetchNextPage = vi.fn()
-
-const mockUseMarketplaceCollectionsAndPlugins = vi.fn()
-const mockUseMarketplacePlugins = vi.fn()
-const mockFetchInstalledIds = vi.fn()
-vi.mock('@/app/components/plugins/marketplace/hooks', () => ({
- useMarketplaceCollectionsAndPlugins: (...args: unknown[]) =>
- mockUseMarketplaceCollectionsAndPlugins(...args),
- useMarketplacePlugins: (...args: unknown[]) => mockUseMarketplacePlugins(...args),
+const requests = vi.hoisted(() => ({
+ installed: vi.fn(),
+ search: vi.fn(),
+ collections: vi.fn(),
+ collectionPlugins: vi.fn(),
}))
-
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
- 'workspaces.current.plugin.installedIds.get': (...args: unknown[]) =>
- mockFetchInstalledIds(...args),
+ 'workspaces.current.plugin.installedIds.get': requests.installed,
}),
}
})
-
-vi.mock('@/utils/var', () => ({
- getMarketplaceUrl: vi.fn(() => 'https://marketplace.test/market'),
-}))
-
-// ==================== Test Utilities ====================
-
-const createWrapper = () => {
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- return function Wrapper({ children }: { children: ReactNode }) {
- return createElement(QueryClientProvider, { client: queryClient }, children)
+vi.mock('@/service/marketplace', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/marketplace')>()
+ return {
+ ...actual,
+ marketplaceClient: {
+ ...actual.marketplaceClient,
+ collections: requests.collections,
+ collectionPlugins: requests.collectionPlugins,
+ },
}
+})
+// The legacy search owner uses this transport; its query state and formatting stay real.
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal()),
+ postMarketplace: requests.search,
+}))
+const plugin = createMarketplacePluginFixture()
+const collection: MarketplaceCollection = {
+ rule: '',
+ created_at: '',
+ updated_at: '',
+ name: 'featured',
+ label: { en_US: 'Featured' },
+ description: { en_US: 'Featured tools' },
+ searchable: false,
+ search_params: {},
}
-
-const setupHookMocks = (overrides?: {
- isLoading?: boolean
- isPluginsLoading?: boolean
- pluginsPage?: number
- hasNextPage?: boolean
- plugins?: Plugin[] | undefined
-}) => {
- mockUseMarketplaceCollectionsAndPlugins.mockReturnValue({
- isLoading: overrides?.isLoading ?? false,
- marketplaceCollections: [],
- marketplaceCollectionPluginsMap: {},
- queryMarketplaceCollectionsAndPlugins: mockQueryMarketplaceCollectionsAndPlugins,
- })
- mockUseMarketplacePlugins.mockReturnValue({
- plugins: overrides?.plugins,
- resetQueryParams: mockResetQueryParams,
- queryPlugins: mockQueryPlugins,
- isLoading: overrides?.isPluginsLoading ?? false,
- fetchNextPage: mockFetchNextPage,
- hasNextPage: overrides?.hasNextPage ?? false,
- page: overrides?.pluginsPage,
+const response = (plugins = [plugin], total = plugins.length) => ({ data: { plugins, total } })
+function renderMarketplace(initial = { search: '', tags: [] as string[], enabled: true }) {
+ const { wrapper } = createConsoleQueryWrapper()
+ return renderHook(({ search, tags, enabled }) => useMarketplace(search, tags, enabled), {
+ wrapper,
+ initialProps: initial,
})
}
-
-// ==================== Tests ====================
-
-describe('useMarketplace', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockFetchInstalledIds.mockResolvedValue({ plugin_ids: [] })
- setupHookMocks()
+const scrollToEnd = (handleScroll: (event: Event) => void) => {
+ const container = document.createElement('div')
+ Object.defineProperties(container, {
+ scrollTop: { value: 200 },
+ scrollHeight: { value: 500 },
+ clientHeight: { value: 300 },
})
+ container.addEventListener('scroll', handleScroll)
+ act(() => container.dispatchEvent(new Event('scroll')))
+ container.removeEventListener('scroll', handleScroll)
+}
+beforeEach(() => {
+ requests.installed.mockReset().mockResolvedValue({ plugin_ids: ['installed-tool'] })
+ requests.search.mockReset().mockResolvedValue(response())
+ requests.collections.mockReset().mockResolvedValue({ data: { collections: [collection] } })
+ requests.collectionPlugins.mockReset().mockResolvedValue(response())
+})
- describe('Queries', () => {
- it('defers installed IDs and marketplace data until activation', async () => {
- const { rerender } = renderHook(({ enabled }) => useMarketplace('', [], enabled), {
- initialProps: { enabled: false },
- wrapper: createWrapper(),
- })
- expect(mockFetchInstalledIds).not.toHaveBeenCalled()
- expect(mockQueryMarketplaceCollectionsAndPlugins).not.toHaveBeenCalled()
- expect(mockQueryPlugins).not.toHaveBeenCalled()
- rerender({ enabled: true })
- await waitFor(() => expect(mockQueryMarketplaceCollectionsAndPlugins).toHaveBeenCalled())
- expect(mockFetchInstalledIds).toHaveBeenCalledOnce()
- })
-
- it('should query plugins when the debounced page filter provides search text', async () => {
- mockFetchInstalledIds.mockResolvedValue({ plugin_ids: ['plugin-a'] })
-
- renderHook(() => useMarketplace('alpha', []), { wrapper: createWrapper() })
-
- await waitFor(() => {
- expect(mockQueryPlugins).toHaveBeenCalledWith({
- category: PluginCategoryEnum.tool,
- query: 'alpha',
- tags: [],
- exclude: ['plugin-a'],
- type: 'plugin',
- })
- })
- expect(mockQueryMarketplaceCollectionsAndPlugins).not.toHaveBeenCalled()
- expect(mockResetQueryParams).not.toHaveBeenCalled()
- })
-
- it('should query plugins immediately when only tags are provided', async () => {
- mockFetchInstalledIds.mockResolvedValue({ plugin_ids: ['plugin-b'] })
-
- renderHook(() => useMarketplace('', ['tag-1']), { wrapper: createWrapper() })
-
- await waitFor(() => {
- expect(mockQueryPlugins).toHaveBeenCalledWith({
- category: PluginCategoryEnum.tool,
- query: '',
- tags: ['tag-1'],
- exclude: ['plugin-b'],
- type: 'plugin',
- })
- })
- })
-
- it('should query collections and reset plugins when no filters are provided', async () => {
- mockFetchInstalledIds.mockResolvedValue({ plugin_ids: ['plugin-c'] })
-
- renderHook(() => useMarketplace('', []), { wrapper: createWrapper() })
-
- await waitFor(() => {
- expect(mockQueryMarketplaceCollectionsAndPlugins).toHaveBeenCalledWith({
- category: PluginCategoryEnum.tool,
- condition: getMarketplaceListCondition(PluginCategoryEnum.tool),
- exclude: ['plugin-c'],
- type: 'plugin',
- })
- })
- expect(mockResetQueryParams).toHaveBeenCalledTimes(1)
- })
- })
-
- describe('State', () => {
- it('should expose combined loading state and fallback page value', () => {
- setupHookMocks({ isLoading: true, isPluginsLoading: false, pluginsPage: undefined })
-
- const { result } = renderHook(() => useMarketplace('', []), { wrapper: createWrapper() })
-
- expect(result.current.isLoading).toBe(true)
- expect(result.current.page).toBe(1)
- })
- })
-
- describe('Scroll', () => {
- it('should fetch next page when scrolling near bottom with filters', () => {
- setupHookMocks({ hasNextPage: true })
- const { result } = renderHook(() => useMarketplace('search', []), {
- wrapper: createWrapper(),
- })
- const event = {
- target: {
- scrollTop: 100,
- scrollHeight: 200,
- clientHeight: 100 + SCROLL_BOTTOM_THRESHOLD,
- },
- } as unknown as Event
-
- act(() => {
- result.current.handleScroll(event)
- })
-
- expect(mockFetchNextPage).toHaveBeenCalledTimes(1)
- })
-
- it('should not fetch next page when no filters are applied', () => {
- setupHookMocks({ hasNextPage: true })
- const { result } = renderHook(() => useMarketplace('', []), { wrapper: createWrapper() })
- const event = {
- target: {
- scrollTop: 100,
- scrollHeight: 200,
- clientHeight: 100 + SCROLL_BOTTOM_THRESHOLD,
- },
- } as unknown as Event
-
- act(() => {
- result.current.handleScroll(event)
- })
-
- expect(mockFetchNextPage).not.toHaveBeenCalled()
- })
+it('defers catalog requests until activation and then supplies the collection results', async () => {
+ const { result, rerender } = renderMarketplace({ search: '', tags: [], enabled: false })
+ expect(requests.installed).not.toHaveBeenCalled()
+ expect(requests.collections).not.toHaveBeenCalled()
+ expect(requests.search).not.toHaveBeenCalled()
+ rerender({ search: '', tags: [], enabled: true })
+ await waitFor(() =>
+ expect(result.current.marketplaceCollectionPluginsMap?.featured).toMatchObject([
+ { plugin_id: plugin.plugin_id },
+ ]),
+ )
+ expect(result.current.marketplaceCollections).toEqual([collection])
+ expect(result.current.isLoading).toBe(false)
+})
+it.each([
+ { search: 'alpha', tags: [] },
+ { search: '', tags: ['search'] },
+])('loads matching tools for search=$search and tags=$tags', async ({ search, tags }) => {
+ const { result } = renderMarketplace({ search, tags, enabled: true })
+ await waitFor(() =>
+ expect(result.current.plugins).toMatchObject([{ plugin_id: plugin.plugin_id }]),
+ )
+ expect(requests.search).toHaveBeenCalledWith('/plugins/search/advanced', {
+ body: {
+ category: 'tool',
+ query: search,
+ tags,
+ exclude: ['installed-tool'],
+ type: 'plugin',
+ page: 1,
+ page_size: 40,
+ sort_by: undefined,
+ sort_order: undefined,
+ },
+ signal: expect.any(AbortSignal),
})
+ expect(requests.collections).not.toHaveBeenCalled()
+})
+it('clears search results and restores collections when filters are removed', async () => {
+ const { result, rerender } = renderMarketplace({ search: 'alpha', tags: [], enabled: true })
+ await waitFor(() => expect(result.current.plugins).toHaveLength(1))
+ rerender({ search: '', tags: [], enabled: true })
+ await waitFor(() =>
+ expect(result.current.marketplaceCollectionPluginsMap?.featured).toHaveLength(1),
+ )
+ expect(result.current.plugins).toBeUndefined()
+ expect(requests.collections).toHaveBeenCalledWith(
+ {
+ query: expect.objectContaining({
+ category: 'tool',
+ exclude: ['installed-tool'],
+ type: 'plugin',
+ }),
+ },
+ { signal: expect.any(AbortSignal) },
+ )
+ expect(result.current.page).toBe(1)
+})
+it('reports loading until the requested first page arrives', async () => {
+ const pending = createDeferred<ReturnType<typeof response>>()
+ requests.search.mockReturnValue(pending.promise)
+ const { result } = renderMarketplace({ search: 'alpha', tags: [], enabled: true })
+ await waitFor(() => expect(result.current.isLoading).toBe(true))
+ expect(result.current.plugins).toBeUndefined()
+ expect(result.current.page).toBe(1)
+ await act(async () => pending.resolve(response()))
+ await waitFor(() => expect(result.current.plugins).toHaveLength(1))
+ expect(result.current.isLoading).toBe(false)
+})
+it('appends the next search page on scroll and stops paging after filters are cleared', async () => {
+ const second = createMarketplacePluginFixture({ plugin_id: 'second-tool', name: 'second-tool' })
+ const firstPage = Array.from({ length: 40 }, (_, index) =>
+ createMarketplacePluginFixture({ plugin_id: `tool-${index}`, name: `tool-${index}` }),
+ )
+ requests.search
+ .mockResolvedValueOnce(response(firstPage, 41))
+ .mockResolvedValue(response([second], 41))
+ const { result, rerender } = renderMarketplace({ search: 'alpha', tags: [], enabled: true })
+ await waitFor(() => expect(result.current.plugins).toHaveLength(40))
+ scrollToEnd(result.current.handleScroll)
+ await waitFor(() =>
+ expect(result.current.plugins?.map((item) => item.plugin_id)).toEqual([
+ ...firstPage.map((item) => item.plugin_id),
+ 'second-tool',
+ ]),
+ )
+ expect(result.current.page).toBe(2)
+ expect(requests.search).toHaveBeenLastCalledWith(
+ '/plugins/search/advanced',
+ expect.objectContaining({ body: expect.objectContaining({ page: 2, query: 'alpha' }) }),
+ )
+ rerender({ search: '', tags: [], enabled: true })
+ await waitFor(() => expect(result.current.marketplaceCollections).toEqual([collection]))
+ scrollToEnd(result.current.handleScroll)
+ expect(requests.search).toHaveBeenCalledTimes(2)
+ expect(result.current.plugins).toBeUndefined()
})
diff --git a/web/app/components/tools/marketplace/__tests__/index.spec.tsx b/web/app/components/tools/marketplace/__tests__/index.spec.tsx
index 4f4b8e8627f..2ccb1539ce8 100644
--- a/web/app/components/tools/marketplace/__tests__/index.spec.tsx
+++ b/web/app/components/tools/marketplace/__tests__/index.spec.tsx
@@ -1,242 +1,132 @@
-import type { SearchParamsFromCollection } from '@dify/contracts/marketplace'
-import type { useMarketplace } from '../hooks'
-import type { Plugin } from '@/app/components/plugins/types'
-import { render, screen } from '@testing-library/react'
+import type { MarketplaceCollection } from '@dify/contracts/marketplace'
+import type { ComponentProps } from 'react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import * as React from 'react'
-import { PluginCategoryEnum } from '@/app/components/plugins/types'
-import { getMarketplaceUrl } from '@/utils/var'
+import { useState } from 'react'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
+import { createNuqsTestRenderer } from '@/test/nuqs-testing'
import Marketplace from '../index'
-const { mockRouterPush } = vi.hoisted(() => ({
- mockRouterPush: vi.fn(),
-}))
-
-const { mockCanInstallPlugin } = vi.hoisted(() => ({
- mockCanInstallPlugin: vi.fn(() => true),
-}))
-
-const listRenderSpy = vi.fn()
-vi.mock('@/app/components/plugins/marketplace/list', () => ({
- default: (props: {
- marketplaceCollections: unknown[]
- marketplaceCollectionPluginsMap: Record<string, unknown[]>
- cardContainerClassName?: string
- plugins?: unknown[]
- showInstallButton?: boolean
- onCollectionMoreClick?: (searchParams?: SearchParamsFromCollection) => void
- }) => {
- listRenderSpy(props)
- return (
- <div data-testid="marketplace-list">
- <button
- onClick={() =>
- props.onCollectionMoreClick?.({
- query: 'featured tools',
- sort_by: 'install_count',
- sort_order: 'DESC',
- })
- }
- >
- More featured tools
- </button>
- </div>
- )
- },
-}))
-
-vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({
- usePluginSettingsAccess: () => ({
- canInstallPlugin: mockCanInstallPlugin(),
- }),
-}))
-
-const mockUseMarketplaceCollectionsAndPlugins = vi.fn()
-const mockUseMarketplacePlugins = vi.fn()
-vi.mock('@/app/components/plugins/marketplace/hooks', () => ({
- useMarketplaceCollectionsAndPlugins: (...args: unknown[]) =>
- mockUseMarketplaceCollectionsAndPlugins(...args),
- useMarketplacePlugins: (...args: unknown[]) => mockUseMarketplacePlugins(...args),
-}))
-
-vi.mock('@/utils/var', () => ({
- getMarketplaceUrl: vi.fn(() => 'https://marketplace.test/market'),
-}))
-
-const mockGetMarketplaceUrl = vi.mocked(getMarketplaceUrl)
-
-vi.mock('@/next/navigation', () => ({
- useRouter: () => ({
- push: mockRouterPush,
- }),
-}))
-
-const createPlugin = (overrides: Partial<Plugin> = {}): Plugin => ({
- type: 'plugin',
- org: 'org',
- author: 'author',
- name: 'Plugin One',
- plugin_id: 'plugin-1',
- version: '1.0.0',
- latest_version: '1.0.0',
- latest_package_identifier: '[email protected]',
- icon: 'icon',
- verified: true,
- label: { en_US: 'Plugin One' },
- brief: { en_US: 'Brief' },
- description: { en_US: 'Plugin description' },
- introduction: 'Intro',
- repository: 'https://example.com',
- category: PluginCategoryEnum.tool,
- install_count: 0,
- endpoint: { settings: [] },
- tags: [{ name: 'tag' }],
- badges: [],
- verification: { authorized_category: 'community' },
- from: 'marketplace',
- ...overrides,
+const requests = vi.hoisted(() => ({ push: vi.fn() }))
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: requests.push }) }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.plugin.permission.fetch.get': () => ({
+ install_permission: 'everyone',
+ debug_permission: 'everyone',
+ }),
+ }),
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.plugin.list.installations.ids.post': () => ({ plugins: [] }),
+ }),
+ }
})
-
-const createMarketplaceContext = (overrides: Partial<ReturnType<typeof useMarketplace>> = {}) => ({
+const render = createNuqsTestRenderer(renderWithConsoleQuery)
+
+type Props = ComponentProps<typeof Marketplace>
+const plugin = createMarketplacePluginFixture({ label: { en_US: 'Search Tool' }, tags: [] })
+const collection: MarketplaceCollection = {
+ name: 'featured',
+ label: { en_US: 'Featured tools' },
+ description: { en_US: 'Recommended tools' },
+ rule: '',
+ created_at: '',
+ updated_at: '',
+ searchable: true,
+ search_params: { query: 'featured tools', sort_by: 'install_count', sort_order: 'DESC' },
+}
+const context = (
+ overrides: Partial<Props['marketplaceContext']> = {},
+): Props['marketplaceContext'] => ({
isLoading: false,
marketplaceCollections: [],
marketplaceCollectionPluginsMap: {},
- plugins: [],
- handleScroll: vi.fn(),
+ plugins: [plugin],
+ handleScroll: () => {},
page: 1,
...overrides,
})
-
-describe('Marketplace', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockCanInstallPlugin.mockReturnValue(true)
- })
-
- // Rendering the marketplace panel based on loading and visibility state.
- describe('Rendering', () => {
- it('should show loading indicator when loading first page', () => {
- // Arrange
- const marketplaceContext = createMarketplaceContext({ isLoading: true, page: 1 })
- render(
- <Marketplace
- searchPluginText=""
- filterPluginTags={[]}
- isMarketplaceArrowVisible={false}
- showMarketplacePanel={vi.fn()}
- marketplaceContext={marketplaceContext}
- />,
- )
-
- // Assert
- expect(screen.queryByRole('progressbar')).toBeInTheDocument()
- expect(screen.queryByTestId('marketplace-list')).not.toBeInTheDocument()
- })
-
- it('should render list when not loading', () => {
- // Arrange
- const marketplaceContext = createMarketplaceContext({
- isLoading: false,
- plugins: [createPlugin()],
- })
- render(
- <Marketplace
- searchPluginText=""
- filterPluginTags={[]}
- isMarketplaceArrowVisible={false}
- showMarketplacePanel={vi.fn()}
- marketplaceContext={marketplaceContext}
- />,
- )
-
- // Assert
- expect(screen.getByTestId('marketplace-list')).toBeInTheDocument()
- expect(listRenderSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- showInstallButton: true,
- }),
- )
- })
-
- it('should hide install actions when plugin install permission is missing', () => {
- mockCanInstallPlugin.mockReturnValue(false)
- const marketplaceContext = createMarketplaceContext({
- isLoading: false,
- plugins: [createPlugin()],
- })
-
- render(
- <Marketplace
- searchPluginText=""
- filterPluginTags={[]}
- isMarketplaceArrowVisible={false}
- showMarketplacePanel={vi.fn()}
- marketplaceContext={marketplaceContext}
- />,
- )
-
- expect(listRenderSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- showInstallButton: false,
- }),
- )
- })
- })
-
- // Prop-driven UI output such as links and action triggers.
- describe('Props', () => {
- it('should build marketplace link and trigger panel when arrow is clicked', async () => {
- const user = userEvent.setup()
- // Arrange
- const marketplaceContext = createMarketplaceContext()
- const showMarketplacePanel = vi.fn()
- render(
+function renderMarketplace(props: Partial<Props> = {}, canInstall = true) {
+ return render(
+ <Marketplace
+ searchPluginText=""
+ filterPluginTags={[]}
+ isMarketplaceArrowVisible={false}
+ showMarketplacePanel={() => {}}
+ marketplaceContext={context()}
+ {...props}
+ />,
+ {
+ workspacePermissionKeys: canInstall ? ['plugin.install'] : [],
+ systemFeatures: { rbac_enabled: true },
+ },
+ )
+}
+it('shows loading in place of plugin cards while the first page is pending', () => {
+ renderMarketplace({ marketplaceContext: context({ isLoading: true }) })
+ expect(screen.getByRole('progressbar')).toBeInTheDocument()
+ expect(screen.queryByText('Search Tool')).not.toBeInTheDocument()
+})
+it('renders the plugin and its install action for an allowed workspace', async () => {
+ renderMarketplace()
+ expect(await screen.findByText('Search Tool')).toBeInTheDocument()
+ expect(
+ await screen.findByRole('button', { name: 'plugin.detailPanel.operation.install' }),
+ ).toBeEnabled()
+})
+it('keeps the plugin visible but removes install actions without installation permission', async () => {
+ renderMarketplace({}, false)
+ expect(await screen.findByText('Search Tool')).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'plugin.detailPanel.operation.install' }),
+ ).not.toBeInTheDocument()
+})
+it('opens the caller panel and exposes a marketplace link with the current filters', async () => {
+ const user = userEvent.setup()
+ function Caller() {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ {open && <section aria-label="Marketplace panel">Expanded marketplace</section>}
<Marketplace
searchPluginText="vector"
filterPluginTags={['tag-a', 'tag-b']}
isMarketplaceArrowVisible
- showMarketplacePanel={showMarketplacePanel}
- marketplaceContext={marketplaceContext}
- />,
- )
-
- // Act
- await user.click(screen.getByRole('button', { name: /plugin.marketplace.moreFrom/i }))
-
- // Assert
- expect(showMarketplacePanel).toHaveBeenCalledTimes(1)
- expect(mockGetMarketplaceUrl).toHaveBeenCalledWith('', {
- language: 'en-US',
- q: 'vector',
- tags: 'tag-a,tag-b',
- theme: undefined,
- })
- const marketplaceLink = screen.getByRole('link', {
- name: /plugin.marketplace.difyMarketplace/i,
- })
- expect(marketplaceLink).toHaveAttribute('href', 'https://marketplace.test/market')
- })
-
- it('should open integrations marketplace when collection more is clicked', async () => {
- const user = userEvent.setup()
- const marketplaceContext = createMarketplaceContext()
- render(
- <Marketplace
- searchPluginText=""
- filterPluginTags={[]}
- isMarketplaceArrowVisible={false}
- showMarketplacePanel={vi.fn()}
- marketplaceContext={marketplaceContext}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: 'More featured tools' }))
-
- expect(mockRouterPush).toHaveBeenCalledWith(
- '/marketplace?category=tool&q=featured+tools&sort_by=install_count&sort_order=DESC',
- )
- })
+ showMarketplacePanel={() => setOpen(true)}
+ marketplaceContext={context()}
+ />
+ </>
+ )
+ }
+ render(<Caller />, {
+ workspacePermissionKeys: ['plugin.install'],
+ systemFeatures: { rbac_enabled: true },
})
+ await user.click(screen.getByRole('button', { name: 'plugin.marketplace.moreFrom' }))
+ expect(screen.getByRole('region', { name: 'Marketplace panel' })).toBeInTheDocument()
+ const link = screen.getByRole('link', { name: 'plugin.marketplace.difyMarketplace' })
+ const url = new URL(link.getAttribute('href')!, window.location.origin)
+ expect(url.searchParams.get('q')).toBe('vector')
+ expect(url.searchParams.get('tags')).toBe('tag-a,tag-b')
+ expect(url.searchParams.get('language')).toBe('en-US')
+})
+it('opens the integrations marketplace from the real collection more button', async () => {
+ const user = userEvent.setup()
+ renderMarketplace({
+ marketplaceContext: context({
+ plugins: undefined,
+ marketplaceCollections: [collection],
+ marketplaceCollectionPluginsMap: { featured: [plugin] },
+ }),
+ })
+ await user.click(await screen.findByRole('button', { name: 'plugin.marketplace.viewMore' }))
+ expect(requests.push).toHaveBeenCalledWith(
+ '/marketplace?category=tool&q=featured+tools&sort_by=install_count&sort_order=DESC',
+ )
})
-
-// useMarketplace hook tests moved to hooks.spec.ts
diff --git a/web/app/components/workflow/block-selector/snippets/__tests__/index.spec.tsx b/web/app/components/workflow/block-selector/snippets/__tests__/index.spec.tsx
index 444e8d5dbea..26a2172de7c 100644
--- a/web/app/components/workflow/block-selector/snippets/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/block-selector/snippets/__tests__/index.spec.tsx
@@ -1,254 +1,205 @@
import type { ReactElement } from 'react'
-import { screen, waitFor } from '@testing-library/react'
+import type { Edge, Node } from '../../../types'
+import type { SnippetListItem, SnippetListResponse } from '@/types/snippet'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
+import { useEdges, useNodes } from 'reactflow'
import { consoleQuery } from '@/service/console'
-import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
+import { createConsoleQueryClient } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { createEdge, createNode } from '../../../__tests__/fixtures'
+import { renderWorkflowFlowComponent } from '../../../__tests__/workflow-test-env'
import Snippets from '../index'
-const mockUseInfiniteSnippetList = vi.fn()
-const mockHandleInsertSnippet = vi.fn()
-
-vi.mock('@/service/use-snippets', () => ({
- useInfiniteSnippetList: (...args: unknown[]) => mockUseInfiniteSnippetList(...args),
-}))
-
-vi.mock('../use-insert-snippet', () => ({
- useInsertSnippet: () => ({
- handleInsertSnippet: mockHandleInsertSnippet,
- }),
-}))
-
-vi.mock('@/service/use-snippet-workflows', () => ({
- useSnippetPublishedWorkflow: () => ({ data: undefined }),
-}))
-
-const render = (ui: ReactElement) => {
+const requests = vi.hoisted(() => ({ list: vi.fn(), increment: vi.fn() }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.customizedSnippets.get': requests.list,
+ 'workspaces.current.customizedSnippets.bySnippetId.useCount.increment.post':
+ requests.increment,
+ }),
+ }
+})
+const snippet: SnippetListItem = {
+ id: 'snippet-1',
+ name: 'Customer Review',
+ description: 'Snippet description',
+ type: 'group',
+ is_published: true,
+ version: 1,
+ use_count: 3,
+ tags: [],
+ created_at: 1,
+ created_by: 'user-1',
+ updated_at: 2,
+ updated_by: 'user-1',
+}
+const page = (data = [snippet]): SnippetListResponse => ({
+ data,
+ page: 1,
+ limit: 30,
+ total: data.length,
+ has_more: false,
+})
+function Canvas() {
+ const nodes = useNodes()
+ const edges = useEdges()
+ return <output aria-label="Canvas graph">{JSON.stringify({ nodes, edges })}</output>
+}
+function renderSnippets(ui: ReactElement = <Snippets searchText="" />) {
const queryClient = createConsoleQueryClient()
queryClient.setQueryData(
consoleQuery.tags.get.queryKey({ input: { query: { type: 'snippet' } } }),
[{ id: 'tag-1', name: 'Sales', type: 'snippet', binding_count: '' }],
)
- return renderWithConsoleQuery(ui, { queryClient })
+ queryClient.setQueryData(
+ consoleQuery.snippets.bySnippetId.workflows.publish.get.queryKey({
+ input: { params: { snippet_id: 'snippet-1' } },
+ }),
+ {
+ id: 'published-1',
+ version: '1',
+ hash: 'published-hash',
+ created_at: 1,
+ updated_at: 2,
+ marked_name: '',
+ marked_comment: '',
+ features: {},
+ conversation_variables: [],
+ environment_variables: [],
+ rag_pipeline_variables: [],
+ tool_published: false,
+ graph: {
+ nodes: [
+ createNode({ id: 'first', data: { title: 'Review input' } }),
+ createNode({ id: 'second', data: { title: 'Review result' } }),
+ ],
+ edges: [createEdge({ source: 'first', target: 'second' })],
+ },
+ },
+ )
+ return {
+ queryClient,
+ ...renderWorkflowFlowComponent(
+ <>
+ {ui}
+ <Canvas />
+ </>,
+ {
+ queryClient,
+ nodes: [
+ createNode({
+ id: 'existing',
+ selected: true,
+ data: { title: 'Existing node', selected: true },
+ }),
+ ],
+ },
+ ),
+ }
}
+beforeEach(() => {
+ requests.list.mockReset().mockResolvedValue(page())
+ requests.increment.mockReset().mockResolvedValue({ use_count: 4 })
+})
-describe('Snippets', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseInfiniteSnippetList.mockReturnValue({
- data: undefined,
- isLoading: false,
- isFetching: false,
- isFetchingNextPage: false,
- fetchNextPage: vi.fn(),
- hasNextPage: false,
- })
+it('shows loading until the snippet query resolves', async () => {
+ const pending = createDeferred<ReturnType<typeof page>>()
+ requests.list.mockReturnValue(pending.promise)
+ renderSnippets()
+ expect(screen.getByRole('status', { name: 'common.loading' })).toBeInTheDocument()
+ await act(async () => pending.resolve(page()))
+ expect(await screen.findByRole('button', { name: /Customer Review/ })).toBeInTheDocument()
+ expect(screen.queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()
+})
+it('shows the empty state after an empty response', async () => {
+ requests.list.mockResolvedValue(page([]))
+ renderSnippets()
+ expect(await screen.findByText('workflow.tabs.noSnippetsFound')).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'workflow.tabs.createSnippet' }),
+ ).not.toBeInTheDocument()
+})
+it('keeps cached rows visible while the current search refreshes', async () => {
+ const pending = createDeferred<ReturnType<typeof page>>()
+ const { queryClient } = renderSnippets(<Snippets searchText="customer" />)
+ await screen.findByRole('button', { name: /Customer Review/ })
+ requests.list.mockReturnValue(pending.promise)
+ act(() => {
+ void queryClient.invalidateQueries({ queryKey: ['snippets', 'list'] })
})
-
- describe('Rendering', () => {
- it('should render loading skeleton when loading', () => {
- mockUseInfiniteSnippetList.mockReturnValue({
- data: undefined,
- isLoading: true,
- isFetching: true,
- isFetchingNextPage: false,
- fetchNextPage: vi.fn(),
- hasNextPage: undefined,
- })
-
- render(<Snippets searchText="" />)
-
- expect(screen.getByRole('status', { name: 'common.loading' })).toBeInTheDocument()
- })
-
- it('should render empty state when snippet list is empty', () => {
- render(<Snippets searchText="" />)
-
- expect(screen.getByText('workflow.tabs.noSnippetsFound')).toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'workflow.tabs.createSnippet' }),
- ).not.toBeInTheDocument()
- })
-
- it('should keep cached snippet rows visible while refetching', () => {
- mockUseInfiniteSnippetList.mockReturnValue({
- data: {
- pages: [
- {
- data: [
- {
- id: 'snippet-1',
- name: 'Customer Review',
- description: 'Snippet description',
- type: 'group',
- is_published: true,
- version: 1,
- use_count: 3,
- tags: [],
- input_fields: [],
- created_at: 1,
- created_by: 'user-1',
- updated_at: 2,
- updated_by: 'user-1',
- },
- ],
- },
- ],
- },
- isLoading: false,
- isFetching: true,
- isFetchingNextPage: false,
- fetchNextPage: vi.fn(),
- hasNextPage: false,
- })
-
- render(<Snippets searchText="customer" />)
-
- expect(mockUseInfiniteSnippetList).toHaveBeenCalledWith({
- page: 1,
- limit: 30,
- keyword: 'customer',
- is_published: true,
- })
- expect(screen.getByText('Customer Review')).toBeInTheDocument()
- })
+ await waitFor(() => expect(queryClient.isFetching()).toBe(1))
+ expect(screen.getByRole('button', { name: /Customer Review/ })).toBeInTheDocument()
+ expect(screen.queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()
+ expect(requests.list).toHaveBeenLastCalledWith({
+ query: { page: 1, limit: 30, keyword: 'customer', is_published: true },
})
-
- describe('User Interactions', () => {
- it('should filter snippets by selected snippet tags', async () => {
- const user = userEvent.setup()
- render(<Snippets searchText="" />)
-
- await user.click(await screen.findByRole('button', { name: 'common.tag.placeholder' }))
- await user.click(await screen.findByRole('checkbox', { name: 'Sales' }))
-
- await waitFor(() => {
- expect(mockUseInfiniteSnippetList).toHaveBeenLastCalledWith({
- page: 1,
- limit: 30,
- tag_ids: ['tag-1'],
- is_published: true,
- })
- })
- })
-
- it('should delegate embedded search changes', async () => {
- const user = userEvent.setup()
- const onSearchTextChange = vi.fn()
-
- function Harness() {
- const [searchText, setSearchText] = useState('')
-
- return (
- <Snippets
- searchText={searchText}
- onSearchTextChange={(value) => {
- setSearchText(value)
- onSearchTextChange(value)
- }}
- />
- )
- }
-
- render(<Harness />)
-
- await user.type(
- screen.getByRole('searchbox', { name: 'workflow.tabs.searchSnippets' }),
- 'review',
- )
-
- expect(onSearchTextChange).toHaveBeenLastCalledWith('review')
-
- const clearButton = screen.getByRole('button', {
- name: 'workflow.tabs.clearSnippetSearch',
- })
- await user.click(clearButton)
-
- expect(onSearchTextChange).toHaveBeenLastCalledWith('')
- })
-
- it('should expose snippet rows as buttons and delegate insertion', async () => {
- const user = userEvent.setup()
- mockUseInfiniteSnippetList.mockReturnValue({
- data: {
- pages: [
- {
- data: [
- {
- id: 'snippet-1',
- name: 'Customer Review',
- description: 'Snippet description',
- type: 'group',
- is_published: true,
- version: 1,
- use_count: 3,
- tags: [],
- input_fields: [],
- created_at: 1,
- created_by: 'user-1',
- updated_at: 2,
- updated_by: 'user-1',
- },
- ],
- },
- ],
- },
- isLoading: false,
- isFetching: false,
- isFetchingNextPage: false,
- fetchNextPage: vi.fn(),
- hasNextPage: false,
- })
-
- render(<Snippets searchText="" />)
-
- const snippet = screen.getByRole('button', { name: /Customer Review/ })
- await user.click(snippet)
-
- expect(mockHandleInsertSnippet).toHaveBeenCalledWith('snippet-1', undefined)
- })
-
- it('should show a preview from the keyboard when a snippet has no description', async () => {
- const user = userEvent.setup()
- mockUseInfiniteSnippetList.mockReturnValue({
- data: {
- pages: [
- {
- data: [
- {
- id: 'snippet-1',
- name: 'No Description',
- description: '',
- type: 'group',
- is_published: true,
- version: 1,
- use_count: 3,
- tags: [],
- input_fields: [],
- created_at: 1,
- created_by: 'user-1',
- updated_at: 2,
- updated_by: 'user-1',
- },
- ],
- },
- ],
- },
- isLoading: false,
- isFetching: false,
- isFetchingNextPage: false,
- fetchNextPage: vi.fn(),
- hasNextPage: false,
- })
-
- render(<Snippets searchText="" />)
-
- await user.tab()
- await user.tab()
- await user.tab()
-
- expect(screen.getByRole('button', { name: 'No Description' })).toHaveFocus()
- expect(await screen.findByText('snippet.unknownUser')).toBeInTheDocument()
- })
+ await act(async () => pending.resolve(page([{ ...snippet, name: 'Updated review' }])))
+ expect(await screen.findByRole('button', { name: /Updated review/ })).toBeInTheDocument()
+})
+it('filters the displayed snippets using the selected tag', async () => {
+ const user = userEvent.setup()
+ requests.list.mockResolvedValueOnce(page()).mockResolvedValue(page([]))
+ renderSnippets()
+ await screen.findByRole('button', { name: /Customer Review/ })
+ await user.click(screen.getByRole('button', { name: 'common.tag.placeholder' }))
+ await user.click(await screen.findByRole('checkbox', { name: 'Sales' }))
+ expect(await screen.findByText('workflow.tabs.noSnippetsFound')).toBeInTheDocument()
+ expect(requests.list).toHaveBeenLastCalledWith({
+ query: { page: 1, limit: 30, tag_ids: ['tag-1'], is_published: true },
})
+ expect(screen.queryByRole('button', { name: /Customer Review/ })).not.toBeInTheDocument()
+})
+it('updates and clears the embedded search through its controlled caller', async () => {
+ const user = userEvent.setup()
+ function Caller() {
+ const [searchText, setSearchText] = useState('')
+ return <Snippets searchText={searchText} onSearchTextChange={setSearchText} />
+ }
+ renderSnippets(<Caller />)
+ const input = screen.getByRole('searchbox', { name: 'workflow.tabs.searchSnippets' })
+ await user.type(input, 'review')
+ expect(input).toHaveValue('review')
+ await waitFor(() =>
+ expect(requests.list).toHaveBeenLastCalledWith({
+ query: { page: 1, limit: 30, keyword: 'review', is_published: true },
+ }),
+ )
+ await user.click(screen.getByRole('button', { name: 'workflow.tabs.clearSnippetSearch' }))
+ expect(input).toHaveValue('')
+ expect(
+ screen.queryByRole('button', { name: 'workflow.tabs.clearSnippetSearch' }),
+ ).not.toBeInTheDocument()
+})
+it('inserts the clicked snippet graph into the real canvas', async () => {
+ const user = userEvent.setup()
+ renderSnippets()
+ await user.click(await screen.findByRole('button', { name: /Customer Review/ }))
+ const graph = (): { nodes: Node[]; edges: Edge[] } =>
+ JSON.parse(screen.getByLabelText('Canvas graph').textContent!)
+ await waitFor(() => expect(graph().nodes).toHaveLength(3))
+ const { nodes, edges } = graph()
+ const first = nodes.find((node) => node.data.title === 'Review input')!
+ const second = nodes.find((node) => node.data.title === 'Review result')!
+ expect(nodes[0]).toMatchObject({ id: 'existing', selected: false })
+ expect(first).toMatchObject({ selected: true })
+ expect(second).toMatchObject({ selected: true })
+ expect(new Set(nodes.map((node) => node.id)).size).toBe(3)
+ expect(edges).toEqual([expect.objectContaining({ source: first.id, target: second.id })])
+ expect(requests.increment).toHaveBeenCalledWith({ params: { snippet_id: 'snippet-1' } })
+})
+it('opens the keyboard preview for a snippet without a description', async () => {
+ const user = userEvent.setup()
+ requests.list.mockResolvedValue(page([{ ...snippet, name: 'No Description', description: '' }]))
+ renderSnippets()
+ const row = await screen.findByRole('button', { name: 'No Description' })
+ act(() => row.focus())
+ await user.keyboard('{Tab}{Shift>}{Tab}{/Shift}')
+ expect(row).toHaveFocus()
+ expect(await screen.findByText('snippet.unknownUser')).toBeInTheDocument()
})