- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
393 lines
14 KiB
TypeScript
393 lines
14 KiB
TypeScript
"use client";
|
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
|
import React from "react";
|
|
import CheckoutPage from "../CheckoutPage";
|
|
import { useCartStore } from "../../lib/store/cartStore";
|
|
import { usePetStore } from "../../lib/store/usePetStore";
|
|
import { useUserStore } from "../../lib/store/userStore";
|
|
import { useSettingsStore } from "../../lib/store/settingsStore";
|
|
import { useCatalogMode } from "../../lib/useCatalogMode";
|
|
import { toast } from "sonner";
|
|
import api from "../../lib/services/api";
|
|
|
|
const mockRouterPush = vi.fn();
|
|
const mockRouterBack = vi.fn();
|
|
|
|
vi.mock("next/navigation", () => ({
|
|
useRouter: () => ({
|
|
push: mockRouterPush,
|
|
back: mockRouterBack,
|
|
}),
|
|
}));
|
|
|
|
vi.mock("sonner", () => ({
|
|
toast: {
|
|
success: vi.fn(),
|
|
error: vi.fn(),
|
|
info: vi.fn(),
|
|
},
|
|
}));
|
|
|
|
vi.mock("../../lib/services/api", () => ({
|
|
default: {
|
|
post: vi.fn(),
|
|
},
|
|
}));
|
|
|
|
vi.mock("../../lib/useCatalogMode", () => ({
|
|
useCatalogMode: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../../lib/store/cartStore", () => ({
|
|
useCartStore: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../../lib/store/usePetStore", () => ({
|
|
usePetStore: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../../lib/store/userStore", () => ({
|
|
useUserStore: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../../lib/store/settingsStore", () => ({
|
|
useSettingsStore: vi.fn(),
|
|
}));
|
|
|
|
const mockProductA = {
|
|
id: "canina-v25",
|
|
name: "Canina V25 ویتامینه",
|
|
price: "۴۵۰,۰۰۰ تومان",
|
|
priceValue: 450000,
|
|
packageSize: 30,
|
|
category: "vitamins",
|
|
image: "/v25.png",
|
|
};
|
|
|
|
describe("CheckoutPage Component", () => {
|
|
const mockClearCart = vi.fn();
|
|
const mockAddOrder = vi.fn();
|
|
const mockSetCharityDonation = vi.fn();
|
|
const mockApplyCoupon = vi.fn();
|
|
|
|
const mockAddAddress = vi.fn().mockResolvedValue({});
|
|
const mockUpdateProfile = vi.fn().mockResolvedValue({});
|
|
const mockFetchProfile = vi.fn().mockResolvedValue({});
|
|
const mockSetAuthModalOpen = vi.fn();
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
|
|
// Default Catalog Mode
|
|
vi.mocked(useCatalogMode).mockReturnValue({
|
|
isCatalogOnly: false,
|
|
allowCheckout: true,
|
|
showPrices: true,
|
|
allowCart: true,
|
|
showPreorderBtn: false,
|
|
showOrders: true,
|
|
showWallet: true,
|
|
showCharity: true,
|
|
orderDisabledTitle: "امکان ثبت سفارش وجود ندارد",
|
|
orderDisabledMessage: "فروشگاه موقتاً در حالت کاتالوگ است.",
|
|
});
|
|
|
|
// Default Cart Store
|
|
const cartState = {
|
|
items: [
|
|
{
|
|
product: mockProductA,
|
|
quantity: 2,
|
|
},
|
|
],
|
|
getTotal: () => 900000,
|
|
getSubtotal: () => 900000,
|
|
isSubscribed: false,
|
|
charityDonation: 0,
|
|
setCharityDonation: mockSetCharityDonation,
|
|
addOrder: mockAddOrder,
|
|
clearCart: mockClearCart,
|
|
applyCoupon: mockApplyCoupon,
|
|
};
|
|
vi.mocked(useCartStore).mockReturnValue(cartState as unknown as ReturnType<typeof useCartStore>);
|
|
(useCartStore as unknown as { getState: () => typeof cartState }).getState = () => cartState;
|
|
|
|
// Default Pet Store
|
|
const petState = {
|
|
pets: [
|
|
{
|
|
id: "pet-1",
|
|
name: "میلو",
|
|
breed: "هاسکی",
|
|
type: "سگ",
|
|
consumptions: [],
|
|
},
|
|
],
|
|
activePetId: "pet-1",
|
|
getActivePet: () => ({
|
|
id: "pet-1",
|
|
name: "میلو",
|
|
breed: "هاسکی",
|
|
type: "سگ",
|
|
consumptions: [],
|
|
}),
|
|
updatePet: vi.fn(),
|
|
};
|
|
vi.mocked(usePetStore).mockReturnValue(petState as unknown as ReturnType<typeof usePetStore>);
|
|
(usePetStore as unknown as { getState: () => typeof petState }).getState = () => petState;
|
|
|
|
// Default User Store
|
|
const userState = {
|
|
isLoggedIn: true,
|
|
profile: {
|
|
id: "usr-1",
|
|
firstName: "علی",
|
|
lastName: "رضایی",
|
|
mobile: "09121112233",
|
|
walletBalance: 2000000,
|
|
addresses: [
|
|
{
|
|
id: "addr-1",
|
|
title: "منزل اصلی",
|
|
receptorName: "علی رضایی",
|
|
phone: "09121112233",
|
|
province: "تهران",
|
|
city: "تهران",
|
|
detail: "خیابان ولیعصر پلاک ۱",
|
|
zipCode: "1234567890",
|
|
isDefault: true,
|
|
},
|
|
],
|
|
},
|
|
addAddress: mockAddAddress,
|
|
updateProfile: mockUpdateProfile,
|
|
fetchProfile: mockFetchProfile,
|
|
setAuthModalOpen: mockSetAuthModalOpen,
|
|
updateAddress: vi.fn(),
|
|
};
|
|
vi.mocked(useUserStore).mockReturnValue(userState as unknown as ReturnType<typeof useUserStore>);
|
|
(useUserStore as unknown as { getState: () => typeof userState }).getState = () => userState;
|
|
|
|
// Default Settings Store
|
|
const settingsState = {
|
|
getText: (key: string, def: string) => {
|
|
if (key === "free_shipping_threshold") return "2000000";
|
|
if (key === "shipping_fee") return "50000";
|
|
if (key === "CHARITY_ROUND_STEP") return "10000";
|
|
return def;
|
|
},
|
|
getBoolean: (key: string, def: boolean) => def,
|
|
};
|
|
vi.mocked(useSettingsStore).mockImplementation(
|
|
(selector: (s: typeof settingsState) => unknown) => selector(settingsState) as ReturnType<typeof selector>
|
|
);
|
|
(useSettingsStore as unknown as { getState: () => typeof settingsState }).getState = () => settingsState;
|
|
});
|
|
|
|
it("renders catalog-only banner when order/checkout is disabled", () => {
|
|
vi.mocked(useCatalogMode).mockReturnValue({
|
|
isCatalogOnly: true,
|
|
allowCheckout: false,
|
|
showPrices: false,
|
|
allowCart: false,
|
|
showPreorderBtn: false,
|
|
showOrders: false,
|
|
showWallet: false,
|
|
showCharity: false,
|
|
orderDisabledTitle: "ثبت سفارش در حال حاضر غیرفعال است",
|
|
orderDisabledMessage: "لطفاً با واحد فروش تماس حاصل فرمایید.",
|
|
});
|
|
|
|
render(<CheckoutPage />);
|
|
|
|
expect(screen.getByText("ثبت سفارش در حال حاضر غیرفعال است")).toBeInTheDocument();
|
|
expect(screen.getByText("لطفاً با واحد فروش تماس حاصل فرمایید.")).toBeInTheDocument();
|
|
expect(screen.getByText("مشاهده کاتالوگ")).toBeInTheDocument();
|
|
});
|
|
|
|
it("renders empty cart state when user cart is empty", () => {
|
|
const emptyCartState = {
|
|
items: [],
|
|
getTotal: () => 0,
|
|
getSubtotal: () => 0,
|
|
isSubscribed: false,
|
|
charityDonation: 0,
|
|
setCharityDonation: mockSetCharityDonation,
|
|
addOrder: mockAddOrder,
|
|
clearCart: mockClearCart,
|
|
applyCoupon: mockApplyCoupon,
|
|
};
|
|
vi.mocked(useCartStore).mockReturnValue(emptyCartState as unknown as ReturnType<typeof useCartStore>);
|
|
(useCartStore as unknown as { getState: () => typeof emptyCartState }).getState = () => emptyCartState;
|
|
|
|
render(<CheckoutPage />);
|
|
|
|
expect(screen.getByText("سبد خرید شما خالی است")).toBeInTheDocument();
|
|
expect(screen.getByText("بازگشت به فروشگاه")).toBeInTheDocument();
|
|
});
|
|
|
|
it("renders order items, stored address, and cost summary properly", () => {
|
|
render(<CheckoutPage />);
|
|
|
|
expect(screen.getByText("اطلاعات تحویل و گیرنده")).toBeInTheDocument();
|
|
expect(screen.getByText("Canina V25 ویتامینه")).toBeInTheDocument();
|
|
expect(screen.getByText("خلاصه سفارش")).toBeInTheDocument();
|
|
expect(screen.getByText("شیوه پرداخت")).toBeInTheDocument();
|
|
|
|
// Stored address should be displayed
|
|
expect(screen.getByText("منزل اصلی")).toBeInTheDocument();
|
|
expect(screen.getByText(/تهران، تهران، خیابان ولیعصر پلاک ۱/)).toBeInTheDocument();
|
|
});
|
|
|
|
it("prevents finalize and opens login modal if user is not logged in", async () => {
|
|
const unauthenticatedUser = {
|
|
isLoggedIn: false,
|
|
profile: { addresses: [] },
|
|
addAddress: mockAddAddress,
|
|
updateProfile: mockUpdateProfile,
|
|
fetchProfile: mockFetchProfile,
|
|
setAuthModalOpen: mockSetAuthModalOpen,
|
|
};
|
|
vi.mocked(useUserStore).mockReturnValue(unauthenticatedUser as unknown as ReturnType<typeof useUserStore>);
|
|
(useUserStore as unknown as { getState: () => typeof unauthenticatedUser }).getState = () => unauthenticatedUser;
|
|
|
|
render(<CheckoutPage />);
|
|
|
|
const submitBtn = screen.getByText("پرداخت و تکمیل سفارش");
|
|
fireEvent.click(submitBtn);
|
|
|
|
expect(toast.error).toHaveBeenCalledWith(
|
|
expect.stringContaining("جهت تکمیل خرید و ثبت سفارش، لطفاً ابتدا وارد حساب کاربری خود شوید.")
|
|
);
|
|
expect(mockSetAuthModalOpen).toHaveBeenCalledWith(true);
|
|
expect(mockAddOrder).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("successfully finalizes order and redirects on valid checkout", async () => {
|
|
mockAddOrder.mockResolvedValue("ORDER-CANINA-101");
|
|
|
|
render(<CheckoutPage />);
|
|
|
|
// Select the address radio button to ensure selectedAddressId is set
|
|
const addressCard = screen.getByText("منزل اصلی").closest("div");
|
|
if (addressCard) fireEvent.click(addressCard);
|
|
|
|
const submitBtn = screen.getByText("پرداخت و تکمیل سفارش");
|
|
fireEvent.click(submitBtn);
|
|
|
|
await waitFor(() => {
|
|
expect(mockAddOrder).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
expect(mockAddOrder).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
items: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
product: mockProductA,
|
|
quantity: 2,
|
|
}),
|
|
]),
|
|
paymentMethod: "card",
|
|
})
|
|
);
|
|
|
|
expect(mockClearCart).toHaveBeenCalledTimes(1);
|
|
expect(toast.success).toHaveBeenCalledWith("سفارش شما با موفقیت ثبت شد!");
|
|
expect(mockRouterPush).toHaveBeenCalledWith("/checkout/success/ORDER-CANINA-101");
|
|
});
|
|
|
|
it("preserves cart and avoids fulfillment when gateway returns no payment URL", async () => {
|
|
mockAddOrder.mockResolvedValueOnce("ORDER-PENDING");
|
|
vi.mocked(api.post).mockResolvedValueOnce({ data: {} });
|
|
render(<CheckoutPage />);
|
|
fireEvent.click(screen.getByRole("radio", { name: "" }));
|
|
fireEvent.click(screen.getByText("درگاه پرداخت اینترنتی (زیبال / شتاب)"));
|
|
fireEvent.click(screen.getByText("پرداخت و تکمیل سفارش"));
|
|
await waitFor(() => expect(toast.error).toHaveBeenCalledWith("خطا در ایجاد تراکنش پرداخت زیبال"));
|
|
await waitFor(() => expect(screen.getByText("پرداخت و تکمیل سفارش").closest("button")).not.toBeDisabled());
|
|
expect(api.post).toHaveBeenCalledWith('/payment/zibal/initiate', { orderId: 'ORDER-PENDING' });
|
|
expect(mockClearCart).not.toHaveBeenCalled();
|
|
expect(usePetStore.getState().updatePet).not.toHaveBeenCalled();
|
|
expect(toast.success).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps cart and reports backend rejection without navigating", async () => {
|
|
mockAddOrder.mockRejectedValueOnce({ response: { data: { message: 'موجودی کافی نیست' } } });
|
|
render(<CheckoutPage />);
|
|
fireEvent.click(screen.getByRole('radio', { name: '' }));
|
|
fireEvent.click(screen.getByText('پرداخت و تکمیل سفارش'));
|
|
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در ثبت سفارش: موجودی کافی نیست'));
|
|
expect(mockClearCart).not.toHaveBeenCalled();
|
|
expect(mockRouterPush).not.toHaveBeenCalled();
|
|
expect(usePetStore.getState().updatePet).not.toHaveBeenCalled();
|
|
await waitFor(() => expect(screen.getByText('پرداخت و تکمیل سفارش').closest('button')).not.toBeDisabled());
|
|
});
|
|
|
|
it("preserves cart on gateway network failure", async () => {
|
|
mockAddOrder.mockResolvedValueOnce('ORDER-NETWORK');
|
|
vi.mocked(api.post).mockRejectedValueOnce({ response: { data: { message: 'درگاه در دسترس نیست' } } });
|
|
render(<CheckoutPage />);
|
|
fireEvent.click(screen.getByRole('radio', { name: '' }));
|
|
fireEvent.click(screen.getByText('درگاه پرداخت اینترنتی (زیبال / شتاب)'));
|
|
fireEvent.click(screen.getByText('پرداخت و تکمیل سفارش'));
|
|
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('درگاه در دسترس نیست'));
|
|
expect(mockRouterPush).toHaveBeenCalledWith('/checkout/success/ORDER-NETWORK');
|
|
expect(mockClearCart).not.toHaveBeenCalled();
|
|
expect(usePetStore.getState().updatePet).not.toHaveBeenCalled();
|
|
expect(toast.success).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("checks wallet balance and shows top-up modal if wallet balance is insufficient", async () => {
|
|
const poorUserState = {
|
|
isLoggedIn: true,
|
|
profile: {
|
|
id: "usr-poor",
|
|
firstName: "علی",
|
|
lastName: "رضایی",
|
|
mobile: "09121112233",
|
|
walletBalance: 100000, // Total is 900,000 + 50,000 = 950,000
|
|
addresses: [
|
|
{
|
|
id: "addr-1",
|
|
title: "منزل اصلی",
|
|
receptorName: "علی رضایی",
|
|
phone: "09121112233",
|
|
province: "تهران",
|
|
city: "تهران",
|
|
detail: "خیابان ولیعصر پلاک ۱",
|
|
zipCode: "1234567890",
|
|
isDefault: true,
|
|
},
|
|
],
|
|
},
|
|
addAddress: mockAddAddress,
|
|
updateProfile: mockUpdateProfile,
|
|
fetchProfile: mockFetchProfile,
|
|
setAuthModalOpen: mockSetAuthModalOpen,
|
|
};
|
|
vi.mocked(useUserStore).mockReturnValue(poorUserState as unknown as ReturnType<typeof useUserStore>);
|
|
(useUserStore as unknown as { getState: () => typeof poorUserState }).getState = () => poorUserState;
|
|
|
|
render(<CheckoutPage />);
|
|
|
|
// Select stored address explicitly
|
|
const addressCard = screen.getByText("منزل اصلی").closest("div");
|
|
if (addressCard) fireEvent.click(addressCard);
|
|
|
|
// Select wallet payment method
|
|
const walletOption = screen.getByText("اعتبار حساب (کیف پول)");
|
|
fireEvent.click(walletOption);
|
|
|
|
const submitBtn = screen.getByText("پرداخت و تکمیل سفارش");
|
|
fireEvent.click(submitBtn);
|
|
|
|
await waitFor(() => {
|
|
expect(toast.error).toHaveBeenCalledWith(
|
|
expect.stringContaining("موجودی کیف پول شما")
|
|
);
|
|
});
|
|
expect(mockAddOrder).not.toHaveBeenCalled();
|
|
});
|
|
});
|