Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

test(web): replace fabricated access controls and result renderers (#45263)

Stephen Zhoubc940af65fc1
diff --git a/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx b/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx
index 9ab9518916b..d489085bd79 100644
--- a/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx
@@ -4,6 +4,7 @@ import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
+import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { render } from '@/test/console/render'
import { createAppDetailFixture } from '@/test/fixtures/app'
import { createTestQueryClient } from '@/test/query-client'
@@ -11,7 +12,8 @@ import { ServiceApiAccessPointCard } from '../built-in-access-points/service-api
const mocks = vi.hoisted(() => ({
appInfo: null as AppDetailWithSite | null,
- apiSecretKeyButtonProps: vi.fn(),
+ getAppDetail: vi.fn(),
+ apiKeys: vi.fn(),
apiEnable: vi.fn(),
}))
@@ -22,17 +24,20 @@ vi.mock('@/app/notifications', () => ({
},
}))
-vi.mock('@/service/base', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/service/base')>()
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
- request: async (url: string, _init: RequestInit, options: { request: Request }) => {
- if (options.request.method === 'GET') return Response.json(mocks.appInfo)
- const body = await options.request.json()
- const updatedApp = await mocks.apiEnable({ params: { app_id: 'app-1' }, body })
- mocks.appInfo = { ...mocks.appInfo, ...updatedApp }
- return Response.json(mocks.appInfo)
- },
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.get': mocks.getAppDetail,
+ 'apps.byAppId.apiEnable.post': async (input) => {
+ const response = await mocks.apiEnable(input)
+ mocks.appInfo = { ...mocks.appInfo!, ...response }
+ return mocks.appInfo
+ },
+ 'apps.byResourceId.apiKeys.get': mocks.apiKeys,
+ }),
}
})
@@ -40,17 +45,6 @@ vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.example.test/en${path}`,
}))
-vi.mock('../built-in-access-points/api-secret-key-button', () => ({
- ApiSecretKeyButton: (props: { canManage: boolean; disabled?: boolean }) => {
- mocks.apiSecretKeyButtonProps(props)
- return (
- <button type="button" disabled={!props.canManage || props.disabled}>
- api-secret-keys
- </button>
- )
- },
-}))
-
function createAppInfo(
mode: AppMode,
overrides: Partial<AppDetailWithSite> = {},
@@ -72,6 +66,7 @@ function renderCard(
) {
mocks.appInfo = createAppInfo(mode, overrides)
const queryClient = createTestQueryClient()
+ seedAccountProfileQuery(queryClient)
queryClient.setQueryData(
consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),
createAppInfo(mode, overrides),
@@ -118,8 +113,16 @@ function createDeferredPromise<T>() {
describe('ServiceApiAccessPointCard', () => {
beforeEach(() => {
- vi.clearAllMocks()
- mocks.apiEnable.mockResolvedValue(createAppDetailFixture({ enable_api: true }))
+ mocks.getAppDetail.mockImplementation(async () => mocks.appInfo)
+ mocks.apiEnable.mockImplementation(async ({ body }) => {
+ mocks.appInfo = { ...mocks.appInfo!, ...body }
+ return mocks.appInfo
+ })
+ mocks.apiKeys.mockResolvedValue({
+ data: [
+ { id: 'key-1', type: 'app', token: 'app-existing-key', last_used_at: null, created_at: 1 },
+ ],
+ })
})
it.each([
@@ -149,28 +152,35 @@ describe('ServiceApiAccessPointCard', () => {
).not.toBeInTheDocument()
})
- it('keeps API keys and external documentation available when the API is stopped', () => {
+ it('keeps API keys and external documentation available when the API is stopped', async () => {
+ const user = userEvent.setup()
renderCard('workflow', 'available', true, { enable_api: false })
- expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeEnabled()
+ expect(screen.getByRole('button', { name: /apiKeyModal\.apiSecretKey/ })).toBeEnabled()
const apiReferenceLink = screen.getByRole('link', { name: /apiInfo\.doc/ })
expect(apiReferenceLink).toHaveAttribute(
'href',
'https://docs.example.test/en/api-reference/guides/workflow',
)
+ await user.click(screen.getByRole('button', { name: /apiKeyModal\.apiSecretKey/ }))
+ expect(
+ await screen.findByRole('dialog', { name: 'appApi.apiKeyModal.apiSecretKey' }),
+ ).toBeVisible()
+ expect(await screen.findByText('app-e...-key')).toBeVisible()
+ expect(mocks.apiKeys).toHaveBeenCalledWith({ params: { resource_id: 'app-1' } })
})
it('disables API management without Access Point management permission', () => {
renderCard('workflow', 'available', false)
- expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: /apiKeyModal\.apiSecretKey/ })).toBeDisabled()
expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
})
it('disables API keys and external documentation when the access point is unavailable', () => {
renderCard('workflow', 'unavailable')
- expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: /apiKeyModal\.apiSecretKey/ })).toBeDisabled()
expect(screen.getByRole('button', { name: /apiInfo\.doc/ })).toBeDisabled()
})
diff --git a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx
index 108f58b4339..675eaf16969 100644
--- a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx
+++ b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx
@@ -25,6 +25,8 @@ const mocks = vi.hoisted(() => ({
getAppDetail: vi.fn<() => Promise<AppDetailWithSite | null>>(),
getUserCanAccess: vi.fn<() => Promise<{ result: boolean }>>(),
siteEnable: vi.fn(),
+ accessSubjects: vi.fn(),
+ updateAccess: vi.fn(),
resetSiteAccessToken: vi.fn().mockResolvedValue({}),
}))
@@ -35,37 +37,17 @@ vi.mock('@/app/notifications', () => ({
},
}))
-vi.mock('@/service/base', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/service/base')>()
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
- request: async (url: string, _init: RequestInit, options: { request: Request }) => {
- if (options.request.method === 'GET') return Response.json(await mocks.getAppDetail())
- if (url.endsWith('/site/access-token-reset')) {
- const site = await mocks.resetSiteAccessToken({ params: { app_id: 'app-1' } })
- if (mocks.appInfo?.site) {
- mocks.appInfo = {
- ...mocks.appInfo,
- site: { ...mocks.appInfo.site, code: site.code, access_token: site.code },
- }
- }
- return Response.json(site)
- }
- const body = await options.request.json()
- const updatedApp = await mocks.siteEnable({ params: { app_id: 'app-1' }, body })
- mocks.appInfo = { ...mocks.appInfo, ...updatedApp }
- return Response.json(mocks.appInfo)
- },
- }
-})
-
-vi.mock('@/service/access-control/use-app-access-control', async (importOriginal) => {
- const actual =
- await importOriginal<typeof import('@/service/access-control/use-app-access-control')>()
- return {
- ...actual,
- useAppWhiteListSubjects: () => ({
- data: undefined,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.get': mocks.getAppDetail,
+ 'apps.byAppId.siteEnable.post': mocks.siteEnable,
+ 'apps.byAppId.site.accessTokenReset.post': mocks.resetSiteAccessToken,
+ 'enterprise.webAppAuth.getWebAppWhitelistSubjects': mocks.accessSubjects,
+ 'enterprise.webAppAuth.updateWebAppWhitelistSubjects': mocks.updateAccess,
}),
}
})
@@ -74,18 +56,6 @@ vi.mock('@/service/share', () => ({
getUserCanAccess: mocks.getUserCanAccess,
}))
-vi.mock('@/app/components/base/app-icon', () => ({
- default: () => <div aria-label="app-icon" />,
-}))
-
-vi.mock('@/app/components/app/app-access-control', () => ({
- default: ({ onConfirm }: { onConfirm: () => Promise<void> }) => (
- <button type="button" onClick={() => void onConfirm()}>
- Save access control
- </button>
- ),
-}))
-
vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.example.test/en${path}`,
}))
@@ -236,20 +206,30 @@ const workflowWithHiddenInput: NonNullable<PublishedWorkflow> = {
describe('WebAppAccessPointCard', () => {
beforeEach(() => {
- vi.clearAllMocks()
mocks.getAppDetail.mockReset().mockImplementation(async () => mocks.appInfo)
+ mocks.accessSubjects.mockResolvedValue({ groups: [], members: [] })
+ mocks.updateAccess.mockResolvedValue({ result: 'success' })
mocks.getUserCanAccess.mockResolvedValue({ result: true })
- mocks.siteEnable.mockResolvedValue(createAppDetailFixture({ enable_site: true }))
- mocks.resetSiteAccessToken.mockResolvedValue({
- app_id: 'app-1',
- code: 'new-site-code',
- customize_token_strategy: 'not_allow',
- default_language: 'en-US',
- prompt_public: false,
- show_workflow_steps: false,
- title: 'App',
- use_icon_as_answer_icon: false,
- } satisfies AppSiteResponse)
+ mocks.siteEnable.mockImplementation(async ({ body }) => {
+ mocks.appInfo = { ...mocks.appInfo!, ...body }
+ return mocks.appInfo
+ })
+ mocks.resetSiteAccessToken.mockImplementation(async () => {
+ mocks.appInfo = {
+ ...mocks.appInfo!,
+ site: { ...mocks.appInfo!.site!, code: 'new-site-code', access_token: 'new-site-code' },
+ }
+ return {
+ app_id: 'app-1',
+ code: 'new-site-code',
+ customize_token_strategy: 'not_allow',
+ default_language: 'en-US',
+ prompt_public: false,
+ show_workflow_steps: false,
+ title: 'App',
+ use_icon_as_answer_icon: false,
+ } satisfies AppSiteResponse
+ })
})
afterEach(() => {
@@ -355,18 +335,29 @@ describe('WebAppAccessPointCard', () => {
await user.click(
screen.getByRole('button', { name: /accessControlDialog\.accessItems\.specific/ }),
)
- expect(screen.getByRole('button', { name: /studio\.accessPoint\.open/ })).toHaveAttribute(
- 'aria-disabled',
- 'true',
+ const dialog = await screen.findByRole('dialog', { name: 'app.accessControlDialog.title' })
+ expect(
+ screen.getByRole('button', { name: /studio\.accessPoint\.open/, hidden: true }),
+ ).toHaveAttribute('aria-disabled', 'true')
+ await user.click(
+ within(dialog).getByRole('radio', {
+ name: 'app.accessControlDialog.accessItems.organization',
+ }),
)
mocks.getUserCanAccess.mockResolvedValue({ result: true })
- await user.click(screen.getByRole('button', { name: 'Save access control' }))
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.confirm' }))
+ await waitFor(() =>
+ expect(mocks.updateAccess).toHaveBeenCalledExactlyOnceWith({
+ body: { appId: 'app-1', accessMode: AccessMode.ORGANIZATION },
+ }),
+ )
expect(await screen.findByRole('link', { name: /studio\.accessPoint\.open/ })).toHaveAttribute(
'href',
`https://site.example.test${basePath}/chat/site-code`,
)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it.each(['workflow', 'completion'] as const)(
diff --git a/web/app/components/share/text-generation/__tests__/text-generation-result-panel.spec.tsx b/web/app/components/share/text-generation/__tests__/text-generation-result-panel.spec.tsx
index ff912670f31..40c5eaeeefc 100644
--- a/web/app/components/share/text-generation/__tests__/text-generation-result-panel.spec.tsx
+++ b/web/app/components/share/text-generation/__tests__/text-generation-result-panel.spec.tsx
@@ -1,28 +1,28 @@
+import type { Task } from '../types'
import type { PromptConfig } from '@/models/debug'
import type { SiteInfo } from '@/models/share'
import type { VisionSettings } from '@/types/app'
-import { render, screen } from '@testing-library/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
import { AppSourceType } from '@/service/share'
+import { captureDownloads } from '@/test/download'
import { Resolution, TransferMethod } from '@/types/app'
import TextGenerationResultPanel from '../text-generation-result-panel'
import { TaskStatus } from '../types'
-const resPropsSpy = vi.fn()
-const resDownloadPropsSpy = vi.fn()
+type CompletionHandlers = Parameters<typeof import('@/service/share').sendCompletionMessage>[1]
-vi.mock('@/app/components/share/text-generation/result', () => ({
- default: (props: Record<string, unknown>) => {
- resPropsSpy(props)
- return <div data-testid={`res-${String(props.taskId ?? 'single')}`} />
- },
+const sendCompletion = vi.hoisted(() =>
+ vi.fn<typeof import('@/service/share').sendCompletionMessage>(),
+)
+vi.mock('@/service/share', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/share')>()),
+ sendCompletionMessage: sendCompletion,
}))
-
-vi.mock('@/app/components/share/text-generation/run-batch/res-download', () => ({
- default: (props: Record<string, unknown>) => {
- resDownloadPropsSpy(props)
- return <div data-testid="res-download-mock" />
- },
+vi.mock('@/next/navigation', () => ({
+ useParams: () => ({ token: 'app-123' }),
+ usePathname: () => '/completion/app-123',
}))
const promptConfig: PromptConfig = {
@@ -44,17 +44,17 @@ const visionConfig: VisionSettings = {
transfer_methods: [TransferMethod.local_file],
}
-const batchTasks = [
+const batchTasks: Task[] = [
{
id: 1,
status: TaskStatus.completed,
params: { inputs: { name: 'Alpha' } },
- }!,
+ },
{
id: 2,
status: TaskStatus.failed,
params: { inputs: { name: 'Beta' } },
- }!,
+ },
]
const baseProps = {
@@ -64,10 +64,10 @@ const baseProps = {
appId: 'app-123',
appSourceType: AppSourceType.webApp,
completionFiles: [],
- controlRetry: 88,
- controlSend: 77,
- controlStopResponding: 66,
- exportRes: [{ Name: 'Alpha', 'share.generation.completionResult': 'Done' }!],
+ controlRetry: 0,
+ controlSend: 0,
+ controlStopResponding: 0,
+ exportRes: [{ Name: 'Alpha', 'share.generation.completionResult': 'Hello Alpha' }],
handleCompleted: vi.fn(),
handleRetryAllFailedTask: vi.fn(),
handleSaveMessage: vi.fn(async () => {}),
@@ -91,111 +91,106 @@ const baseProps = {
}
describe('TextGenerationResultPanel', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should render a single result in run-once mode and pass non-batch props', () => {
- render(<TextGenerationResultPanel {...baseProps} />)
-
- expect(screen.getByTestId('res-single'))!.toBeInTheDocument()
- expect(resPropsSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- appId: 'app-123',
- appSourceType: AppSourceType.webApp,
- completionFiles: [],
- controlSend: 77,
- controlStopResponding: 66,
- hideInlineStopButton: true,
- inputs: { name: 'Alice' },
- isCallBatchAPI: false,
- moreLikeThisEnabled: true,
- taskId: undefined,
- }),
- )
- expect(screen.queryByTestId('res-download-mock')).not.toBeInTheDocument()
- })
-
- it('should render batch results, download entry, loading area, and retry banner', async () => {
- const user = userEvent.setup()
- const handleRetryAllFailedTask = vi.fn()
-
- render(
- <TextGenerationResultPanel
- {...baseProps}
- allFailedTaskList={[batchTasks[1]!]}
- allSuccessTaskList={[batchTasks[0]!]}
- isCallBatchAPI
- noPendingTask={false}
- handleRetryAllFailedTask={handleRetryAllFailedTask}
- />,
- )
-
- expect(screen.getByTestId('res-1'))!.toBeInTheDocument()
- expect(screen.getByTestId('res-2'))!.toBeInTheDocument()
- expect(resPropsSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- inputs: { name: 'Alpha' },
- isError: false,
- controlRetry: 0,
- taskId: 1,
- onRunControlChange: undefined,
- }),
- )
- expect(resPropsSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- inputs: { name: 'Beta' },
- isError: true,
- controlRetry: 88,
- taskId: 2,
- }),
- )
- expect(screen.getByText('share.generation.executions:{"num":2}'))!.toBeInTheDocument()
- expect(screen.getByTestId('res-download-mock'))!.toBeInTheDocument()
- expect(resDownloadPropsSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- isMobile: false,
- values: baseProps.exportRes,
- }),
+ afterEach(() => vi.restoreAllMocks())
+
+ it('renders the single execution for the current inputs without batch controls', async () => {
+ let handlers!: CompletionHandlers
+ sendCompletion.mockImplementation(async (_data, callbacks) => {
+ handlers = callbacks
+ })
+ const { rerender } = render(<TextGenerationResultPanel {...baseProps} />)
+ rerender(<TextGenerationResultPanel {...baseProps} controlSend={1} />)
+
+ expect(sendCompletion).toHaveBeenCalledExactlyOnceWith(
+ { inputs: { name: 'Alice' } },
+ expect.any(Object),
+ AppSourceType.webApp,
+ 'app-123',
)
- expect(screen.getByText('share.generation.batchFailed.info:{"num":1}'))!.toBeInTheDocument()
+ await act(async () => {
+ handlers.onData?.('Hello Alice', true, { messageId: 'message-alice', taskId: 'task-alice' })
+ handlers.onCompleted?.()
+ })
+ expect(await screen.findByText('Hello Alice')).toBeVisible()
+ expect(screen.queryByText(/share.generation.executions/)).not.toBeInTheDocument()
expect(
- screen.getByRole('button', { name: 'share.generation.batchFailed.retry' }),
- )!.toBeInTheDocument()
- expect(screen.getByRole('progressbar', { name: 'common.loading' }))!.toBeInTheDocument()
-
- await user.click(screen.getByRole('button', { name: 'share.generation.batchFailed.retry' }))
- expect(handleRetryAllFailedTask).toHaveBeenCalledTimes(1)
+ screen.queryByRole('button', { name: 'common.operation.download' }),
+ ).not.toBeInTheDocument()
})
- it('should toggle mobile result panel handle between show and hide actions', async () => {
+ it('renders per-task inputs, exports successful results and retries failed executions', async () => {
const user = userEvent.setup()
- const onHideResultPanel = vi.fn()
- const onShowResultPanel = vi.fn()
- const { rerender } = render(
- <TextGenerationResultPanel
- {...baseProps}
- isPC={false}
- isShowResultPanel={true}
- onHideResultPanel={onHideResultPanel}
- onShowResultPanel={onShowResultPanel}
- />,
+ const downloads = captureDownloads()
+ let betaAttempt = 0
+ sendCompletion.mockImplementation(async ({ inputs }, handlers) => {
+ const { name } = inputs as { name: string }
+ if (name === 'Beta' && betaAttempt++ === 0) {
+ handlers.onError?.('offline')
+ return
+ }
+ handlers.onData?.(`Hello ${name}`, true, {
+ messageId: `message-${name}`,
+ taskId: `task-${name}`,
+ })
+ handlers.onCompleted?.()
+ })
+ function Batch() {
+ const [retry, setRetry] = useState(0)
+ const [tasks, setTasks] = useState(batchTasks)
+ return (
+ <TextGenerationResultPanel
+ {...baseProps}
+ allFailedTaskList={tasks.filter((task) => task.status === TaskStatus.failed)}
+ showTaskList={tasks}
+ handleCompleted={(_content, id, success) =>
+ setTasks((current) =>
+ current.map((task) =>
+ task.id === id
+ ? { ...task, status: success ? TaskStatus.completed : TaskStatus.failed }
+ : task,
+ ),
+ )
+ }
+ allSuccessTaskList={tasks.filter((task) => task.status === TaskStatus.completed)}
+ allTaskList={[
+ ...tasks,
+ { id: 3, status: TaskStatus.pending, params: { inputs: { name: 'Gamma' } } },
+ ]}
+ isCallBatchAPI
+ noPendingTask={false}
+ controlSend={1}
+ controlRetry={retry}
+ handleRetryAllFailedTask={() => setRetry((value) => value + 1)}
+ />
+ )
+ }
+ render(<Batch />)
+
+ expect(await screen.findByText('Hello Alpha')).toBeVisible()
+ expect(screen.getByText('01')).toBeVisible()
+ expect(screen.getByText('02')).toBeVisible()
+ expect(screen.getByText('share.generation.executions:{"num":3}')).toBeVisible()
+ expect(screen.getByText('share.generation.batchFailed.info:{"num":1}')).toBeVisible()
+ expect(screen.getByRole('progressbar', { name: 'common.loading' })).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.download' }))
+ expect(downloads).toHaveLength(1)
+ expect(downloads[0]!.filename).toBe('result.csv')
+ expect(await downloads[0]!.blob.text()).toBe(
+ '\uFEFFName,share.generation.completionResult\r\nAlpha,Hello Alpha',
)
- await user.click(document.querySelector('.cursor-grab') as HTMLElement)
- expect(onHideResultPanel).toHaveBeenCalledTimes(1)
-
- rerender(
- <TextGenerationResultPanel
- {...baseProps}
- isPC={false}
- isShowResultPanel={false}
- onHideResultPanel={onHideResultPanel}
- onShowResultPanel={onShowResultPanel}
- />,
- )
-
- await user.click(document.querySelector('.cursor-grab') as HTMLElement)
- expect(onShowResultPanel).toHaveBeenCalledTimes(1)
+ await user.click(screen.getByText('share.generation.batchFailed.retry'))
+ await waitFor(() => expect(sendCompletion).toHaveBeenCalledTimes(3))
+ expect(sendCompletion.mock.calls.map(([data]) => data.inputs)).toEqual([
+ { name: 'Alpha' },
+ { name: 'Beta' },
+ { name: 'Beta' },
+ ])
+ expect(screen.getByText('Hello Alpha')).toBeVisible()
+ expect(await screen.findByText('Hello Beta')).toBeVisible()
+ expect(
+ screen.queryByText('share.generation.batchFailed.info:{"num":1}'),
+ ).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/share/text-generation/result/__tests__/index.spec.tsx b/web/app/components/share/text-generation/result/__tests__/index.spec.tsx
index cdf0706aa70..539745c436f 100644
--- a/web/app/components/share/text-generation/result/__tests__/index.spec.tsx
+++ b/web/app/components/share/text-generation/result/__tests__/index.spec.tsx
@@ -4,6 +4,7 @@ import type { IOtherOptions } from '@/service/base'
import type { VisionSettings } from '@/types/app'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { TEXT_GENERATION_TIMEOUT_MS } from '@/config'
import { AppSourceType } from '@/service/share'
import { Resolution, TransferMethod } from '@/types/app'
import Result from '../index'
@@ -12,16 +13,12 @@ const {
notifyMock,
sendCompletionMessageMock,
sendWorkflowMessageMock,
- sleepMock,
stopChatMessageRespondingMock,
- textGenerationResPropsSpy,
} = vi.hoisted(() => ({
notifyMock: vi.fn(),
sendCompletionMessageMock: vi.fn(),
sendWorkflowMessageMock: vi.fn(),
- sleepMock: vi.fn(),
stopChatMessageRespondingMock: vi.fn(),
- textGenerationResPropsSpy: vi.fn(),
}))
vi.mock('i18next', async (importOriginal) => {
@@ -50,14 +47,6 @@ vi.mock('@/app/notifications', () => ({
toast: (...args: unknown[]) => notifyMock(...args),
}))
-vi.mock('@/utils', async () => {
- const actual = await vi.importActual<typeof import('@/utils')>('@/utils')
- return {
- ...actual,
- sleep: (...args: Parameters<typeof actual.sleep>) => sleepMock(...args),
- }
-})
-
vi.mock('@/service/share', async () => {
const actual = await vi.importActual<typeof import('@/service/share')>('@/service/share')
return {
@@ -71,19 +60,9 @@ vi.mock('@/service/share', async () => {
}
})
-vi.mock('@/app/components/app/text-generate/item', () => ({
- default: (props: Record<string, unknown>) => {
- textGenerationResPropsSpy(props)
- return (
- <div data-testid="text-generation-res">
- {typeof props.content === 'string' ? props.content : JSON.stringify(props.content ?? null)}
- </div>
- )
- },
-}))
-
-vi.mock('@/app/components/share/text-generation/no-data', () => ({
- default: () => <div data-testid="no-data">No data</div>,
+vi.mock('@/next/navigation', () => ({
+ useParams: () => ({ token: 'app-123' }),
+ usePathname: () => '/completion/app-123',
}))
const promptConfig: PromptConfig = {
@@ -131,17 +110,12 @@ const baseProps = {
}
describe('Result', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- sleepMock.mockImplementation(() => new Promise<void>(() => {}))
- stopChatMessageRespondingMock.mockResolvedValue(undefined)
- })
+ afterEach(() => vi.useRealTimers())
it('should render no data before the first execution', () => {
render(<Result {...baseProps} />)
- expect(screen.getByTestId('no-data')).toBeTruthy()
- expect(screen.queryByTestId('text-generation-res')).toBeNull()
+ expect(screen.getByText('share.generation.noData')).toBeVisible()
})
it('should stream completion results and stop the current task', async () => {
@@ -186,7 +160,7 @@ describe('Result', () => {
})
})
- expect(screen.getByTestId('text-generation-res').textContent).toContain('Hello')
+ expect(await screen.findByText('Hello')).toBeVisible()
await waitFor(() => {
expect(onRunControlChange).toHaveBeenLastCalledWith(
@@ -212,11 +186,9 @@ describe('Result', () => {
})
expect(onCompleted).toHaveBeenCalledWith('Hello', undefined, true)
- expect(textGenerationResPropsSpy).toHaveBeenLastCalledWith(
- expect.objectContaining({
- messageId: 'message-1',
- }),
- )
+ expect(
+ screen.queryByRole('button', { name: 'operation.stopResponding' }),
+ ).not.toBeInTheDocument()
})
it('should render workflow results after workflow completion', async () => {
@@ -275,27 +247,13 @@ describe('Result', () => {
})
})
- expect(screen.getByTestId('text-generation-res').textContent).toContain('{"answer":"Hello"}')
- expect(textGenerationResPropsSpy).toHaveBeenLastCalledWith(
- expect.objectContaining({
- workflowProcessData: expect.objectContaining({
- resultText: 'Hello',
- status: 'succeeded',
- }),
- }),
- )
+ expect(await screen.findByText('Hello')).toBeVisible()
expect(onCompleted).toHaveBeenCalledWith('{"answer":"Hello"}', undefined, true)
})
it('should finish a timed-out workflow and show a translated warning', async () => {
- let resolveTimeout!: () => void
+ vi.useFakeTimers()
let workflowHandlers: IOtherOptions | null = null
- sleepMock.mockImplementation(
- () =>
- new Promise<void>((resolve) => {
- resolveTimeout = resolve
- }),
- )
sendWorkflowMessageMock.mockImplementation(async (_data, handlers) => {
workflowHandlers = handlers
})
@@ -316,8 +274,7 @@ describe('Result', () => {
created_at: 0,
},
})
- resolveTimeout()
- await Promise.resolve()
+ await vi.advanceTimersByTimeAsync(TEXT_GENERATION_TIMEOUT_MS)
})
await act(async () => {
@@ -345,14 +302,10 @@ describe('Result', () => {
})
})
- expect(textGenerationResPropsSpy).toHaveBeenLastCalledWith(
- expect.objectContaining({
- workflowProcessData: expect.objectContaining({
- resultText: '',
- status: 'succeeded',
- }),
- }),
- )
+ expect(screen.queryByText('Late result')).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'operation.stopResponding' }),
+ ).not.toBeInTheDocument()
expect(notifyMock).toHaveBeenCalledWith('Translated timeout warning', { type: 'warning' })
expect(onCompleted).toHaveBeenCalledWith('', undefined, false)
expect(onCompleted).toHaveBeenCalledTimes(1)
@@ -361,18 +314,9 @@ describe('Result', () => {
it('should render batch task ids for both short and long indexes', () => {
const { rerender } = render(<Result {...baseProps} isCallBatchAPI taskId={3} />)
- expect(textGenerationResPropsSpy).toHaveBeenLastCalledWith(
- expect.objectContaining({
- taskId: '03',
- }),
- )
-
+ expect(screen.getByText('03')).toBeVisible()
rerender(<Result {...baseProps} isCallBatchAPI taskId={12} />)
-
- expect(textGenerationResPropsSpy).toHaveBeenLastCalledWith(
- expect.objectContaining({
- taskId: '12',
- }),
- )
+ expect(screen.getByText('12')).toBeVisible()
+ expect(screen.queryByText('03')).not.toBeInTheDocument()
})
})