admin/context/AlertModalContext.test.tsx
alisaza edd468cf1d test: enhance test configurations and cleanup procedures
Updated the Vitest configuration to increase test and hook timeouts to 20 seconds, addressing flaky tests under pre-push load. Additionally, improved test cleanup procedures across multiple test files by ensuring mocks are cleared after each test, enhancing test reliability and maintainability.
2026-09-13 13:42:22 +03:30

93 lines
2.4 KiB
TypeScript

import type { ButtonHTMLAttributes } from 'react'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AlertModalProvider } from '@/context/AlertModalContext'
import useAlertModal from '@/hooks/useAlertModal'
vi.mock('@/components/formElements/Button', () => ({
default: ({
children,
isLoading,
fullWidth: _fullWidth,
color: _color,
variant: _variant,
...props
}: ButtonHTMLAttributes<HTMLButtonElement> & {
isLoading?: boolean
fullWidth?: boolean
color?: string
variant?: string
}) => (
<button
{...props}
disabled={props.disabled || isLoading}
>
{children}
</button>
),
}))
afterEach(() => {
cleanup()
vi.clearAllMocks()
})
function AlertHarness({ onConfirm }: { onConfirm: () => void | Promise<void> }) {
const { showAlert } = useAlertModal()
return (
<button
type="button"
onClick={() => {
showAlert('این عملیات قابل بازگشت نیست.', onConfirm, undefined, { dangerAccept: true })
}}
>
حذف
</button>
)
}
describe('AlertModalProvider', () => {
it('renders a semantic alert dialog and runs the confirmation once', async () => {
const onConfirm = vi.fn()
render(
<AlertModalProvider>
<AlertHarness onConfirm={onConfirm} />
</AlertModalProvider>
)
fireEvent.click(screen.getByRole('button', { name: 'حذف' }))
const dialog = await screen.findByRole('alertdialog')
expect(dialog).toHaveTextContent('این عملیات قابل بازگشت نیست.')
fireEvent.click(screen.getByRole('button', { name: 'تأیید' }))
await waitFor(() => {
expect(onConfirm).toHaveBeenCalledTimes(1)
})
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
})
it('closes without running the confirmation when cancelled', async () => {
const onConfirm = vi.fn()
render(
<AlertModalProvider>
<AlertHarness onConfirm={onConfirm} />
</AlertModalProvider>
)
fireEvent.click(screen.getByRole('button', { name: 'حذف' }))
await screen.findByRole('alertdialog')
fireEvent.click(screen.getByRole('button', { name: 'انصراف' }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(onConfirm).not.toHaveBeenCalled()
})
})