Files
canina/frontend/admin-panel/src/pages/Videos.test.tsx
T
devops ddbf1ca026
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation.
- Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings.
- Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors.
- Fixed unmount lifecycle guards, promise error handling, and component edge cases.
2026-10-13 16:01:00 +00:00

295 lines
11 KiB
TypeScript

import { fireEvent,render,screen,waitFor } from '@testing-library/react';
import { toast } from 'react-hot-toast';
import { beforeEach,describe,expect,it,vi } from 'vitest';
import api from '../services/api';
import Videos from './Videos';
vi.mock('../services/api', () => ({
default: {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn(),
},
BASE_DOMAIN: 'https://api.example.com',
}));
vi.mock('react-hot-toast', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));
vi.mock('../components/ui/MediaSelector', () => ({
default: ({ isOpen, onClose, onSelect }: any) => {
if (!isOpen) return null;
return (
<div data-testid="media-selector">
<button onClick={() => { onSelect('/uploads/media-item.mp4'); onClose(); }}>
انتخاب مدیا
</button>
</div>
);
},
}));
describe('Videos Component', () => {
const mockVideos = [
{
id: 'vid-1',
title: 'آموزش استفاده از مکمل کانی‌هیدروکس',
doctor: 'دکتر علیرضا کاظمی',
doctorId: 'doc-1',
duration: '۰۳:۴۵',
thumbnail: '/uploads/thumb1.jpg',
videoUrl: 'https://example.com/video1.mp4',
description: 'توضیحات و راهنمای جامع مصرف مکمل مفصل‌ساز',
viewsCount: 150,
isFeatured: true,
createdAt: '2026-03-01T10:00:00Z',
},
{
id: 'vid-2',
title: 'تقویت سیستم ایمنی توله سگ‌ها',
doctor: 'دکتر مریم رضایی',
doctorId: 'doc-2',
duration: '۰۲:۱۵',
thumbnail: '',
videoUrl: '/uploads/video2.mp4',
description: 'راهکارهای تقویت سیستم دفاعی با مکمل‌های آلمانی',
viewsCount: 85,
isFeatured: false,
createdAt: '2026-03-05T14:00:00Z',
},
];
const mockDoctors = [
{ id: 'doc-1', name: 'دکتر علیرضا کاظمی', title: 'متخصص جراحی دامپزشکی' },
{ id: 'doc-2', name: 'دکتر مریم رضایی', title: 'کلینیسین داخلی' },
];
beforeEach(() => {
vi.clearAllMocks();
(api.get as any).mockImplementation((url: string) => {
if (url === '/videos') {
return Promise.resolve({
data: {
videos: mockVideos,
meta: { totalPages: 1, total: 2 },
},
});
}
if (url === '/doctors') {
return Promise.resolve({
data: { doctors: mockDoctors },
});
}
return Promise.resolve({ data: {} });
});
});
it('renders videos list and doctor names correctly', async () => {
render(<Videos />);
expect(api.get).toHaveBeenCalledWith('/videos', expect.any(Object));
expect(api.get).toHaveBeenCalledWith('/doctors', expect.any(Object));
await waitFor(() => {
expect(screen.getByText('آموزش استفاده از مکمل کانی‌هیدروکس')).toBeInTheDocument();
expect(screen.getByText('تقویت سیستم ایمنی توله سگ‌ها')).toBeInTheDocument();
});
expect(screen.getByText('دکتر علیرضا کاظمی')).toBeInTheDocument();
expect(screen.getByText('دکتر مریم رضایی')).toBeInTheDocument();
expect(screen.getByText('ویژه صفحه اصلی')).toBeInTheDocument();
expect(screen.getByText('تعداد: 2 مورد')).toBeInTheDocument();
});
it('opens modal to create a new video and saves it with doctor linkage', async () => {
(api.post as any).mockResolvedValue({ data: { success: true } });
render(<Videos />);
await waitFor(() => {
expect(screen.getByText('آموزش استفاده از مکمل کانی‌هیدروکس')).toBeInTheDocument();
});
const addBtn = screen.getByRole('button', { name: /افزودن ویدئوی جدید/ });
fireEvent.click(addBtn);
expect(screen.getByText('افزودن ویدئوی جدید به آکادمی')).toBeInTheDocument();
const titleInput = screen.getByPlaceholderText(/نحوه مصرف مکمل کانی‌هیدروکس/);
fireEvent.change(titleInput, { target: { value: 'ویدئوی جدید آموزش مکمل' } });
// Link doctor via select - use the second select element (doctor dropdown in modal)
const doctorSelect = document.querySelector('#videoForm select')!;
fireEvent.change(doctorSelect, { target: { value: 'doc-1' } });
// Video URL input
const videoUrlInput = screen.getByPlaceholderText(/https:\/\/... یا کد آیفرم/);
fireEvent.change(videoUrlInput, { target: { value: 'https://example.com/new-video.mp4' } });
// Duration input
const durationInput = screen.getByPlaceholderText('۰۲:۴۵');
fireEvent.change(durationInput, { target: { value: '۰۵:۰۰' } });
// Featured checkbox
const featuredCheckbox = screen.getByLabelText(/نمایش به عنوان ویدئوی ویژه/);
fireEvent.click(featuredCheckbox);
// Submit form
const form = document.getElementById('videoForm') as HTMLFormElement;
fireEvent.submit(form);
await waitFor(() => {
expect(api.post).toHaveBeenCalledWith(
'/videos',
expect.objectContaining({
title: 'ویدئوی جدید آموزش مکمل',
doctorId: 'doc-1',
doctor: 'دکتر علیرضا کاظمی',
videoUrl: 'https://example.com/new-video.mp4',
duration: '۰۵:۰۰',
isFeatured: true,
})
);
expect(toast.success).toHaveBeenCalledWith('ویدئو جدید با موفقیت ذخیره شد');
});
});
it('opens modal to edit an existing video and updates via api.put', async () => {
(api.put as any).mockResolvedValue({ data: { success: true } });
render(<Videos />);
await waitFor(() => {
expect(screen.getByText('آموزش استفاده از مکمل کانی‌هیدروکس')).toBeInTheDocument();
});
const editButtons = screen.getAllByTitle('ویرایش ویدئو');
fireEvent.click(editButtons[0]);
expect(screen.getByText('ویرایش ویدئوی آموزشی')).toBeInTheDocument();
const titleInput = screen.getByPlaceholderText(/نحوه مصرف مکمل کانی‌هیدروکس/);
expect(titleInput).toHaveValue('آموزش استفاده از مکمل کانی‌هیدروکس');
fireEvent.change(titleInput, { target: { value: 'آموزش ویرایش شده کانی‌هیدروکس' } });
const form = document.getElementById('videoForm') as HTMLFormElement;
fireEvent.submit(form);
await waitFor(() => {
expect(api.put).toHaveBeenCalledWith(
'/videos/vid-1',
expect.objectContaining({
title: 'آموزش ویرایش شده کانی‌هیدروکس',
doctorId: 'doc-1',
})
);
expect(toast.success).toHaveBeenCalledWith('ویدئو با موفقیت ویرایش شد');
});
});
it('deletes a video after confirmation dialog', async () => {
(api.delete as any).mockResolvedValue({ data: { success: true } });
render(<Videos />);
await waitFor(() => {
expect(screen.getByText('آموزش استفاده از مکمل کانی‌هیدروکس')).toBeInTheDocument();
});
const deleteButtons = screen.getAllByTitle('حذف ویدئو');
fireEvent.click(deleteButtons[0]);
expect(screen.getByText('حذف ویدئوی آموزشی')).toBeInTheDocument();
expect(screen.getByText(/آیا از حذف این ویدئوی آموزشی اطمینان دارید؟/)).toBeInTheDocument();
const confirmBtn = screen.getByRole('button', { name: 'تایید' });
fireEvent.click(confirmBtn);
await waitFor(() => {
expect(api.delete).toHaveBeenCalledWith('/videos/vid-1');
expect(toast.success).toHaveBeenCalledWith('ویدئو با موفقیت حذف شد');
});
});
it('filters videos by search term and featured status', async () => {
render(<Videos />);
await waitFor(() => {
expect(screen.getByText('آموزش استفاده از مکمل کانی‌هیدروکس')).toBeInTheDocument();
});
const searchInput = screen.getByPlaceholderText(/جستجو در عناوین، نام دامپزشک/);
fireEvent.change(searchInput, { target: { value: 'ایمنی' } });
await waitFor(() => {
expect(api.get).toHaveBeenCalledWith(
'/videos',
expect.objectContaining({
params: expect.objectContaining({
search: 'ایمنی',
}),
})
);
});
const featuredFilterSelect = screen.getByDisplayValue('همه وضعیت‌ها');
fireEvent.change(featuredFilterSelect, { target: { value: 'true' } });
await waitFor(() => {
expect(api.get).toHaveBeenCalledWith(
'/videos',
expect.objectContaining({
params: expect.objectContaining({
featured: true,
}),
})
);
});
});
it('requires title and URL and retains draft after failed save', async () => {
vi.mocked(api.post).mockRejectedValueOnce(new Error('offline'));
render(<Videos />); await screen.findByText('آموزش استفاده از مکمل کانی‌هیدروکس');
fireEvent.click(screen.getByRole('button', { name: /افزودن ویدئوی جدید/ }));
const title = screen.getByPlaceholderText(/نحوه مصرف مکمل کانی‌هیدروکس/) as HTMLInputElement;
const url = screen.getByPlaceholderText(/https:\/\/... یا کد آیفرم/) as HTMLInputElement;
expect(title).toBeRequired(); expect(url).toBeRequired();
expect(title.checkValidity()).toBe(false); expect(url.checkValidity()).toBe(false);
expect(api.post).not.toHaveBeenCalled();
fireEvent.change(title, { target: { value: 'Draft video' } });
fireEvent.change(url, { target: { value: '/uploads/draft.mp4' } });
fireEvent.submit(document.getElementById('videoForm')!);
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در ذخیره‌سازی ویدئو'));
expect(screen.getByDisplayValue('Draft video')).toBeInTheDocument(); expect(toast.success).not.toHaveBeenCalled();
});
it('handles already-deleted videos by reporting 404 and refreshing', async () => {
vi.mocked(api.delete).mockRejectedValueOnce({ response: { status: 404 } });
render(<Videos />); await screen.findByText('آموزش استفاده از مکمل کانی‌هیدروکس');
fireEvent.click(screen.getAllByTitle('حذف ویدئو')[0]); fireEvent.click(screen.getByRole('button', { name: 'تایید' }));
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('این ویدئو در پایگاه داده یافت نشد (احتمالاً قبلاً حذف شده است).'));
await waitFor(() => expect(api.get).toHaveBeenCalledTimes(3)); expect(toast.success).not.toHaveBeenCalled();
});
it('handles empty state when no videos exist', async () => {
(api.get as any).mockImplementation((url: string) => {
if (url === '/videos') {
return Promise.resolve({ data: { videos: [], meta: { totalPages: 1, total: 0 } } });
}
return Promise.resolve({ data: { doctors: [] } });
});
render(<Videos />);
await waitFor(() => {
expect(screen.getByText('هیچ ویدئویی یافت نشد')).toBeInTheDocument();
expect(screen.getByText('با کلیک روی دکمه افزودن، اولین ویدئو را اضافه کنید.')).toBeInTheDocument();
});
});
});