import { fireEvent,render,screen,waitFor } from '@testing-library/react'; import { toast } from 'react-hot-toast'; import { MemoryRouter } from 'react-router-dom'; import { beforeEach,describe,expect,it,vi } from 'vitest'; import api from '../services/api'; import SystemSettingsPage from './SystemSettingsPage'; vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn(), put: vi.fn(), post: vi.fn() } })); vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); const submit = () => fireEvent.submit(document.querySelector('form')!); describe('SystemSettingsPage', () => { beforeEach(() => { vi.resetAllMocks(); vi.mocked(api.get).mockImplementation(async (url) => ({ data: url === '/settings/system' ? { data: { maintenanceMode: false, supportPhone: '02100000000', catalogOnlyMode: '1', catalogShowPrices: 'false', catalogAllowCart: 1 } } : {} })); vi.mocked(api.patch).mockResolvedValue({ data: {} }); vi.mocked(api.put).mockResolvedValue({ data: {} }); }); const load = async () => { render(); await screen.findByText('نمایش قیمت محصولات در حالت کاتالوگ'); }; it('normalizes catalog flags and links to security and SMS', async () => { await load(); expect(screen.getByLabelText('نمایش قیمت محصولات در حالت کاتالوگ')).not.toBeChecked(); expect(screen.getByRole('link', { name: /SSL/ })).toHaveAttribute('href', '/settings/ssl'); expect(screen.getByRole('link', { name: /MeliPayamak/ })).toHaveAttribute('href', '/settings/sms'); }); it('synchronizes maintenance and catalog flags to both endpoints', async () => { await load(); fireEvent.click(screen.getAllByRole('checkbox')[0]); fireEvent.click(screen.getByLabelText('نمایش قیمت محصولات در حالت کاتالوگ')); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalled()); expect(api.patch).toHaveBeenCalledWith('/settings/system', expect.objectContaining({ maintenanceMode: true, CATALOG_SHOW_PRICES: 'true', CATALOG_ALLOW_CART: 'true' })); expect(api.put).toHaveBeenCalledWith('/settings/ui-texts', expect.objectContaining({ MAINTENANCE_MODE: 'true', CATALOG_ONLY_MODE: 'true' })); }); it('does not announce success if one synchronization fails and retains edits', async () => { await load(); vi.mocked(api.put).mockRejectedValueOnce(new Error('offline')); submit(); await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بروزرسانی تنظیمات سیستمی')); expect(toast.success).not.toHaveBeenCalled(); expect(screen.getByLabelText('نمایش قیمت محصولات در حالت کاتالوگ')).not.toBeChecked(); submit(); await waitFor(() => expect(toast.success).toHaveBeenCalled()); }); it('falls back to defaults on failed loading', async () => { vi.mocked(api.get).mockRejectedValue(new Error('offline')); render(); await waitFor(() => expect(document.querySelector('form')).not.toBeNull()); expect(screen.getAllByRole('checkbox')[0]).not.toBeChecked(); expect(api.patch).not.toHaveBeenCalled(); }); });