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)
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { useCartStore } from '../cartStore';
|
||||
import { orderService } from '../../services/orderService';
|
||||
|
||||
vi.mock('../../services/orderService', () => ({
|
||||
orderService: {
|
||||
createOrder: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockProduct = {
|
||||
id: 'prod-1',
|
||||
artNo: 'art-1',
|
||||
name: 'Canhydrox GAG',
|
||||
scientificTagline: 'Joint helper',
|
||||
description: 'Joints',
|
||||
price: '۱,۰۰۰ تومان',
|
||||
priceValue: 1000,
|
||||
category: 'joints',
|
||||
unit: 'tablet',
|
||||
packageSize: 100,
|
||||
main_ingredients: [],
|
||||
dosage_logic: '1',
|
||||
benefits: '',
|
||||
symptoms: [],
|
||||
suitableFor: 'سگ' as any,
|
||||
calculateDosage: () => ({ quantity: 1, unit: 'tablet', description: '' }),
|
||||
analysis: {},
|
||||
feedingAdvice: '',
|
||||
specialist: null as any,
|
||||
image: '',
|
||||
};
|
||||
|
||||
describe('cartStore', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useCartStore.setState({
|
||||
items: [],
|
||||
isSubscribed: false,
|
||||
charityDonation: 0,
|
||||
coupon: null,
|
||||
orders: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should add item to cart', () => {
|
||||
const store = useCartStore.getState();
|
||||
store.addItem(mockProduct, 2);
|
||||
|
||||
const state = useCartStore.getState();
|
||||
expect(state.items).toHaveLength(1);
|
||||
expect(state.items[0].product.id).toBe('prod-1');
|
||||
expect(state.items[0].quantity).toBe(2);
|
||||
});
|
||||
|
||||
it('should increment quantity if item already in cart', () => {
|
||||
const store = useCartStore.getState();
|
||||
store.addItem(mockProduct, 2);
|
||||
store.addItem(mockProduct, 3);
|
||||
|
||||
const state = useCartStore.getState();
|
||||
expect(state.items).toHaveLength(1);
|
||||
expect(state.items[0].quantity).toBe(5);
|
||||
});
|
||||
|
||||
it('should remove item from cart', () => {
|
||||
const store = useCartStore.getState();
|
||||
store.addItem(mockProduct, 2);
|
||||
store.removeItem('prod-1');
|
||||
|
||||
const state = useCartStore.getState();
|
||||
expect(state.items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should update quantity', () => {
|
||||
const store = useCartStore.getState();
|
||||
store.addItem(mockProduct, 2);
|
||||
store.updateQuantity('prod-1', 4);
|
||||
|
||||
const state = useCartStore.getState();
|
||||
expect(state.items[0].quantity).toBe(4);
|
||||
});
|
||||
|
||||
it('should remove item if update quantity is <= 0', () => {
|
||||
const store = useCartStore.getState();
|
||||
store.addItem(mockProduct, 2);
|
||||
store.updateQuantity('prod-1', 0);
|
||||
|
||||
const state = useCartStore.getState();
|
||||
expect(state.items).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should apply discount coupon', () => {
|
||||
const store = useCartStore.getState();
|
||||
const success = store.applyCoupon('CANINA2024');
|
||||
expect(success).toBe(true);
|
||||
|
||||
const state = useCartStore.getState();
|
||||
expect(state.coupon).toEqual({ code: 'CANINA2024', discount: 0.1 });
|
||||
});
|
||||
|
||||
it('should calculate subtotal, discount and total', () => {
|
||||
const store = useCartStore.getState();
|
||||
store.addItem(mockProduct, 2); // 2 * 1000 = 2000
|
||||
store.applyCoupon('CANINA2024'); // 10% discount
|
||||
|
||||
expect(useCartStore.getState().getSubtotal()).toBe(2000);
|
||||
expect(useCartStore.getState().getDiscount()).toBe(200);
|
||||
expect(useCartStore.getState().getTotal()).toBe(1800);
|
||||
});
|
||||
|
||||
it('should create order successfully via orderService', async () => {
|
||||
const mockBackendOrder = {
|
||||
id: 'backend-order-id',
|
||||
createdAt: '2026-05-26T18:00:00.000Z',
|
||||
totalAmount: '2000.00',
|
||||
charityDonation: '0.00',
|
||||
status: 'processing',
|
||||
trackingNumber: 'TRK-12345',
|
||||
};
|
||||
|
||||
vi.mocked(orderService.createOrder).mockResolvedValue(mockBackendOrder);
|
||||
|
||||
const store = useCartStore.getState();
|
||||
store.addItem(mockProduct, 2);
|
||||
|
||||
const orderId = await store.addOrder({
|
||||
items: store.items,
|
||||
total: 2000,
|
||||
charityDonation: 0,
|
||||
petId: 'pet-id',
|
||||
});
|
||||
|
||||
expect(orderService.createOrder).toHaveBeenCalled();
|
||||
expect(orderId).toBe('backend-order-id');
|
||||
|
||||
const state = useCartStore.getState();
|
||||
expect(state.orders).toHaveLength(1);
|
||||
expect(state.orders[0].id).toBe('backend-order-id');
|
||||
expect(state.orders[0].total).toBe(2000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { useSettingsStore } from '../settingsStore';
|
||||
import api from '../../services/api';
|
||||
|
||||
vi.mock('../../services/api', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('settingsStore', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useSettingsStore.setState({
|
||||
texts: {},
|
||||
scientificTerms: {},
|
||||
isLoading: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return fallback if key is not found', () => {
|
||||
const text = useSettingsStore.getState().getText('non-existent', 'Fallback Text');
|
||||
expect(text).toBe('Fallback Text');
|
||||
});
|
||||
|
||||
it('should return value if key is found', () => {
|
||||
useSettingsStore.setState({
|
||||
texts: { 'test-key': 'Real Value' },
|
||||
});
|
||||
const text = useSettingsStore.getState().getText('test-key', 'Fallback Text');
|
||||
expect(text).toBe('Real Value');
|
||||
});
|
||||
|
||||
it('should fetch settings successfully and map array to object', async () => {
|
||||
const mockUiTexts = [
|
||||
{ key: 'hero_title', value: 'Welcome to Canina' },
|
||||
{ key: 'hero_desc', value: 'Best supplements' },
|
||||
];
|
||||
const mockTerms = [
|
||||
{ key: 'mussel', term: 'Mussel', definition: 'NZ Green Mussel', wikiId: 'general' },
|
||||
];
|
||||
|
||||
vi.mocked(api.get).mockImplementation((url: string) => {
|
||||
if (url === '/settings/ui-texts') {
|
||||
return Promise.resolve({ data: mockUiTexts });
|
||||
}
|
||||
if (url === '/settings/scientific-terms') {
|
||||
return Promise.resolve({ data: mockTerms });
|
||||
}
|
||||
return Promise.reject(new Error('Unknown URL'));
|
||||
});
|
||||
|
||||
const store = useSettingsStore.getState();
|
||||
await store.fetchSettings();
|
||||
|
||||
const state = useSettingsStore.getState();
|
||||
expect(state.texts['hero_title']).toBe('Welcome to Canina');
|
||||
expect(state.texts['hero_desc']).toBe('Best supplements');
|
||||
expect(state.scientificTerms['mussel']).toEqual(mockTerms[0]);
|
||||
expect(state.isLoading).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { useUserStore } from '../userStore';
|
||||
import { authService } from '../../services/authService';
|
||||
import api from '../../services/api';
|
||||
|
||||
vi.mock('../../services/authService', () => ({
|
||||
authService: {
|
||||
updateProfile: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
getProfile: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../services/api', () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('userStore', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useUserStore.setState({
|
||||
role: 'User_Guest',
|
||||
isLoggedIn: false,
|
||||
profile: {
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
mobile: '',
|
||||
walletBalance: 0,
|
||||
charityDonationTotal: 0,
|
||||
addresses: [],
|
||||
transactions: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should logout correctly', () => {
|
||||
useUserStore.setState({
|
||||
role: 'User_PetOwner',
|
||||
isLoggedIn: true,
|
||||
profile: {
|
||||
firstName: 'Ali',
|
||||
lastName: 'Ahmadi',
|
||||
email: 'ali@example.com',
|
||||
mobile: '0912',
|
||||
walletBalance: 100,
|
||||
charityDonationTotal: 10,
|
||||
addresses: [],
|
||||
transactions: [],
|
||||
},
|
||||
});
|
||||
|
||||
useUserStore.getState().logout();
|
||||
|
||||
expect(authService.logout).toHaveBeenCalled();
|
||||
const state = useUserStore.getState();
|
||||
expect(state.isLoggedIn).toBe(false);
|
||||
expect(state.role).toBe('User_Guest');
|
||||
expect(state.profile.firstName).toBe('');
|
||||
});
|
||||
|
||||
it('should fetch profile successfully', async () => {
|
||||
const mockProfileData = {
|
||||
firstName: 'Ali',
|
||||
lastName: 'Ahmadi',
|
||||
email: 'ali@example.com',
|
||||
mobile: '09123456789',
|
||||
role: 'User_PetOwner',
|
||||
walletBalance: '1500.00',
|
||||
charityDonationTotal: '50.00',
|
||||
addresses: [],
|
||||
pets: [],
|
||||
walletTransactions: [],
|
||||
};
|
||||
|
||||
vi.mocked(authService.getProfile).mockResolvedValue(mockProfileData);
|
||||
|
||||
const store = useUserStore.getState();
|
||||
await store.fetchProfile();
|
||||
|
||||
expect(authService.getProfile).toHaveBeenCalled();
|
||||
const state = useUserStore.getState();
|
||||
expect(state.isLoggedIn).toBe(true);
|
||||
expect(state.role).toBe('User_PetOwner');
|
||||
expect(state.profile.firstName).toBe('Ali');
|
||||
expect(state.profile.walletBalance).toBe(1500);
|
||||
});
|
||||
|
||||
it('should update profile correctly', async () => {
|
||||
const mockUpdatedData = {
|
||||
firstName: 'Ali Updated',
|
||||
lastName: 'Ahmadi',
|
||||
email: 'ali@example.com',
|
||||
mobile: '09123456789',
|
||||
};
|
||||
|
||||
vi.mocked(authService.updateProfile).mockResolvedValue(mockUpdatedData);
|
||||
|
||||
const store = useUserStore.getState();
|
||||
await store.updateProfile({ firstName: 'Ali Updated' });
|
||||
|
||||
expect(authService.updateProfile).toHaveBeenCalledWith({ firstName: 'Ali Updated' });
|
||||
const state = useUserStore.getState();
|
||||
expect(state.profile.firstName).toBe('Ali Updated');
|
||||
});
|
||||
|
||||
it('should add address and call fetchProfile', async () => {
|
||||
const address = {
|
||||
id: 'addr-1',
|
||||
title: 'Home',
|
||||
receptorName: 'Ali',
|
||||
phone: '0912',
|
||||
province: 'Teh',
|
||||
city: 'Teh',
|
||||
detail: 'Det',
|
||||
zipCode: '123',
|
||||
isDefault: false,
|
||||
};
|
||||
|
||||
const fetchSpy = vi.spyOn(useUserStore.getState(), 'fetchProfile').mockResolvedValue(undefined);
|
||||
vi.mocked(api.post).mockResolvedValue({ data: { success: true } });
|
||||
|
||||
const store = useUserStore.getState();
|
||||
await store.addAddress(address);
|
||||
|
||||
expect(api.post).toHaveBeenCalled();
|
||||
expect(fetchSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import '@testing-library/jest-dom';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
class LocalStorageMock {
|
||||
private store: Record<string, string> = {};
|
||||
|
||||
clear() {
|
||||
this.store = {};
|
||||
}
|
||||
|
||||
getItem(key: string) {
|
||||
return this.store[key] || null;
|
||||
}
|
||||
|
||||
setItem(key: string, value: string) {
|
||||
this.store[key] = String(value);
|
||||
}
|
||||
|
||||
removeItem(key: string) {
|
||||
delete this.store[key];
|
||||
}
|
||||
|
||||
get length() {
|
||||
return Object.keys(this.store).length;
|
||||
}
|
||||
|
||||
key(index: number) {
|
||||
return Object.keys(this.store)[index] || null;
|
||||
}
|
||||
}
|
||||
|
||||
const localStorageMock = new LocalStorageMock();
|
||||
Object.defineProperty(window, 'localStorage', {
|
||||
value: localStorageMock,
|
||||
writable: true,
|
||||
});
|
||||
|
||||
// Mock IntersectionObserver for framer-motion/motion viewport triggers
|
||||
class IntersectionObserverMock {
|
||||
readonly root: Element | null = null;
|
||||
readonly rootMargin: string = '';
|
||||
readonly thresholds: ReadonlyArray<number> = [];
|
||||
constructor(callback: any, options?: any) {}
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
takeRecords() { return []; }
|
||||
}
|
||||
Object.defineProperty(window, 'IntersectionObserver', {
|
||||
value: IntersectionObserverMock,
|
||||
writable: true,
|
||||
});
|
||||
|
||||
// Mock matchMedia if needed
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation(query => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(), // deprecated
|
||||
removeListener: vi.fn(), // deprecated
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
Reference in new issue
Block a user