feat: complete testing, security, dynamic content, and devops overhaul
This commit is contained in:
1 parent
467532713c
commit
40ff169dc2
52 files changed
+3918
-104
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import React, { useState } from "react";
|
||||
import { PRODUCTS, Product } from "../data/products";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Product } from "../data/products";
|
||||
import { useCartStore } from "../store/cartStore";
|
||||
import { productService } from "../services/productService";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
Building2,
|
||||
@@ -20,12 +21,17 @@ interface QuickOrderItem {
|
||||
}
|
||||
|
||||
export default function B2BPortal({ onClose }: { onClose: () => void }) {
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [quantities, setQuantities] = useState<Record<string, number>>({});
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { addItem } = useCartStore();
|
||||
const [showSuccess, setShowSuccess] = useState(false);
|
||||
|
||||
const filteredProducts = PRODUCTS.filter(p =>
|
||||
useEffect(() => {
|
||||
productService.getProducts().then(data => setProducts(data));
|
||||
}, []);
|
||||
|
||||
const filteredProducts = products.filter(p =>
|
||||
p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
p.artNo.includes(searchQuery)
|
||||
);
|
||||
@@ -39,7 +45,7 @@ export default function B2BPortal({ onClose }: { onClose: () => void }) {
|
||||
Object.entries(quantities).forEach(([id, qty]) => {
|
||||
const numQty = qty as number;
|
||||
if (numQty > 0) {
|
||||
const product = PRODUCTS.find(p => p.id === id);
|
||||
const product = products.find(p => p.id === id);
|
||||
if (product) {
|
||||
addItem(product, numQty);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React from "react";
|
||||
import { motion } from "motion/react";
|
||||
import { ChevronRight, Calendar, User, ArrowLeft, Sparkles, BookOpen } from "lucide-react";
|
||||
import { Product, PRODUCTS } from "../data/products";
|
||||
import { Product } from "../data/products";
|
||||
import { productService } from "../services/productService";
|
||||
|
||||
const BLOG_POSTS = [
|
||||
{
|
||||
@@ -42,6 +43,11 @@ const BLOG_POSTS = [
|
||||
|
||||
export default function BlogPage({ onBack, onProductClick }: { onBack: () => void, onProductClick: (p: Product) => void }) {
|
||||
const [selectedPost, setSelectedPost] = React.useState<typeof BLOG_POSTS[0] | null>(null);
|
||||
const [products, setProducts] = React.useState<Product[]>([]);
|
||||
|
||||
React.useEffect(() => {
|
||||
productService.getProducts().then(data => setProducts(data));
|
||||
}, []);
|
||||
|
||||
if (selectedPost) {
|
||||
return (
|
||||
@@ -113,7 +119,7 @@ export default function BlogPage({ onBack, onProductClick }: { onBack: () => voi
|
||||
</div>
|
||||
<h4 className="text-2xl font-black mb-6 italic relative z-10">محصولات پیشنهادی</h4>
|
||||
<div className="space-y-6 relative z-10">
|
||||
{PRODUCTS.slice(4, 7).map(p => (
|
||||
{products.slice(4, 7).map(p => (
|
||||
<div
|
||||
key={p.id}
|
||||
onClick={() => onProductClick(p)}
|
||||
@@ -316,7 +322,7 @@ export default function BlogPage({ onBack, onProductClick }: { onBack: () => voi
|
||||
</button>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4 flex-shrink-0">
|
||||
{PRODUCTS.slice(0, 2).map((p) => (
|
||||
{products.slice(0, 2).map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
onClick={() => onProductClick(p)}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { X, Trash2, Plus, Minus, ShoppingBag, ShieldCheck, ArrowLeft, Ticket, Sparkles, CheckCircle2 } from "lucide-react";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import { toPersian, cn } from "../lib/utils";
|
||||
import { useCartStore } from "../store/cartStore";
|
||||
import { PRODUCTS } from "../data/products";
|
||||
import { Product } from "../data/products";
|
||||
import { productService } from "../services/productService";
|
||||
import SafeImage from "./SafeImage";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -32,10 +33,18 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
|
||||
// Smart Cross-sell Logic
|
||||
const hasCanhydrox = items.some(i => i.product.id === 'canhydrox-gag');
|
||||
const hasLachsOl = items.some(i => i.product.id === 'lachs-ol');
|
||||
|
||||
const suggestedProduct = (!hasLachsOl && hasCanhydrox)
|
||||
? PRODUCTS.find(p => p.id === 'lachs-ol')
|
||||
: null;
|
||||
const [suggestedProduct, setSuggestedProduct] = useState<Product | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasLachsOl && hasCanhydrox) {
|
||||
productService.getProducts().then(prods => {
|
||||
const found = prods.find(p => p.id === 'lachs-ol' || p.artNo === 'lachs-ol');
|
||||
setSuggestedProduct(found || null);
|
||||
});
|
||||
} else {
|
||||
setSuggestedProduct(null);
|
||||
}
|
||||
}, [hasLachsOl, hasCanhydrox]);
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
@@ -103,6 +112,7 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
|
||||
<button
|
||||
onClick={() => updateQuantity(item.product.id, item.quantity - 1)}
|
||||
className="p-1 hover:text-canina-blue transition-colors"
|
||||
data-testid="minus-btn"
|
||||
>
|
||||
<Minus className="w-3 h-3" />
|
||||
</button>
|
||||
@@ -110,6 +120,7 @@ export default function CartDrawer({ isOpen, onClose, onCheckout, onShopNavigate
|
||||
<button
|
||||
onClick={() => updateQuantity(item.product.id, item.quantity + 1)}
|
||||
className="p-1 hover:text-canina-blue transition-colors"
|
||||
data-testid="plus-btn"
|
||||
>
|
||||
<Plus className="w-3 h-3" />
|
||||
</button>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
ChevronRight,
|
||||
@@ -19,7 +19,8 @@ import { toPersian, cn } from "../lib/utils";
|
||||
import { useCartStore } from "../store/cartStore";
|
||||
import { usePetStore } from "../store/usePetStore";
|
||||
import { useUserStore } from "../store/userStore";
|
||||
import { PRODUCTS } from "../data/products";
|
||||
import { Product } from "../data/products";
|
||||
import { productService } from "../services/productService";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function CheckoutPage({ onBack, onComplete }: { onBack: () => void; onComplete: (orderId: string) => void }) {
|
||||
@@ -29,6 +30,11 @@ export default function CheckoutPage({ onBack, onComplete }: { onBack: () => voi
|
||||
const [step, setStep] = useState(1);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [useRoundUp, setUseRoundUp] = useState(false);
|
||||
const [dbProducts, setDbProducts] = useState<Product[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
productService.getProducts().then(data => setDbProducts(data));
|
||||
}, []);
|
||||
|
||||
const subtotal = getSubtotal();
|
||||
const roundedAmount = Math.ceil(subtotal / 10000) * 10000;
|
||||
@@ -329,7 +335,7 @@ export default function CheckoutPage({ onBack, onComplete }: { onBack: () => voi
|
||||
{items.map(item => {
|
||||
const activePet = usePetStore.getState().getActivePet();
|
||||
// Re-hydrate product to ensure methods like calculateDosage exist
|
||||
const fullProduct = PRODUCTS.find(p => p.id === item.product.id) || item.product;
|
||||
const fullProduct = dbProducts.find(p => p.id === item.product.id) || item.product;
|
||||
const dose = activePet ? fullProduct.calculateDosage(activePet.weight, activePet.age <= 1) : { quantity: 1 };
|
||||
const days = Math.floor(fullProduct.packageSize / (dose.quantity || 1));
|
||||
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { useMemo } from "react";
|
||||
import { INGREDIENTS_WIKI, PRODUCTS, Product } from "../data/products";
|
||||
import { useMemo, useState, useEffect } from "react";
|
||||
import { INGREDIENTS_WIKI, Product } from "../data/products";
|
||||
import { motion } from "motion/react";
|
||||
import { FlaskConical, CheckCircle2, ChevronRight, ChevronLeft, Beaker } from "lucide-react";
|
||||
import { useSettingsStore } from "../store/settingsStore";
|
||||
import { productService } from "../services/productService";
|
||||
|
||||
export default function IngredientWiki({ onProductClick, onBack }: { onProductClick: (p: Product) => void, onBack?: () => void }) {
|
||||
const texts = useSettingsStore(state => state.texts);
|
||||
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
productService.getProducts().then(data => setProducts(data));
|
||||
}, []);
|
||||
|
||||
const ingredientsWiki = useMemo(() => {
|
||||
const jsonStr = texts['ingredients_wiki'];
|
||||
if (jsonStr) {
|
||||
@@ -62,9 +68,9 @@ export default function IngredientWiki({ onProductClick, onBack }: { onProductCl
|
||||
|
||||
<div className="space-y-32">
|
||||
{ingredientsWiki.map((ing, idx) => {
|
||||
const hasIngredient = PRODUCTS.filter(p =>
|
||||
p.main_ingredients.some(mi => mi.toLowerCase().includes(ing.name.toLowerCase())) ||
|
||||
p.main_ingredients.some(mi => mi.toLowerCase().includes(ing.id.replace('-', ' ')))
|
||||
const hasIngredient = products.filter(p =>
|
||||
p.main_ingredients?.some(mi => mi.toLowerCase().includes(ing.name.toLowerCase())) ||
|
||||
p.main_ingredients?.some(mi => mi.toLowerCase().includes(ing.id.replace('-', ' ')))
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useState, useMemo, useEffect } from "react";
|
||||
import { PRODUCTS, Product, PetType } from "../data/products";
|
||||
import { Product, PetType } from "../data/products";
|
||||
import { productService } from "../services/productService";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import { PetProfileSkeleton } from "./Skeleton";
|
||||
import {
|
||||
@@ -43,6 +44,13 @@ export default function PetProfile({ onProductClick, onBack, initialView, adviso
|
||||
const { orders } = useCartStore();
|
||||
const activePet = getActivePet();
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
productService.getProducts()
|
||||
.then(setProducts)
|
||||
.catch(err => console.error("Error fetching products in PetProfile:", err));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setIsLoading(false), 800);
|
||||
@@ -151,50 +159,50 @@ export default function PetProfile({ onProductClick, onBack, initialView, adviso
|
||||
};
|
||||
|
||||
const recommendedProducts = useMemo(() => {
|
||||
if (!activePet) return [];
|
||||
if (!activePet || products.length === 0) return [];
|
||||
|
||||
let picks: { product: Product, reason?: string }[] = [];
|
||||
|
||||
// Priority: Medical Conditions
|
||||
if (activePet.medicalConditions.includes("جراحی مفاصل")) {
|
||||
const gag = PRODUCTS.find(p => p.id === "canhydrox-gag");
|
||||
const gag = products.find(p => p.id === "canhydrox-gag");
|
||||
if (gag) picks.push({ product: gag, reason: "پیشنهاد ویژه بر اساس سوابق جراحی مفاصل" });
|
||||
}
|
||||
|
||||
if (activePet.medicalConditions.includes("زایمان اخیر") || activePet.medicalConditions.includes("بارداری")) {
|
||||
const booster = PRODUCTS.find(p => p.id === "immun-booster");
|
||||
const booster = products.find(p => p.id === "immun-booster");
|
||||
if (booster) picks.push({ product: booster, reason: "حمایت حیاتی دوران بارداری و زایمان" });
|
||||
}
|
||||
|
||||
if (activePet.medicalConditions.includes("مشکلات گوارشی")) {
|
||||
const moor = PRODUCTS.find(p => p.id === "moor-tranke");
|
||||
const moor = products.find(p => p.id === "moor-tranke");
|
||||
if (moor) picks.push({ product: moor, reason: "تنظیم تخصصی سیستم گوارش" });
|
||||
}
|
||||
|
||||
if (activePet.medicalConditions.includes("ریزش موی شدید")) {
|
||||
const lachs = PRODUCTS.find(p => p.id === "lachs-ol");
|
||||
const lachs = products.find(p => p.id === "lachs-ol");
|
||||
if (lachs) picks.push({ product: lachs, reason: "تقویت تارهای مو و کنترل ریزش" });
|
||||
}
|
||||
|
||||
if (activePet.medicalConditions.includes("بیاشتهایی")) {
|
||||
const energy = PRODUCTS.find(p => p.id === "energy-gel");
|
||||
const energy = products.find(p => p.id === "energy-gel");
|
||||
if (energy) picks.push({ product: energy, reason: "تامین فوری انرژی و تحریک اشتها" });
|
||||
}
|
||||
|
||||
// Biological factors
|
||||
if (activePet.age > 7) {
|
||||
const heart = PRODUCTS.find(p => p.id === "herz-vital");
|
||||
const heart = products.find(p => p.id === "herz-vital");
|
||||
if (heart && !picks.some(x => x.product.id === heart.id)) picks.push({ product: heart, reason: "محافظت از قلب پتهای مسن" });
|
||||
}
|
||||
|
||||
// Fill defaults if needed
|
||||
if (picks.length < 4) {
|
||||
const defaults = PRODUCTS.filter(p => !picks.some(x => x.product.id === p.id) && (p.suitableFor === activePet.type || p.suitableFor === "هر دو"));
|
||||
const defaults = products.filter(p => !picks.some(x => x.product.id === p.id) && (p.suitableFor === activePet.type || p.suitableFor === "هر دو"));
|
||||
defaults.slice(0, 4 - picks.length).forEach(p => picks.push({ product: p }));
|
||||
}
|
||||
|
||||
return picks;
|
||||
}, [activePet]);
|
||||
}, [activePet, products]);
|
||||
|
||||
const handleNext = () => setStep(s => s + 1);
|
||||
const handleBackStep = () => setStep(s => s - 1);
|
||||
@@ -716,7 +724,7 @@ export default function PetProfile({ onProductClick, onBack, initialView, adviso
|
||||
</div>
|
||||
) : (
|
||||
activePet.consumptions.map((consumption) => {
|
||||
const product = PRODUCTS.find(p => p.id === consumption.productId);
|
||||
const product = products.find(p => p.id === consumption.productId);
|
||||
if (!product) return null;
|
||||
|
||||
const percentage = (consumption.remaining / (consumption.packageSize || 1)) * 100;
|
||||
|
||||
@@ -40,7 +40,8 @@ const ICON_MAP: Record<string, any> = {
|
||||
Users
|
||||
};
|
||||
import { toPersian, cn } from "../lib/utils";
|
||||
import { Product, PRODUCTS } from "../data/products";
|
||||
import { Product } from "../data/products";
|
||||
import { productService } from "../services/productService";
|
||||
import { SCIENTIFIC_TERMS } from "../data/scientificTerms";
|
||||
import { useSettingsStore } from "../store/settingsStore";
|
||||
import { create } from "zustand";
|
||||
@@ -75,6 +76,13 @@ export default function ProductPage({ product, onBack, onProductClick, onWikiNav
|
||||
const [activeTab, setActiveTab] = useState<"specs" | "feeding" | "notes">("specs");
|
||||
const [showRefillModal, setShowRefillModal] = useState(false);
|
||||
const [itemQuantity, setItemQuantity] = useState(1);
|
||||
const [allProducts, setAllProducts] = useState<Product[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
productService.getProducts()
|
||||
.then(setAllProducts)
|
||||
.catch(err => console.error("Error fetching products in ProductPage:", err));
|
||||
}, []);
|
||||
const { pets, getActivePet } = usePetStore();
|
||||
const activePet = getActivePet();
|
||||
const { petType, weight, setPetType, setWeight } = useCalculatorStore();
|
||||
@@ -89,8 +97,8 @@ export default function ProductPage({ product, onBack, onProductClick, onWikiNav
|
||||
|
||||
// Re-hydrate product to ensure methods like calculateDosage exist
|
||||
const fullProduct = useMemo(() => {
|
||||
return PRODUCTS.find(p => p.id === product.id) || product;
|
||||
}, [product]);
|
||||
return allProducts.find(p => p.id === product.id) || product;
|
||||
}, [product, allProducts]);
|
||||
|
||||
const syncActivePet = useMemo(() => {
|
||||
if (activePet) {
|
||||
@@ -490,7 +498,7 @@ export default function ProductPage({ product, onBack, onProductClick, onWikiNav
|
||||
|
||||
<div className="grid lg:grid-cols-2 gap-8">
|
||||
{product.relatedProducts.map(relId => {
|
||||
const relProduct = PRODUCTS.find(p => p.id === relId);
|
||||
const relProduct = allProducts.find(p => p.id === relId);
|
||||
if (!relProduct) return null;
|
||||
return (
|
||||
<motion.div
|
||||
|
||||
@@ -1,21 +1,29 @@
|
||||
import React, { useMemo } from "react";
|
||||
import React, { useMemo, useState, useEffect } from "react";
|
||||
import { Search, ShoppingBag, ChevronLeft, ArrowRight, Activity, Sparkles, HeartPulse, Stethoscope, ShieldCheck, Heart, AlertCircle } from "lucide-react";
|
||||
import { usePetStore } from "../store/usePetStore";
|
||||
import { motion } from "motion/react";
|
||||
import { Product, PRODUCTS } from "../data/products";
|
||||
import { Product } from "../data/products";
|
||||
import { productService } from "../services/productService";
|
||||
|
||||
export default function SearchResultsPage({ query, onProductClick, onBack }: { query: string; onProductClick: (p: Product) => void; onBack: () => void }) {
|
||||
const { getActivePet } = usePetStore();
|
||||
const activePet = getActivePet();
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
|
||||
const results = PRODUCTS.filter(p =>
|
||||
useEffect(() => {
|
||||
productService.getProducts()
|
||||
.then(setProducts)
|
||||
.catch(err => console.error("Error fetching products in SearchResultsPage:", err));
|
||||
}, []);
|
||||
|
||||
const results = products.filter(p =>
|
||||
p.name.toLowerCase().includes(query.toLowerCase()) ||
|
||||
p.description.toLowerCase().includes(query.toLowerCase()) ||
|
||||
p.main_ingredients.some(ing => ing.toLowerCase().includes(query.toLowerCase())) ||
|
||||
p.symptoms.some(sym => sym.toLowerCase().includes(query.toLowerCase()))
|
||||
);
|
||||
|
||||
const bestSellers = PRODUCTS.slice(0, 3);
|
||||
const bestSellers = products.slice(0, 3);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-medical-gray-50 py-20 px-6 font-vazir" dir="rtl">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useState } from "react";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import { ChevronRight, PlayCircle, Star, ShieldCheck, X, Search, Clock, User } from "lucide-react";
|
||||
import { Product, PRODUCTS } from "../data/products";
|
||||
|
||||
|
||||
const ALL_VIDEOS = [
|
||||
{
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
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(<CartDrawer isOpen={true} onClose={vi.fn()} onCheckout={vi.fn()} />);
|
||||
|
||||
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(<CartDrawer isOpen={true} onClose={vi.fn()} onCheckout={vi.fn()} />);
|
||||
|
||||
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(<CartDrawer isOpen={true} onClose={vi.fn()} onCheckout={vi.fn()} />);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import FeaturedProducts from '../FeaturedProducts';
|
||||
import { productService } from '../../services/productService';
|
||||
import { usePetStore } from '../../store/usePetStore';
|
||||
|
||||
vi.mock('../../services/productService', () => ({
|
||||
productService: {
|
||||
getFeaturedProducts: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../store/usePetStore', () => ({
|
||||
usePetStore: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockProducts = [
|
||||
{
|
||||
id: 'prod-1',
|
||||
name: 'Canhydrox GAG',
|
||||
description: 'Joint helper',
|
||||
price: '۱,۰۰۰ تومان',
|
||||
priceValue: 1000,
|
||||
category: 'joints',
|
||||
image: '',
|
||||
suitableFor: 'سگ',
|
||||
symptoms: ['joint_pain'],
|
||||
benefits: 'Strengthens joints',
|
||||
calculateDosage: vi.fn(),
|
||||
},
|
||||
];
|
||||
|
||||
describe('FeaturedProducts', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(usePetStore).mockReturnValue({
|
||||
getActivePet: () => null,
|
||||
} as any);
|
||||
});
|
||||
|
||||
it('renders loading skeletons initially', () => {
|
||||
vi.mocked(productService.getFeaturedProducts).mockReturnValue(new Promise(() => {}));
|
||||
const { container } = render(<FeaturedProducts onProductClick={vi.fn()} onShopNavigate={vi.fn()} />);
|
||||
// Check if skeletons are present (e.g. searching for animate-pulse)
|
||||
expect(container.getElementsByClassName('animate-pulse').length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('renders products once loaded', async () => {
|
||||
vi.mocked(productService.getFeaturedProducts).mockResolvedValue(mockProducts as any);
|
||||
render(<FeaturedProducts onProductClick={vi.fn()} onShopNavigate={vi.fn()} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Canhydrox GAG')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText('Joint helper')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onProductClick when product card is clicked', async () => {
|
||||
const handleProductClick = vi.fn();
|
||||
vi.mocked(productService.getFeaturedProducts).mockResolvedValue(mockProducts as any);
|
||||
render(<FeaturedProducts onProductClick={handleProductClick} onShopNavigate={vi.fn()} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Canhydrox GAG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Canhydrox GAG'));
|
||||
expect(handleProductClick).toHaveBeenCalledWith(mockProducts[0]);
|
||||
});
|
||||
|
||||
it('calls onShopNavigate when navigation link is clicked', async () => {
|
||||
const handleShopNavigate = vi.fn();
|
||||
vi.mocked(productService.getFeaturedProducts).mockResolvedValue(mockProducts as any);
|
||||
render(<FeaturedProducts onProductClick={vi.fn()} onShopNavigate={handleShopNavigate} />);
|
||||
|
||||
const navBtn = screen.getByText('مشاهده تمامی محصولات');
|
||||
fireEvent.click(navBtn);
|
||||
expect(handleShopNavigate).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import Footer from '../Footer';
|
||||
|
||||
describe('Footer', () => {
|
||||
it('renders footer brand text and standard layout elements', () => {
|
||||
render(<Footer onNavigate={vi.fn()} onShopNavigate={vi.fn()} onB2BOpen={vi.fn()} />);
|
||||
|
||||
expect(screen.getByText('کانینا ایران')).toBeInTheDocument();
|
||||
expect(screen.getByText('نماینده رسمی در ایران')).toBeInTheDocument();
|
||||
expect(screen.getByText('تهران، جردن، خیابان سعیدی، ساختمان کانینا، طبقه ۵، واحد ۱۹')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('triggers onNavigate and onShopNavigate when quick links are clicked', () => {
|
||||
const handleNavigate = vi.fn();
|
||||
const handleShopNavigate = vi.fn();
|
||||
const handleB2BOpen = vi.fn();
|
||||
|
||||
render(
|
||||
<Footer
|
||||
onNavigate={handleNavigate}
|
||||
onShopNavigate={handleShopNavigate}
|
||||
onB2BOpen={handleB2BOpen}
|
||||
/>
|
||||
);
|
||||
|
||||
// Click quick link for shop
|
||||
const shopLink = screen.getByText('محصولات تخصصی ۲۰۲۴');
|
||||
fireEvent.click(shopLink);
|
||||
expect(handleShopNavigate).toHaveBeenCalled();
|
||||
|
||||
// Click quick link for blog
|
||||
const blogLink = screen.getByText('مجله سلامت پت (وبلاگ)');
|
||||
fireEvent.click(blogLink);
|
||||
expect(handleNavigate).toHaveBeenCalledWith('blog');
|
||||
|
||||
// Click B2B link
|
||||
const b2bLink = screen.getByText('پنل سفارش عمده (B2B)');
|
||||
fireEvent.click(b2bLink);
|
||||
expect(handleB2BOpen).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import Header from '../Header';
|
||||
import { useCartStore } from '../../store/cartStore';
|
||||
import { usePetStore } from '../../store/usePetStore';
|
||||
import { useUserStore } from '../../store/userStore';
|
||||
|
||||
vi.mock('../../store/cartStore', () => ({
|
||||
useCartStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../store/usePetStore', () => ({
|
||||
usePetStore: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../store/userStore', () => ({
|
||||
useUserStore: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Header', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
vi.mocked(useCartStore).mockReturnValue({
|
||||
getTotalItems: () => 3,
|
||||
} as any);
|
||||
|
||||
vi.mocked(usePetStore).mockReturnValue({
|
||||
pets: [],
|
||||
activePetId: null,
|
||||
setActivePet: vi.fn(),
|
||||
getActivePet: () => null,
|
||||
} as any);
|
||||
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
role: 'User_Guest',
|
||||
isLoggedIn: false,
|
||||
logout: vi.fn(),
|
||||
profile: { firstName: '' },
|
||||
} as any);
|
||||
});
|
||||
|
||||
it('renders brand name and login button when guest', () => {
|
||||
render(
|
||||
<Header
|
||||
onNavigate={vi.fn()}
|
||||
onShopNavigate={vi.fn()}
|
||||
currentView="home"
|
||||
onCartOpen={vi.fn()}
|
||||
onSearch={vi.fn()}
|
||||
onB2BOpen={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Canina')).toBeInTheDocument();
|
||||
expect(screen.getByText('ایران')).toBeInTheDocument();
|
||||
expect(screen.getByText('ورود / ثبتنام')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders user first name and pet selection when logged in', () => {
|
||||
vi.mocked(useUserStore).mockReturnValue({
|
||||
role: 'User_PetOwner',
|
||||
isLoggedIn: true,
|
||||
logout: vi.fn(),
|
||||
profile: { firstName: 'کوروش' },
|
||||
} as any);
|
||||
|
||||
vi.mocked(usePetStore).mockReturnValue({
|
||||
pets: [{ id: 'pet-1', name: 'ملوس', type: 'گربه' }],
|
||||
activePetId: 'pet-1',
|
||||
setActivePet: vi.fn(),
|
||||
getActivePet: () => ({ id: 'pet-1', name: 'ملوس', type: 'گربه' }),
|
||||
} as any);
|
||||
|
||||
render(
|
||||
<Header
|
||||
onNavigate={vi.fn()}
|
||||
onShopNavigate={vi.fn()}
|
||||
currentView="home"
|
||||
onCartOpen={vi.fn()}
|
||||
onSearch={vi.fn()}
|
||||
onB2BOpen={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.queryByText('ورود / ثبتنام')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('کوروش')).toBeInTheDocument();
|
||||
expect(screen.getByText('ملوس')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onCartOpen when click on cart button', () => {
|
||||
const handleCartOpen = vi.fn();
|
||||
render(
|
||||
<Header
|
||||
onNavigate={vi.fn()}
|
||||
onShopNavigate={vi.fn()}
|
||||
currentView="home"
|
||||
onCartOpen={handleCartOpen}
|
||||
onSearch={vi.fn()}
|
||||
onB2BOpen={vi.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
const cartBtn = screen.getByText('سبد خرید').closest('button');
|
||||
expect(cartBtn).toBeInTheDocument();
|
||||
fireEvent.click(cartBtn!);
|
||||
expect(handleCartOpen).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import Hero from '../Hero';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
|
||||
vi.mock('../../store/settingsStore', () => ({
|
||||
useSettingsStore: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Hero', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders title and description from settingsStore', () => {
|
||||
const mockGetText = vi.fn().mockImplementation((key, fallback) => {
|
||||
if (key === 'hero_title') return 'Test Title Line 1\nTest Title Line 2';
|
||||
if (key === 'hero_desc') return 'Test Description Text';
|
||||
return fallback;
|
||||
});
|
||||
|
||||
vi.mocked(useSettingsStore).mockImplementation((selector: any) => selector({ getText: mockGetText }));
|
||||
|
||||
render(<Hero onShopNavigate={vi.fn()} />);
|
||||
|
||||
expect(screen.getByText('Test Title Line 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Test Title Line 2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Test Description Text')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onShopNavigate when "مشاهده محصولات" button is clicked', () => {
|
||||
const mockGetText = vi.fn().mockImplementation((key, fallback) => fallback);
|
||||
vi.mocked(useSettingsStore).mockImplementation((selector: any) => selector({ getText: mockGetText }));
|
||||
|
||||
const handleShopNavigate = vi.fn();
|
||||
render(<Hero onShopNavigate={handleShopNavigate} />);
|
||||
|
||||
const shopBtn = screen.getByText('مشاهده محصولات');
|
||||
fireEvent.click(shopBtn);
|
||||
expect(handleShopNavigate).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import Tooltip from '../Tooltip';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
|
||||
vi.mock('../../store/settingsStore', () => ({
|
||||
useSettingsStore: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Tooltip', () => {
|
||||
it('should render children correctly', () => {
|
||||
vi.mocked(useSettingsStore).mockReturnValue({});
|
||||
|
||||
render(
|
||||
<Tooltip termKey="mussel">
|
||||
<span>Mussel Term</span>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Mussel Term')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display tooltip definition on hover', async () => {
|
||||
const mockTerms = {
|
||||
mussel: {
|
||||
key: 'mussel',
|
||||
term: 'Green Mussel',
|
||||
definition: 'Scientific definition of NZ green mussel',
|
||||
wikiId: 'green-mussel',
|
||||
},
|
||||
};
|
||||
vi.mocked(useSettingsStore).mockReturnValue(mockTerms);
|
||||
|
||||
render(
|
||||
<Tooltip termKey="mussel">
|
||||
<span>Hover Me</span>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
const trigger = screen.getByText('Hover Me');
|
||||
fireEvent.mouseEnter(trigger);
|
||||
|
||||
expect(screen.getByText('Green Mussel')).toBeInTheDocument();
|
||||
expect(screen.getByText('Scientific definition of NZ green mussel')).toBeInTheDocument();
|
||||
|
||||
fireEvent.mouseLeave(trigger);
|
||||
// Tooltip should exit (though animations might delay actual removal, under standard RTL fireEvent it updates state immediately)
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user