"use client";
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import React from 'react';
import CartDrawer from '../CartDrawer';
import { useCartStore } from '../../store/cartStore';
import { productService } from '../../services/productService';
vi.mock('../../store/cartStore', () => ({
useCartStore: vi.fn(),
}));
vi.mock('../../services/productService', () => ({
productService: {
getProducts: vi.fn(),
},
}));
const mockProduct = {
id: 'canhydrox-gag',
name: 'Canhydrox GAG',
price: '۱,۰۰۰ تومان',
priceValue: 1000,
category: 'joints',
image: '',
};
describe('CartDrawer', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(productService.getProducts).mockResolvedValue([]);
});
it('renders empty cart state when no items in cart', () => {
vi.mocked(useCartStore).mockReturnValue({
items: [],
updateQuantity: vi.fn(),
removeItem: vi.fn(),
isSubscribed: false,
toggleSubscription: vi.fn(),
getTotal: () => 0,
getSubtotal: () => 0,
getDiscount: () => 0,
coupon: null,
applyCoupon: vi.fn(),
addItem: vi.fn(),
} as any);
render();
expect(screen.getByText('سبد خرید شما خالی است')).toBeInTheDocument();
});
it('renders cart items and total when items are present', () => {
vi.mocked(useCartStore).mockReturnValue({
items: [{ product: mockProduct, quantity: 2 }],
updateQuantity: vi.fn(),
removeItem: vi.fn(),
isSubscribed: false,
toggleSubscription: vi.fn(),
getTotal: () => 2000,
getSubtotal: () => 2000,
getDiscount: () => 0,
coupon: null,
applyCoupon: vi.fn(),
addItem: vi.fn(),
} as any);
render();
expect(screen.getByText('Canhydrox GAG')).toBeInTheDocument();
expect(screen.getAllByText('۲,۰۰۰').length).toBeGreaterThanOrEqual(1);
});
it('triggers updateQuantity when plus/minus buttons are clicked', () => {
const mockUpdateQuantity = vi.fn();
vi.mocked(useCartStore).mockReturnValue({
items: [{ product: mockProduct, quantity: 2 }],
updateQuantity: mockUpdateQuantity,
removeItem: vi.fn(),
isSubscribed: false,
toggleSubscription: vi.fn(),
getTotal: () => 2000,
getSubtotal: () => 2000,
getDiscount: () => 0,
coupon: null,
applyCoupon: vi.fn(),
addItem: vi.fn(),
} as any);
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);
});
});