"use client";
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import React from 'react';
import CartDrawer from '../CartDrawer';
import { useCartStore } from '../../lib/store/cartStore';
import { useUserStore } from '../../lib/store/userStore';
import { useSettingsStore } from '../../lib/store/settingsStore';
import { useCatalogMode } from '../../lib/useCatalogMode';
import { productService } from '../../lib/services/productService';
import { toast } from 'sonner';
vi.mock('../../lib/store/cartStore', () => ({
useCartStore: Object.assign(vi.fn(), {
getState: vi.fn(),
}),
}));
vi.mock('../../lib/store/userStore', () => ({
useUserStore: vi.fn(),
}));
vi.mock('../../lib/store/settingsStore', () => ({
useSettingsStore: Object.assign(vi.fn(), {
getState: vi.fn(),
}),
}));
vi.mock('../../lib/services/productService', () => ({
productService: {
getProducts: vi.fn(),
},
}));
vi.mock('../../lib/useCatalogMode', () => ({
useCatalogMode: vi.fn(),
}));
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
info: vi.fn(),
},
}));
// Mock child modals to keep unit tests isolated and fast
vi.mock('../AuthModal', () => ({
default: ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) =>
isOpen ?
: null,
}));
vi.mock('../DeleteConfirmModal', () => ({
default: ({
isOpen,
onClose,
onConfirm,
title,
message,
}: {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
title: string;
message: string;
}) =>
isOpen ? (
{title}
{message}
) : null,
}));
const mockProduct = {
id: 'canhydrox-gag',
name: 'Canhydrox GAG',
nameFa: 'کانهیدروکس گگ',
price: '۱,۰۰۰ تومان',
priceValue: 1000,
category: 'joints',
image: '/images/canhydrox.png',
};
const mockSuggestedProduct = {
id: 'lachs-ol',
name: 'Lachs-Öl',
nameFa: 'روغن سالمون خالص',
price: '۵۰۰ تومان',
priceValue: 500,
category: 'skin-coat',
image: '/images/lachs.png',
};
describe('CartDrawer - Extended Interactive Test Suite', () => {
const mockUpdateQuantity = vi.fn();
const mockRemoveItem = vi.fn();
const mockToggleSubscription = vi.fn();
const mockApplyCoupon = vi.fn();
const mockRemoveCoupon = vi.fn();
const mockAddItem = vi.fn();
const mockOnClose = vi.fn();
const mockOnCheckout = vi.fn();
const mockOnShopNavigate = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(productService.getProducts).mockResolvedValue({
data: [mockSuggestedProduct as any],
total: 1,
});
vi.mocked(useUserStore).mockReturnValue({
isLoggedIn: true,
profile: { mobile: '09121234567', firstName: 'تست' },
} as any);
const mockGetText = vi.fn((key: string, def?: string) => {
if (key === 'REFILL_SUBSCRIPTION_ENABLED') return 'true';
if (key === 'REFILL_REWARD_PERCENT') return '5';
if (key === 'contact_phone') return '۰۲۱-۸۸۸۸۴۴۴۴';
if (key === 'contact_phone_link') return 'tel:02188884444';
return def || '';
});
vi.mocked(useSettingsStore).mockImplementation((selector: any) => {
return selector({ getText: mockGetText });
});
(useSettingsStore as any).getState = vi.fn(() => ({
getText: mockGetText,
}));
vi.mocked(useCatalogMode).mockReturnValue({
isCatalogOnly: false,
showPrices: true,
allowCart: true,
allowCheckout: true,
showPreorderBtn: false,
showOrders: true,
showWallet: true,
showCharity: true,
orderDisabledTitle: '',
orderDisabledMessage: '',
});
vi.mocked(useCartStore).mockReturnValue({
items: [{ product: mockProduct as any, quantity: 2 }],
updateQuantity: mockUpdateQuantity,
removeItem: mockRemoveItem,
isSubscribed: false,
toggleSubscription: mockToggleSubscription,
getTotal: () => 2000,
getSubtotal: () => 2000,
getDiscount: () => 0,
coupon: null,
applyCoupon: mockApplyCoupon,
addItem: mockAddItem,
} as any);
(useCartStore as any).getState = vi.fn(() => ({
removeCoupon: mockRemoveCoupon,
}));
});
it('renders empty cart view and calls navigation on button click', () => {
vi.mocked(useCartStore).mockReturnValue({
items: [],
updateQuantity: mockUpdateQuantity,
removeItem: mockRemoveItem,
isSubscribed: false,
toggleSubscription: mockToggleSubscription,
getTotal: () => 0,
getSubtotal: () => 0,
getDiscount: () => 0,
coupon: null,
applyCoupon: mockApplyCoupon,
addItem: mockAddItem,
} as any);
render(
);
expect(screen.getByText('سبد خرید شما خالی است')).toBeInTheDocument();
const shopBtn = screen.getByText('مشاهده محصولات تخصصی');
fireEvent.click(shopBtn);
expect(mockOnClose).toHaveBeenCalled();
expect(mockOnShopNavigate).toHaveBeenCalled();
});
it('handles item quantity increment and decrement clicks', () => {
render(
);
const plusBtn = screen.getByTestId('plus-btn');
const minusBtn = screen.getByTestId('minus-btn');
fireEvent.click(plusBtn);
expect(mockUpdateQuantity).toHaveBeenCalledWith('canhydrox-gag', 3);
fireEvent.click(minusBtn);
expect(mockUpdateQuantity).toHaveBeenCalledWith('canhydrox-gag', 1);
});
it('shows inline delete confirmation overlay and deletes item on confirm', () => {
render(
);
const deleteBtn = screen.getByTestId('cart-item-delete-btn');
fireEvent.click(deleteBtn);
expect(
screen.getByText('مطمئنی میخوای این محصول رو حذف کنی؟')
).toBeInTheDocument();
const confirmDeleteBtn = screen.getByRole('button', { name: 'حذف' });
fireEvent.click(confirmDeleteBtn);
expect(mockRemoveItem).toHaveBeenCalledWith('canhydrox-gag');
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('Canhydrox GAG'));
});
it('cancels inline delete confirmation overlay when cancel is clicked', async () => {
render(
);
const deleteBtn = screen.getByTestId('cart-item-delete-btn');
fireEvent.click(deleteBtn);
expect(
screen.getByText('مطمئنی میخوای این محصول رو حذف کنی؟')
).toBeInTheDocument();
const cancelBtn = screen.getByRole('button', { name: 'لغو' });
fireEvent.click(cancelBtn);
await waitFor(() => {
expect(
screen.queryByText('مطمئنی میخوای این محصول رو حذف کنی؟')
).not.toBeInTheDocument();
});
expect(mockRemoveItem).not.toHaveBeenCalled();
});
it('handles coupon code submission successfully and shows applied coupon badge', async () => {
mockApplyCoupon.mockResolvedValue(true);
const { rerender } = render(
);
const couponInput = screen.getByPlaceholderText('CANINO2024');
fireEvent.change(couponInput, { target: { value: 'OFF20' } });
const applyBtn = screen.getByRole('button', { name: 'اعمال' });
fireEvent.click(applyBtn);
await waitFor(() => {
expect(mockApplyCoupon).toHaveBeenCalledWith('OFF20');
});
// Rerender with coupon in store
vi.mocked(useCartStore).mockReturnValue({
items: [{ product: mockProduct as any, quantity: 2 }],
updateQuantity: mockUpdateQuantity,
removeItem: mockRemoveItem,
isSubscribed: false,
toggleSubscription: mockToggleSubscription,
getTotal: () => 1600,
getSubtotal: () => 2000,
getDiscount: () => 400,
coupon: { code: 'OFF20', discount: 0.2 },
applyCoupon: mockApplyCoupon,
addItem: mockAddItem,
} as any);
rerender(
);
expect(screen.getByText(/کد OFF20/)).toBeInTheDocument();
expect(screen.getByText(/مجموع تخفیفها/)).toBeInTheDocument();
expect(screen.getByText(/-۴۰۰/)).toBeInTheDocument();
});
it('shows error state when applying invalid coupon code', async () => {
mockApplyCoupon.mockResolvedValue(false);
render(
);
const couponInput = screen.getByPlaceholderText('CANINO2024');
fireEvent.change(couponInput, { target: { value: 'INVALID' } });
const applyBtn = screen.getByRole('button', { name: 'اعمال' });
fireEvent.click(applyBtn);
await waitFor(() => {
expect(mockApplyCoupon).toHaveBeenCalledWith('INVALID');
expect(couponInput).toHaveClass('border-red-300');
});
expect(mockOnCheckout).not.toHaveBeenCalled();
expect(screen.queryByText(/حذف کد/)).not.toBeInTheDocument();
});
it('triggers checkout callback when checkout button is clicked', () => {
render(
);
const checkoutBtn = screen.getByText(/ثبت نهایی و تسویه حساب/);
fireEvent.click(checkoutBtn);
expect(mockOnCheckout).toHaveBeenCalled();
});
it('toggles subscription for logged-in user', () => {
render(
);
const subscriptionToggle = screen.getByText(/سامانه تمدید هوشمند/).closest('div[class*="cursor-pointer"]');
expect(subscriptionToggle).toBeInTheDocument();
fireEvent.click(subscriptionToggle!);
expect(mockToggleSubscription).toHaveBeenCalled();
});
it('opens auth modal if logged-out user tries to toggle refill subscription', () => {
vi.mocked(useUserStore).mockReturnValue({
isLoggedIn: false,
profile: null,
} as any);
render(
);
const subscriptionToggle = screen.getByText(/سامانه تمدید هوشمند/).closest('div[class*="cursor-pointer"]');
fireEvent.click(subscriptionToggle!);
expect(toast.info).toHaveBeenCalledWith(expect.stringContaining('وارد حساب کاربری خود شوید'));
expect(screen.getByTestId('auth-modal')).toBeInTheDocument();
expect(mockToggleSubscription).not.toHaveBeenCalled();
});
it('fetches and renders smart cross-sell product and adds to cart when clicked', async () => {
render(
);
await waitFor(() => {
expect(productService.getProducts).toHaveBeenCalledWith({ limit: 999 });
expect(screen.getByText('Lachs-Öl')).toBeInTheDocument();
});
const crossSellAddBtn = screen.getByText('Lachs-Öl').closest('div')!.parentElement!.querySelector('button')!;
fireEvent.click(crossSellAddBtn);
expect(mockAddItem).toHaveBeenCalledWith(mockSuggestedProduct, 1);
});
it('closes drawer on header close button click', () => {
render(
);
// Header close button has X icon
const closeButtons = screen.getAllByRole('button');
const headerCloseBtn = closeButtons.find(b => b.querySelector('svg.lucide-x'));
expect(headerCloseBtn).toBeDefined();
fireEvent.click(headerCloseBtn!);
expect(mockOnClose).toHaveBeenCalled();
});
it('hides prices and financial controls when catalog mode showPrices is false', () => {
vi.mocked(useCatalogMode).mockReturnValue({
isCatalogOnly: true,
showPrices: false,
allowCart: true,
allowCheckout: true,
showPreorderBtn: false,
showOrders: false,
showWallet: false,
showCharity: false,
orderDisabledTitle: '',
orderDisabledMessage: '',
});
render(
);
expect(screen.getByText('کانهیدروکس گگ')).toBeInTheDocument();
expect(screen.queryByText('کد تخفیف اختصاصی')).not.toBeInTheDocument();
expect(screen.queryByText('مجموع قابل پرداخت')).not.toBeInTheDocument();
expect(screen.getByText('تعداد کل اقلام انتخابی')).toBeInTheDocument();
expect(screen.getByText('۲ قلم کالا')).toBeInTheDocument();
});
});