test: comprehensive test suites and quality gates pass across backend, storefront and admin
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s

- 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.
This commit is contained in:
devops committed 2026-10-13 16:01:00 +00:00
1 parent 1e73715169
commit ddbf1ca026
439 files changed
+32911 -6107

No files matched your search

@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState } from 'react';
import { Outlet } from 'react-router-dom';
import Sidebar from './Sidebar';
import Topbar from './Topbar';
@@ -0,0 +1,224 @@
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
import { MemoryRouter,Route,Routes } from 'react-router-dom';
import { beforeEach,describe,expect,it,vi } from 'vitest';
import api from '../services/api';
import { useAdminAuthStore } from '../store/adminAuthStore';
import Layout from './Layout';
import Sidebar from './Sidebar';
import Topbar from './Topbar';
vi.mock('../services/api', () => ({
default: {
get: vi.fn().mockResolvedValue({ data: { success: true, data: { newOrders: 5 } } }),
post: vi.fn().mockResolvedValue({ data: { success: true } }),
},
}));
describe('Admin Panel Navigation Components', () => {
beforeEach(() => {
vi.clearAllMocks();
useAdminAuthStore.getState().clearAuth();
localStorage.clear();
});
describe('Sidebar component', () => {
it('renders navigation group headings and sub-menu items', () => {
const setIsOpen = vi.fn();
render(
<MemoryRouter initialEntries={['/']}>
<Sidebar isOpen={true} setIsOpen={setIsOpen} />
</MemoryRouter>
);
// Verify main group titles
expect(screen.getByText('داشبورد و تحلیل داده')).toBeInTheDocument();
expect(screen.getByText('سفارشات و مالی')).toBeInTheDocument();
expect(screen.getByText('محصولات و کاتالوگ')).toBeInTheDocument();
// Default active group is 'main', check its items
expect(screen.getByText('نمای کلی داشبورد')).toBeInTheDocument();
expect(screen.getByText('گزارشات و تحلیل فروش')).toBeInTheDocument();
});
it('highlights the active route based on current path and auto-expands its group', () => {
const setIsOpen = vi.fn();
render(
<MemoryRouter initialEntries={['/orders']}>
<Sidebar isOpen={true} setIsOpen={setIsOpen} />
</MemoryRouter>
);
// Group 'سفارشات و مالی' should be open
const ordersLink = screen.getByRole('link', { name: /مدیریت سفارشات/i });
expect(ordersLink).toBeInTheDocument();
expect(ordersLink.className).toContain('bg-purple-600');
});
it('toggles groups when clicking group accordion buttons', () => {
const setIsOpen = vi.fn();
render(
<MemoryRouter initialEntries={['/']}>
<Sidebar isOpen={true} setIsOpen={setIsOpen} />
</MemoryRouter>
);
// Initially products group items are collapsed
expect(screen.queryByText('لیست محصولات')).not.toBeInTheDocument();
// Click group button
const productsGroupBtn = screen.getByRole('button', { name: /محصولات و کاتالوگ/i });
fireEvent.click(productsGroupBtn);
// Now items should be visible
expect(screen.getByText('لیست محصولات')).toBeInTheDocument();
expect(screen.getByText('دسته‌بندی‌های تخصصی')).toBeInTheDocument();
});
it('renders badges when fetched from stats API', async () => {
vi.mocked(api.get).mockResolvedValueOnce({
data: { success: true, data: { newOrders: 7 } },
});
render(
<MemoryRouter initialEntries={['/orders']}>
<Sidebar isOpen={true} setIsOpen={vi.fn()} />
</MemoryRouter>
);
await waitFor(() => {
expect(screen.getByText('7')).toBeInTheDocument();
});
});
it('calls setIsOpen(false) when clicking an item link', () => {
const setIsOpen = vi.fn();
render(
<MemoryRouter initialEntries={['/']}>
<Sidebar isOpen={true} setIsOpen={setIsOpen} />
</MemoryRouter>
);
const dashboardLink = screen.getByRole('link', { name: /نمای کلی داشبورد/i });
fireEvent.click(dashboardLink);
expect(setIsOpen).toHaveBeenCalledWith(false);
});
it('renders in collapsed mode correctly with tooltip triggers', () => {
render(
<MemoryRouter initialEntries={['/']}>
<Sidebar isOpen={false} setIsOpen={vi.fn()} isCollapsed={true} />
</MemoryRouter>
);
const aside = screen.getByRole('complementary');
expect(aside.className).toContain('lg:w-20');
});
});
describe('Topbar component', () => {
it('displays user profile info, role, and toggle buttons', () => {
useAdminAuthStore.getState().setAuth('test-token', {
id: '1',
mobile: '09123456789',
role: 'SUPER_ADMIN',
firstName: 'علی',
lastName: 'محمدی',
});
const toggleMenu = vi.fn();
const toggleCollapse = vi.fn();
render(
<MemoryRouter initialEntries={['/']}>
<Topbar toggleMenu={toggleMenu} isCollapsed={false} toggleCollapse={toggleCollapse} />
</MemoryRouter>
);
expect(screen.getByText('علی محمدی')).toBeInTheDocument();
expect(screen.getByText('SUPER_ADMIN')).toBeInTheDocument();
// Collapse toggle button
const collapseBtn = screen.getByRole('button', { name: /کوچک کردن سایدبار/i });
fireEvent.click(collapseBtn);
expect(toggleCollapse).toHaveBeenCalledTimes(1);
// Mobile menu button
const mobileBtn = screen.getByRole('button', { name: /باز کردن منو/i });
fireEvent.click(mobileBtn);
expect(toggleMenu).toHaveBeenCalledTimes(1);
});
it('filters searchable pages with live autocomplete dropdown', async () => {
render(
<MemoryRouter initialEntries={['/']}>
<Topbar toggleMenu={vi.fn()} />
</MemoryRouter>
);
const searchInput = screen.getByPlaceholderText('جستجوی سریع در بخش‌های پنل...');
fireEvent.change(searchInput, { target: { value: 'سفارش' } });
expect(await screen.findByText('مدیریت سفارشات مشتریان')).toBeInTheDocument();
// Click the search result item
fireEvent.click(screen.getByText('مدیریت سفارشات مشتریان'));
expect(screen.queryByText('مدیریت سفارشات مشتریان')).not.toBeInTheDocument();
expect(searchInput).toHaveValue('');
});
it('handles user menu dropdown and logout trigger', async () => {
useAdminAuthStore.getState().setAuth('test-token', {
id: 'admin-1',
mobile: '09123456789',
role: 'ADMIN',
firstName: 'مدیر',
lastName: 'سیستم',
});
render(
<MemoryRouter initialEntries={['/']}>
<Topbar toggleMenu={vi.fn()} />
</MemoryRouter>
);
// Click profile button to open dropdown
const profileBtn = screen.getByText('مدیر سیستم').closest('button');
expect(profileBtn).not.toBeNull();
fireEvent.click(profileBtn!);
expect(screen.getByText('مرکز مانیتورینگ')).toBeInTheDocument();
expect(screen.getByText('خروج از حساب')).toBeInTheDocument();
// Click logout
const logoutBtn = screen.getByText('خروج از حساب');
fireEvent.click(logoutBtn);
await waitFor(() => {
expect(api.post).toHaveBeenCalledWith('/auth/logout');
expect(useAdminAuthStore.getState().isAuthenticated).toBe(false);
});
});
});
describe('Layout integration', () => {
it('integrates Sidebar, Topbar and Outlet with collapse toggling and persistence', () => {
render(
<MemoryRouter initialEntries={['/test']}>
<Routes>
<Route path="/" element={<Layout />}>
<Route path="test" element={<div>Nested Content View</div>} />
</Route>
</Routes>
</MemoryRouter>
);
expect(screen.getByText('Nested Content View')).toBeInTheDocument();
expect(screen.getByRole('complementary')).toBeInTheDocument();
// Toggle sidebar collapse
const collapseBtn = screen.getByRole('button', { name: /کوچک کردن سایدبار/i });
fireEvent.click(collapseBtn);
expect(localStorage.getItem('canina_admin_sidebar_collapsed')).toBe('true');
});
});
});
@@ -0,0 +1,151 @@
import { render,screen,waitFor } from '@testing-library/react';
import { MemoryRouter,Route,Routes } from 'react-router-dom';
import { beforeEach,describe,expect,it,vi } from 'vitest';
import api from '../services/api';
import { useAdminAuthStore } from '../store/adminAuthStore';
import type { AdminUser } from '../types/admin';
import ProtectedRoute from './ProtectedRoute';
vi.mock('../services/api', () => ({
default: {
post: vi.fn(),
get: vi.fn(),
},
}));
describe('ProtectedRoute Guard Component', () => {
const superAdminUser: AdminUser = {
id: 'user-1',
mobile: '09120000000',
role: 'SUPER_ADMIN',
};
const regularAdminUser: AdminUser = {
id: 'user-2',
mobile: '09121111111',
role: 'ADMIN',
};
const customerUser: AdminUser = {
id: 'user-3',
mobile: '09122222222',
role: 'CUSTOMER',
};
beforeEach(() => {
vi.clearAllMocks();
useAdminAuthStore.getState().clearAuth();
localStorage.clear();
});
const renderWithRouter = () => {
return render(
<MemoryRouter initialEntries={['/admin/dashboard']}>
<Routes>
<Route path="/login" element={<div>Login Page</div>} />
<Route element={<ProtectedRoute />}>
<Route path="/admin/dashboard" element={<div>Admin Dashboard Content</div>} />
</Route>
</Routes>
</MemoryRouter>
);
};
it('renders protected child content immediately when already authenticated with ADMIN role', async () => {
useAdminAuthStore.getState().setAuth('valid-token', regularAdminUser);
renderWithRouter();
expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument();
});
it('renders protected child content immediately when authenticated with SUPER_ADMIN role', async () => {
useAdminAuthStore.getState().setAuth('valid-token', superAdminUser);
renderWithRouter();
expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument();
});
it('redirects to /login if user is authenticated but does not have ADMIN or SUPER_ADMIN role', async () => {
useAdminAuthStore.getState().setAuth('valid-token', customerUser);
renderWithRouter();
expect(await screen.findByText('Login Page')).toBeInTheDocument();
expect(screen.queryByText('Admin Dashboard Content')).not.toBeInTheDocument();
});
it('redirects to /login when completely unauthenticated (no token, no user)', async () => {
renderWithRouter();
expect(await screen.findByText('Login Page')).toBeInTheDocument();
expect(screen.queryByText('Admin Dashboard Content')).not.toBeInTheDocument();
});
it('refreshes token successfully via /auth/refresh when accessToken exists but state is unauthenticated', async () => {
useAdminAuthStore.setState({
accessToken: 'stale-token',
isAuthenticated: false,
adminUser: null,
});
vi.mocked(api.post).mockResolvedValueOnce({
data: {
success: true,
data: {
accessToken: 'fresh-token',
user: regularAdminUser,
},
},
});
renderWithRouter();
expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument();
expect(api.post).toHaveBeenCalledWith('/auth/refresh');
expect(useAdminAuthStore.getState().accessToken).toBe('fresh-token');
expect(useAdminAuthStore.getState().isAuthenticated).toBe(true);
});
it('falls back to /users/profile when /auth/refresh fails, and succeeds if profile is valid', async () => {
useAdminAuthStore.setState({
accessToken: 'persisted-token',
isAuthenticated: false,
adminUser: null,
});
vi.mocked(api.post).mockRejectedValueOnce(new Error('Refresh failed'));
vi.mocked(api.get).mockResolvedValueOnce({
data: {
success: true,
data: superAdminUser,
},
});
renderWithRouter();
expect(await screen.findByText('Admin Dashboard Content')).toBeInTheDocument();
expect(api.get).toHaveBeenCalledWith('/users/profile');
expect(useAdminAuthStore.getState().isAuthenticated).toBe(true);
});
it('clears auth and redirects to /login when both refresh and profile validation fail', async () => {
useAdminAuthStore.setState({
accessToken: 'invalid-token',
isAuthenticated: false,
adminUser: null,
});
vi.mocked(api.post).mockRejectedValueOnce(new Error('Refresh failed'));
vi.mocked(api.get).mockRejectedValueOnce(new Error('Profile failed'));
renderWithRouter();
expect(await screen.findByText('Login Page')).toBeInTheDocument();
await waitFor(() => {
expect(useAdminAuthStore.getState().isAuthenticated).toBe(false);
expect(useAdminAuthStore.getState().accessToken).toBeNull();
});
});
});
@@ -1,8 +1,8 @@
import { useState, useEffect } from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { useEffect,useState } from 'react';
import { Navigate,Outlet } from 'react-router-dom';
import api from '../services/api';
import { useAdminAuthStore } from '../store/adminAuthStore';
import type { ApiResponse, AuthResponseData, AdminUser } from '../types/admin';
import type { AdminUser,ApiResponse,AuthResponseData } from '../types/admin';
export default function ProtectedRoute() {
const { isAuthenticated, accessToken, setAuth, clearAuth } = useAdminAuthStore();
@@ -1,5 +1,5 @@
import { Component, ReactNode, ErrorInfo } from 'react';
import { AlertCircle, RefreshCw, Home } from 'lucide-react';
import { AlertCircle,Home,RefreshCw } from 'lucide-react';
import { Component,type ErrorInfo,type ReactNode } from 'react';
interface Props {
children: ReactNode;
+38 -38
View File
@@ -1,43 +1,43 @@
import { useState, useEffect, useRef } from 'react';
import { Link, useLocation } from 'react-router-dom';
import {
LayoutDashboard,
TrendingUp,
ShoppingCart,
Receipt,
Package,
FolderTree,
Tag,
Sparkles,
FileText,
Users,
Heart,
MessageSquare,
Building2,
PhoneCall,
Image,
FlaskConical,
MessageSquareQuote,
BookOpen,
Video,
Settings,
ShieldCheck,
Languages,
UserCheck,
DollarSign,
CreditCard,
Truck,
Sliders,
Globe,
ChevronDown,
Star,
Layers,
HelpCircle,
Menu,
RotateCcw,
Activity,
Key,
Activity,
BookOpen,
Building2,
ChevronDown,
CreditCard,
DollarSign,
FileText,
FlaskConical,
FolderTree,
Globe,
Heart,
HelpCircle,
Image,
Key,
Languages,
Layers,
LayoutDashboard,
Menu,
MessageSquare,
MessageSquareQuote,
Package,
PhoneCall,
Receipt,
RotateCcw,
Settings,
ShieldCheck,
ShoppingCart,
Sliders,
Sparkles,
Star,
Tag,
TrendingUp,
Truck,
UserCheck,
Users,
Video,
} from 'lucide-react';
import { useEffect,useRef,useState } from 'react';
import { Link,useLocation } from 'react-router-dom';
import api from '../services/api';
interface SubMenuItem {
@@ -1,7 +1,7 @@
import { useState, useRef, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Search, UserCircle, Menu, Activity, ShieldCheck, MessageSquare, Calendar, Clock, RefreshCw, PanelRightClose, PanelRightOpen } from 'lucide-react';
import { Activity,Clock,Menu,PanelRightClose,PanelRightOpen,Search,UserCircle } from 'lucide-react';
import { useEffect,useRef,useState } from 'react';
import { toast } from 'react-hot-toast';
import { Link,useNavigate } from 'react-router-dom';
import api from '../services/api';
import { useAdminAuthStore } from '../store/adminAuthStore';
@@ -1,5 +1,4 @@
import React from 'react';
import { Printer, X, CheckCircle2, ShieldCheck, Copy } from 'lucide-react';
import { Copy,Printer,ShieldCheck,X } from 'lucide-react';
import { toast } from 'react-hot-toast';
import Button from './ui/Button';
@@ -0,0 +1,62 @@
import { fireEvent,render,screen } from '@testing-library/react';
import { describe,expect,it,vi } from 'vitest';
import Button from './Button';
describe('Button Component', () => {
it('renders children correctly', () => {
render(<Button>کلیک کنید</Button>);
expect(screen.getByRole('button', { name: 'کلیک کنید' })).toBeInTheDocument();
});
it('renders with different variants and size styling classes', () => {
const { rerender } = render(<Button variant="danger" size="sm">حذف</Button>);
let btn = screen.getByRole('button');
expect(btn.className).toContain('bg-rose-600');
expect(btn.className).toContain('px-3');
rerender(<Button variant="success" size="lg">تایید</Button>);
btn = screen.getByRole('button');
expect(btn.className).toContain('bg-emerald-600');
expect(btn.className).toContain('px-5');
});
it('handles click events when enabled', () => {
const handleClick = vi.fn();
render(<Button onClick={handleClick}>کلیک</Button>);
fireEvent.click(screen.getByRole('button'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
it('shows spinner and disables button when isLoading is true', () => {
const handleClick = vi.fn();
render(<Button isLoading onClick={handleClick}>ارسال</Button>);
const btn = screen.getByRole('button');
expect(btn).toBeDisabled();
expect(screen.queryByText('ارسال')).not.toBeInTheDocument();
fireEvent.click(btn);
expect(handleClick).not.toHaveBeenCalled();
});
it('renders startIcon, endIcon, badge, and info tooltip correctly', () => {
const MockIcon = ({ className }: { className?: string }) => <svg data-testid="mock-icon" className={className} />;
render(
<Button
startIcon={MockIcon}
endIcon={MockIcon}
badge={5}
info="اطلاعات کمکی"
>
آیتم
</Button>
);
const icons = screen.getAllByTestId('mock-icon');
expect(icons.length).toBe(2);
expect(screen.getByText('5')).toBeInTheDocument();
expect(screen.getByTitle('اطلاعات کمکی')).toBeInTheDocument();
});
});
@@ -1,5 +1,5 @@
import React from 'react';
import { Info } from 'lucide-react';
import React from 'react';
import Spinner from './Spinner';
export type ButtonVariant =
@@ -0,0 +1,97 @@
import { fireEvent,render,screen } from '@testing-library/react';
import { describe,expect,it,vi } from 'vitest';
import ConfirmModal from './ConfirmModal';
describe('ConfirmModal Component', () => {
const defaultProps = {
isOpen: true,
title: 'حذف آیتم',
message: 'آیا از حذف این آیتم اطمینان دارید؟',
onConfirm: vi.fn(),
onCancel: vi.fn(),
};
it('does not render when isOpen is false', () => {
const { container } = render(<ConfirmModal {...defaultProps} isOpen={false} />);
expect(container.firstChild).toBeNull();
});
it('renders title, message, and default button texts when isOpen is true', () => {
render(<ConfirmModal {...defaultProps} />);
expect(screen.getByText('حذف آیتم')).toBeInTheDocument();
expect(screen.getByText('آیا از حذف این آیتم اطمینان دارید؟')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'تایید' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'لغو' })).toBeInTheDocument();
});
it('calls onConfirm when confirm button is clicked', () => {
const onConfirmMock = vi.fn();
render(<ConfirmModal {...defaultProps} onConfirm={onConfirmMock} />);
const confirmButton = screen.getByRole('button', { name: 'تایید' });
fireEvent.click(confirmButton);
expect(onConfirmMock).toHaveBeenCalledTimes(1);
});
it('calls onCancel when cancel button or close X is clicked', () => {
const onCancelMock = vi.fn();
render(<ConfirmModal {...defaultProps} onCancel={onCancelMock} />);
const cancelButton = screen.getByRole('button', { name: 'لغو' });
fireEvent.click(cancelButton);
expect(onCancelMock).toHaveBeenCalledTimes(1);
const buttons = screen.getAllByRole('button');
const closeIconButton = buttons[0];
fireEvent.click(closeIconButton);
expect(onCancelMock).toHaveBeenCalledTimes(2);
});
it('renders custom confirm and cancel texts', () => {
render(
<ConfirmModal
{...defaultProps}
confirmText="بله، حذف کن"
cancelText="انصراف"
/>
);
expect(screen.getByRole('button', { name: 'بله، حذف کن' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'انصراف' })).toBeInTheDocument();
});
it('disables buttons and shows loading text when isLoading is true', () => {
const onConfirmMock = vi.fn();
const onCancelMock = vi.fn();
render(
<ConfirmModal
{...defaultProps}
isLoading={true}
onConfirm={onConfirmMock}
onCancel={onCancelMock}
/>
);
const confirmButton = screen.getByRole('button', { name: 'در حال پردازش...' });
const cancelButton = screen.getByRole('button', { name: 'لغو' });
expect(confirmButton).toBeDisabled();
expect(cancelButton).toBeDisabled();
fireEvent.click(confirmButton);
fireEvent.click(cancelButton);
expect(onConfirmMock).not.toHaveBeenCalled();
expect(onCancelMock).not.toHaveBeenCalled();
});
it('applies non-destructive styling when isDestructive is false', () => {
render(<ConfirmModal {...defaultProps} isDestructive={false} />);
const confirmButton = screen.getByRole('button', { name: 'تایید' });
expect(confirmButton.className).toContain('bg-purple-600');
});
});
@@ -1,4 +1,4 @@
import { X, AlertTriangle } from 'lucide-react';
import { AlertTriangle,X } from 'lucide-react';
interface ConfirmModalProps {
isOpen: boolean;
@@ -1,5 +1,5 @@
import React from 'react';
import { HelpCircle } from 'lucide-react';
import React from 'react';
export interface FormFieldProps {
label?: string;
@@ -1,45 +1,45 @@
import React, { useState, useMemo } from 'react';
import {
X,
Search,
Check,
Smile,
Pill,
ShieldCheck,
HeartPulse,
Sparkles,
ShoppingBag,
User,
Building2,
PhoneCall,
Activity,
Heart,
Dog,
BookOpen,
FileText,
Video,
Award,
Star,
Truck,
HelpCircle,
MessageSquare,
Globe,
Settings,
Flame,
CheckCircle2,
AlertCircle,
ThumbsUp,
Package,
Layers,
Compass,
MapPin,
Mail,
Send,
Zap,
Tag,
Gift,
Clock,
Activity,
AlertCircle,
Award,
BookOpen,
Building2,
Check,
CheckCircle2,
Clock,
Compass,
Dog,
FileText,
Flame,
Gift,
Globe,
Heart,
HeartPulse,
HelpCircle,
Layers,
Mail,
MapPin,
MessageSquare,
Package,
PhoneCall,
Pill,
Search,
Send,
Settings,
ShieldCheck,
ShoppingBag,
Smile,
Sparkles,
Star,
Tag,
ThumbsUp,
Truck,
User,
Video,
X,
Zap,
} from 'lucide-react';
import React,{ useMemo,useState } from 'react';
interface IconPickerModalProps {
isOpen: boolean;
@@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { X, ZoomIn, ZoomOut, Download, ExternalLink } from 'lucide-react';
import { ExternalLink,X,ZoomIn,ZoomOut } from 'lucide-react';
import React,{ useEffect } from 'react';
export interface ImagePreviewModalProps {
isOpen: boolean;
@@ -1,4 +1,4 @@
import React, { forwardRef } from 'react';
import React,{ forwardRef } from 'react';
export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
error?: string;
@@ -1,5 +1,5 @@
import React, { useState } from 'react';
import { Eye, EyeOff, Copy, Check } from 'lucide-react';
import { Check,Copy,Eye,EyeOff } from 'lucide-react';
import React,{ useState } from 'react';
import { toast } from 'react-hot-toast';
interface MaskableFieldProps {
@@ -0,0 +1,188 @@
import { fireEvent,render,screen,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,it,vi } from 'vitest';
import api from '../../services/api';
import MediaSelector from './MediaSelector';
vi.mock('../../services/api', () => ({
default: {
get: vi.fn(),
post: vi.fn(),
delete: vi.fn(),
},
BASE_DOMAIN: 'https://test.canina.ir',
}));
describe('MediaSelector Modal Component', () => {
const mockMediaData = [
{
id: 'media-1',
url: '/uploads/product-1.jpg',
filename: 'product-1.jpg',
createdAt: '2025-01-01T10:00:00Z',
mimetype: 'image/jpeg',
},
{
id: 'media-2',
url: '/uploads/guide-video.mp4',
filename: 'guide-video.mp4',
createdAt: '2025-01-02T10:00:00Z',
mimetype: 'video/mp4',
},
{
id: 'media-3',
url: '/uploads/catalog.pdf',
filename: 'catalog.pdf',
createdAt: '2025-01-03T10:00:00Z',
mimetype: 'application/pdf',
},
];
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(api.get).mockResolvedValue({
data: { success: true, data: mockMediaData },
});
});
it('renders nothing when isOpen is false', () => {
const { container } = render(
<MediaSelector isOpen={false} onClose={vi.fn()} onSelect={vi.fn()} />
);
expect(container.firstChild).toBeNull();
});
it('fetches and displays media items when isOpen is true', async () => {
render(
<MediaSelector isOpen={true} onClose={vi.fn()} onSelect={vi.fn()} />
);
expect(await screen.findByText('گالری و مدیریت رسانه')).toBeInTheDocument();
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
expect(screen.getByText('guide-video.mp4')).toBeInTheDocument();
expect(screen.getByText('catalog.pdf')).toBeInTheDocument();
expect(api.get).toHaveBeenCalledWith('/admin/media');
});
it('filters media list by file type tabs', async () => {
render(
<MediaSelector isOpen={true} onClose={vi.fn()} onSelect={vi.fn()} />
);
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
// Click 'ویدئوها' tab
const videoTab = screen.getByRole('button', { name: 'ویدئوها' });
fireEvent.click(videoTab);
// Only video should remain visible
expect(screen.getByText('guide-video.mp4')).toBeInTheDocument();
expect(screen.queryByText('product-1.jpg')).not.toBeInTheDocument();
expect(screen.queryByText('catalog.pdf')).not.toBeInTheDocument();
// Click 'اسناد PDF' tab
const pdfTab = screen.getByRole('button', { name: 'اسناد PDF' });
fireEvent.click(pdfTab);
expect(screen.getByText('catalog.pdf')).toBeInTheDocument();
expect(screen.queryByText('guide-video.mp4')).not.toBeInTheDocument();
});
it('selects an item on click and confirms selection with the footer button', async () => {
const onSelect = vi.fn();
const onClose = vi.fn();
render(
<MediaSelector isOpen={true} onClose={onClose} onSelect={onSelect} />
);
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
const submitBtn = screen.getByRole('button', { name: /انتخاب و ثبت فایل/i });
expect(submitBtn).toBeDisabled();
// Click on the product card
const cardText = screen.getByText('product-1.jpg');
fireEvent.click(cardText);
// Now submit button should be enabled
expect(submitBtn).not.toBeDisabled();
expect(screen.getByText(/۱ فایل انتخاب شد/i)).toBeInTheDocument();
// Click submit
fireEvent.click(submitBtn);
expect(onSelect).toHaveBeenCalledWith('https://test.canina.ir/uploads/product-1.jpg');
expect(onClose).toHaveBeenCalled();
});
it('immediately confirms and closes on card double-click', async () => {
const onSelect = vi.fn();
const onClose = vi.fn();
render(
<MediaSelector isOpen={true} onClose={onClose} onSelect={onSelect} />
);
const cardText = await screen.findByText('product-1.jpg');
fireEvent.doubleClick(cardText);
expect(onSelect).toHaveBeenCalledWith('https://test.canina.ir/uploads/product-1.jpg');
expect(onClose).toHaveBeenCalled();
});
it('opens preview modal when eye button is clicked', async () => {
render(
<MediaSelector isOpen={true} onClose={vi.fn()} onSelect={vi.fn()} />
);
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
const eyeButtons = screen.getAllByTitle('مشاهده');
expect(eyeButtons.length).toBeGreaterThan(0);
fireEvent.click(eyeButtons[0]);
// Modal or preview image should be triggered
await waitFor(() => {
const previewImg = document.querySelector('img[src="https://test.canina.ir/uploads/product-1.jpg"]');
expect(previewImg).toBeInTheDocument();
});
});
it('triggers delete confirm modal and executes delete on confirmation', async () => {
vi.mocked(api.delete).mockResolvedValueOnce({ data: { success: true } });
render(
<MediaSelector isOpen={true} onClose={vi.fn()} onSelect={vi.fn()} />
);
expect(await screen.findByText('product-1.jpg')).toBeInTheDocument();
const deleteButtons = screen.getAllByTitle('حذف فایل');
fireEvent.click(deleteButtons[0]);
expect(await screen.findByText('حذف تصویر')).toBeInTheDocument();
expect(screen.getByText(/آیا از حذف این تصویر مطمئن هستید؟/i)).toBeInTheDocument();
// Confirm deletion
const confirmBtn = screen.getByRole('button', { name: /تایید/i });
fireEvent.click(confirmBtn);
await waitFor(() => {
expect(api.delete).toHaveBeenCalledWith('/admin/media/media-1');
expect(screen.queryByText('product-1.jpg')).not.toBeInTheDocument();
});
});
it('calls onClose when clicking close icon or cancel button', async () => {
const onClose = vi.fn();
render(
<MediaSelector isOpen={true} onClose={onClose} onSelect={vi.fn()} />
);
await screen.findByText('گالری و مدیریت رسانه');
const cancelBtn = screen.getByRole('button', { name: 'انصراف' });
fireEvent.click(cancelBtn);
expect(onClose).toHaveBeenCalled();
});
});
@@ -1,11 +1,11 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { X, Upload, Image as ImageIcon, Trash2, CheckCircle2, Clipboard, Eye, Video, FileText, Music, Play } from 'lucide-react';
import { CheckCircle2,Clipboard,Eye,FileText,Image as ImageIcon,Music,Play,Trash2,Upload,X } from 'lucide-react';
import { useCallback,useEffect,useRef,useState } from 'react';
import { toast } from 'react-hot-toast';
import api, { BASE_DOMAIN } from '../../services/api';
import Spinner from './Spinner';
import Pagination from './Pagination';
import api,{ BASE_DOMAIN } from '../../services/api';
import ConfirmModal from './ConfirmModal';
import ImagePreviewModal from './ImagePreviewModal';
import Pagination from './Pagination';
import Spinner from './Spinner';
interface Media {
id: string;
@@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { X } from 'lucide-react';
import React,{ useEffect } from 'react';
export interface ModalProps {
isOpen: boolean;
@@ -0,0 +1,111 @@
import { fireEvent,render,screen } from '@testing-library/react';
import { describe,expect,it,vi } from 'vitest';
import Pagination from './Pagination';
describe('Pagination Component', () => {
it('renders nothing when totalPages is 1 or less', () => {
const { container: c1 } = render(
<Pagination currentPage={1} totalPages={1} onPageChange={vi.fn()} />
);
expect(c1.firstChild).toBeNull();
const { container: c0 } = render(
<Pagination currentPage={1} totalPages={0} onPageChange={vi.fn()} />
);
expect(c0.firstChild).toBeNull();
});
it('renders navigation buttons and page numbers when totalPages > 1', () => {
render(
<Pagination currentPage={2} totalPages={5} onPageChange={vi.fn()} />
);
expect(screen.getByTitle('صفحه اول')).toBeInTheDocument();
expect(screen.getByTitle('صفحه قبلی')).toBeInTheDocument();
expect(screen.getByTitle('صفحه بعدی')).toBeInTheDocument();
expect(screen.getByTitle('صفحه آخر')).toBeInTheDocument();
// Check Persian digit representation of current page 2 ('۲')
const page2Button = screen.getByRole('button', { name: (2).toLocaleString('fa-IR') });
expect(page2Button).toBeInTheDocument();
expect(page2Button.className).toContain('bg-purple-600');
});
it('disables first and previous buttons on the first page', () => {
render(
<Pagination currentPage={1} totalPages={5} onPageChange={vi.fn()} />
);
const firstBtn = screen.getByTitle('صفحه اول');
const prevBtn = screen.getByTitle('صفحه قبلی');
const nextBtn = screen.getByTitle('صفحه بعدی');
const lastBtn = screen.getByTitle('صفحه آخر');
expect(firstBtn).toBeDisabled();
expect(prevBtn).toBeDisabled();
expect(nextBtn).not.toBeDisabled();
expect(lastBtn).not.toBeDisabled();
});
it('disables next and last buttons on the last page', () => {
render(
<Pagination currentPage={5} totalPages={5} onPageChange={vi.fn()} />
);
const firstBtn = screen.getByTitle('صفحه اول');
const prevBtn = screen.getByTitle('صفحه قبلی');
const nextBtn = screen.getByTitle('صفحه بعدی');
const lastBtn = screen.getByTitle('صفحه آخر');
expect(firstBtn).not.toBeDisabled();
expect(prevBtn).not.toBeDisabled();
expect(nextBtn).toBeDisabled();
expect(lastBtn).toBeDisabled();
});
it('calls onPageChange with correct page numbers when navigation buttons are clicked', () => {
const handlePageChange = vi.fn();
render(
<Pagination currentPage={3} totalPages={10} onPageChange={handlePageChange} />
);
fireEvent.click(screen.getByTitle('صفحه اول'));
expect(handlePageChange).toHaveBeenCalledWith(1);
fireEvent.click(screen.getByTitle('صفحه قبلی'));
expect(handlePageChange).toHaveBeenCalledWith(2);
fireEvent.click(screen.getByTitle('صفحه بعدی'));
expect(handlePageChange).toHaveBeenCalledWith(4);
fireEvent.click(screen.getByTitle('صفحه آخر'));
expect(handlePageChange).toHaveBeenCalledWith(10);
});
it('navigates directly via jump input form', () => {
const handlePageChange = vi.fn();
render(
<Pagination currentPage={2} totalPages={10} onPageChange={handlePageChange} />
);
const input = screen.getByPlaceholderText('2');
const submitBtn = screen.getByRole('button', { name: /برو/ });
// Valid jump
fireEvent.change(input, { target: { value: '7' } });
fireEvent.click(submitBtn);
expect(handlePageChange).toHaveBeenCalledWith(7);
// Invalid jump (out of range > totalPages)
handlePageChange.mockClear();
fireEvent.change(input, { target: { value: '15' } });
fireEvent.click(submitBtn);
expect(handlePageChange).not.toHaveBeenCalled();
// Invalid jump (<= 0)
handlePageChange.mockClear();
fireEvent.change(input, { target: { value: '0' } });
fireEvent.click(submitBtn);
expect(handlePageChange).not.toHaveBeenCalled();
});
});
@@ -1,4 +1,4 @@
import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-react';
import { ChevronLeft,ChevronRight,ChevronsLeft,ChevronsRight } from 'lucide-react';
import { useState } from 'react';
interface PaginationProps {
@@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React,{ useEffect,useState } from 'react';
interface PriceInputProps {
value: number | string;
@@ -38,7 +38,6 @@ export default function PriceInput({
suffix = 'تومان',
disabled = false,
required = false,
min,
max,
name,
id,
@@ -1,33 +1,33 @@
import React, { useRef, useEffect, useState, useCallback } from 'react';
import {
Bold,
Italic,
Underline,
Heading1,
Heading2,
Heading3,
Heading4,
List,
ListOrdered,
Link as LinkIcon,
AlignRight,
AlignCenter,
AlignLeft,
Palette,
PaintBucket,
Undo,
Redo,
Code,
RemoveFormatting,
Image as ImageIcon,
Video,
Music,
Table as TableIcon,
Quote,
Minus,
Maximize2,
Minimize2,
AlignCenter,
AlignLeft,
AlignRight,
Bold,
Code,
Heading1,
Heading2,
Heading3,
Heading4,
Image as ImageIcon,
Italic,
Link as LinkIcon,
List,
ListOrdered,
Maximize2,
Minimize2,
Minus,
Music,
PaintBucket,
Palette,
Quote,
Redo,
RemoveFormatting,
Table as TableIcon,
Underline,
Undo,
Video,
} from 'lucide-react';
import { useCallback,useEffect,useRef,useState } from 'react';
import MediaSelector from './MediaSelector';
interface RichTextEditorProps {
@@ -1,5 +1,5 @@
import React, { forwardRef } from 'react';
import { ChevronDown } from 'lucide-react';
import React,{ forwardRef } from 'react';
export interface SelectOption {
value: string | number;
@@ -1,4 +1,4 @@
import React, { forwardRef } from 'react';
import React,{ forwardRef } from 'react';
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
error?: string;
@@ -1,5 +1,5 @@
import { ArrowDown,ArrowUp,ArrowUpDown } from 'lucide-react';
import React from 'react';
import { ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
export interface ThSortProps {
column: string;
@@ -1,4 +1,3 @@
import React from 'react';
export interface ToggleSwitchProps {
checked: boolean;