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.

8.6 KB
Raw Blame
import type { ReactElement } from 'react'
import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { consoleClient } from '@/service/console'
import { expectLoadingButton } from '@/test/button'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { encryptPassword } from '@/utils/encryption'
import InstallForm from './installForm'

const render = (ui: ReactElement) => renderWithConsoleQuery(ui)

const mockReplace = vi.fn()

vi.mock('@/next/navigation', () => ({
  useRouter: () => ({ replace: mockReplace }),
}))

vi.mock('@/service/console', async (importOriginal) => {
  const actual = await importOriginal<typeof import('@/service/console')>()
  const { withConsoleClientResponses, withConsoleResponses } =
    await import('@/test/console/service-responses')
  const responses = {
    'setup.post': vi.fn(),
    'init.get': vi.fn(),
    'login.post': vi.fn(),
  }
  return {
    ...actual,
    consoleClient: withConsoleClientResponses(actual.consoleClient, responses),
    consoleQuery: withConsoleResponses(actual.consoleQuery, responses),
  }
})

const mockSetup = vi.mocked(consoleClient.setup.post)
const mockLogin = vi.mocked(consoleClient.login.post)
const mockFetchInitStatus = vi.mocked(consoleClient.init.get)

describe('InstallForm', () => {
  beforeEach(() => {
    vi.resetAllMocks()
    mockFetchInitStatus.mockResolvedValue({ status: 'finished' })
  })

  it('should render form after loading', async () => {
    render(<InstallForm />)

    const emailInput = await screen.findByLabelText('login.email')
    const nameInput = screen.getByLabelText('login.name')
    const passwordInput = screen.getByLabelText('login.password')

    expect(emailInput).toHaveAttribute('type', 'email')
    expect(emailInput).toHaveAttribute('autocomplete', 'email')
    expect(nameInput).toHaveAttribute('autocomplete', 'name')
    expect(nameInput).toHaveAttribute('maxlength', '30')
    expect(passwordInput).toHaveAttribute('autocomplete', 'new-password')
    expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('login.setAdminAccount')
    expect(screen.getByRole('button', { name: /login\.installBtn/ })).toBeInTheDocument()
  })

  it('should reveal and hide the password with an accessible action', async () => {
    const user = userEvent.setup()
    render(<InstallForm />)

    const passwordInput = await screen.findByLabelText('login.password')

    await user.click(screen.getByRole('button', { name: 'login.showPassword' }))
    expect(passwordInput).toHaveAttribute('type', 'text')

    await user.click(screen.getByRole('button', { name: 'login.showPassword' }))
    expect(passwordInput).toHaveAttribute('type', 'password')
  })

  it('should identify required fields only after submission', async () => {
    const user = userEvent.setup()
    render(<InstallForm />)

    const emailInput = await screen.findByLabelText('login.email')
    const nameInput = screen.getByLabelText('login.name')
    const passwordInput = screen.getByLabelText('login.password')

    expect(screen.queryByText('login.error.emailInValid')).not.toBeInTheDocument()
    expect(screen.queryByText('login.error.nameEmpty')).not.toBeInTheDocument()
    expect(screen.getAllByText('login.error.passwordInvalid')).toHaveLength(1)
    expect(passwordInput).toHaveAccessibleDescription('login.error.passwordInvalid')

    await user.click(screen.getByRole('button', { name: /login\.installBtn/ }))

    await waitFor(() => {
      expect(screen.getByText('login.error.emailInValid')).toBeInTheDocument()
      expect(screen.getByText('login.error.nameEmpty')).toBeInTheDocument()
      expect(screen.getAllByText('login.error.passwordInvalid')).toHaveLength(1)
    })
    expect(emailInput).toHaveAttribute('aria-invalid', 'true')
    expect(nameInput).toHaveAttribute('aria-invalid', 'true')
    expect(passwordInput).toHaveAttribute('aria-invalid', 'true')
    expect(passwordInput).toHaveAccessibleDescription('login.error.passwordInvalid')
    expect(mockSetup).not.toHaveBeenCalled()
  })

  it('should identify an invalid email and focus the field', async () => {
    const user = userEvent.setup()
    render(<InstallForm />)

    const emailInput = await screen.findByLabelText('login.email')
    await user.type(emailInput, 'invalid-email')
    await user.click(screen.getByRole('button', { name: /login\.installBtn/ }))

    expect(await screen.findByText('login.error.emailInValid')).toBeInTheDocument()
    expect(emailInput).toHaveAttribute('aria-invalid', 'true')
    expect(emailInput).toHaveFocus()
    expect(mockSetup).not.toHaveBeenCalled()
  })

  it('should enforce the password requirements before submission', async () => {
    const user = userEvent.setup()
    render(<InstallForm />)

    await user.type(await screen.findByLabelText('login.email'), '[email protected]')
    await user.type(screen.getByLabelText('login.name'), 'Admin')
    const passwordInput = screen.getByLabelText('login.password')
    await user.type(passwordInput, 'abcdefgh')
    await user.click(screen.getByRole('button', { name: /login\.installBtn/ }))

    expect(passwordInput).toHaveAttribute('aria-invalid', 'true')
    expect(passwordInput).toHaveFocus()
    expect(mockSetup).not.toHaveBeenCalled()
  })

  it('should submit and redirect to the console root on successful login', async () => {
    mockSetup.mockResolvedValue({ result: 'success' })
    mockLogin.mockResolvedValue({ result: 'success', data: 'token' })

    render(<InstallForm />)

    fireEvent.change(await screen.findByLabelText('login.email'), {
      target: { value: '[email protected]' },
    })
    fireEvent.change(screen.getByLabelText('login.name'), { target: { value: 'Admin' } })
    fireEvent.change(screen.getByLabelText('login.password'), { target: { value: 'Password123' } })

    const form = screen.getByRole('button', { name: /login\.installBtn/ }).closest('form')
    expect(form).not.toBeNull()

    fireEvent.submit(form as HTMLFormElement)

    await waitFor(() => {
      expect(mockSetup).toHaveBeenCalledWith({
        body: {
          email: '[email protected]',
          name: 'Admin',
          password: 'Password123',
          language: 'en-US',
        },
      })
    })

    await waitFor(() => {
      expect(mockLogin).toHaveBeenCalledWith({
        body: {
          email: '[email protected]',
          password: encryptPassword('Password123'),
        },
      })
    })

    await waitFor(() => {
      expect(mockReplace).toHaveBeenCalledWith('/')
    })
  })

  it('should redirect to sign in when login fails', async () => {
    mockSetup.mockResolvedValue({ result: 'success' })
    mockLogin.mockResolvedValue({
      result: 'fail',
      data: 'error',
    })

    render(<InstallForm />)

    fireEvent.change(await screen.findByLabelText('login.email'), {
      target: { value: '[email protected]' },
    })
    fireEvent.change(screen.getByLabelText('login.name'), { target: { value: 'Admin' } })
    fireEvent.change(screen.getByLabelText('login.password'), { target: { value: 'Password123' } })

    fireEvent.click(screen.getByRole('button', { name: /login\.installBtn/ }))

    await waitFor(() => {
      expect(mockReplace).toHaveBeenCalledWith('/signin')
    })
  })

  it('should disable submit while request is in flight', async () => {
    let resolveSetup:
      | ((value: Awaited<ReturnType<typeof consoleClient.setup.post>>) => void)
      | undefined
    const setupPromise = new Promise<Awaited<ReturnType<typeof consoleClient.setup.post>>>(
      (resolve) => {
        resolveSetup = resolve
      },
    )
    mockSetup.mockReturnValue(setupPromise)
    mockLogin.mockResolvedValue({ result: 'success', data: 'token' })

    render(<InstallForm />)

    fireEvent.change(await screen.findByLabelText('login.email'), {
      target: { value: '[email protected]' },
    })
    fireEvent.change(screen.getByLabelText('login.name'), { target: { value: 'Admin' } })
    fireEvent.change(screen.getByLabelText('login.password'), { target: { value: 'Password123' } })

    const button = screen.getByRole('button', { name: /login\.installBtn/ })
    fireEvent.click(button)

    await waitFor(() => {
      expectLoadingButton(button)
    })

    fireEvent.click(button)
    expect(mockSetup).toHaveBeenCalledTimes(1)

    resolveSetup?.({ result: 'success' })

    await waitFor(() => {
      expect(mockLogin).toHaveBeenCalledTimes(1)
    })
  })

  it('sends an instance that still needs its init password to init', async () => {
    mockFetchInitStatus.mockResolvedValue({ status: 'not_started' })

    render(<InstallForm />)

    await waitFor(() => expect(mockReplace).toHaveBeenCalledWith('/init'))
  })
})