04 / 12Proje
E-ticaret ürün kartı için adım adım test.
Mağaza sayfasında her ürün bir kartta görünür. Kart şunları yapar:
Ürün adını ve fiyatını gösterir.
Add to cart butonuna tıklanınca ürünü bildirir.
Ürün stokta yoksa Out of stock yazar ve butonu devre dışı bırakır.
Ürün indirimliyse eski fiyatı üstü çizili gösterir.
Projenin çalışan hali GitHub'da: examples/vitest/project. Takıldığınızda karşılaştırın.
Bu proje boyunca kullanacağınız son ProductCard sürümü. Önceki sürüme oldPrice ve aria-labelledby eklendi.1 Bu iki ekleme sonraki derslerde işe yarar.
import { formatPrice } from "./format-price";
import type { Product } from "./types";
type ProductCardProps = {
product: Product;
onAddToCart: (product: Product) => void;
};
export function ProductCard({ product, onAddToCart }: ProductCardProps) {
const titleId = `product-${product.id}-title`;
return (
<article aria-labelledby={titleId}>
<h2 id={titleId}>{product.name}</h2>
{product.oldPrice ? <s>{formatPrice(product.oldPrice)}</s> : null}
<p>{formatPrice(product.price)}</p>
{product.inStock ? null : <p>Out of stock</p>}
<button
type="button"
disabled={!product.inStock}
onClick={() => onAddToCart(product)}
>
Add to cart
</button>
</article>
);
}Product tipine isteğe bağlı bir oldPrice alanı ekleyin:
export type Product = {
id: number;
name: string;
price: number;
oldPrice?: number;
inStock: boolean;
};Testleri tek bir dosyada, adım adım yazın. Önce ortak veriyi tanımlayın:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ProductCard } from "./ProductCard";
import type { Product } from "./types";
const headphones: Product = {
id: 1,
name: "Wireless Headphones",
price: 1299,
inStock: true,
};describe("ProductCard", () => {
test("shows the product name and price", () => {
render(<ProductCard product={headphones} onAddToCart={vi.fn()} />);
expect(
screen.getByRole("heading", { name: "Wireless Headphones" }),
).toBeInTheDocument();
expect(screen.getByText("€1,299.00")).toBeInTheDocument();
});
});Sonraki üç testi aynı describe bloğunun içine ekleyin.
test("reports the product when Add to cart is clicked", async () => {
const user = userEvent.setup();
const onAddToCart = vi.fn();
render(<ProductCard product={headphones} onAddToCart={onAddToCart} />);
await user.click(screen.getByRole("button", { name: "Add to cart" }));
expect(onAddToCart).toHaveBeenCalledWith(headphones);
});test("disables the button for an out-of-stock product", async () => {
const user = userEvent.setup();
const onAddToCart = vi.fn();
render(
<ProductCard
product={{ ...headphones, inStock: false }}
onAddToCart={onAddToCart}
/>,
);
expect(screen.getByText("Out of stock")).toBeVisible();
expect(screen.getByRole("button", { name: "Add to cart" })).toBeDisabled();
await user.click(screen.getByRole("button", { name: "Add to cart" }));
expect(onAddToCart).not.toHaveBeenCalled();
});test("shows the old price for a discounted product", () => {
render(
<ProductCard
product={{ ...headphones, oldPrice: 1499 }}
onAddToCart={vi.fn()}
/>,
);
expect(screen.getByText("€1,499.00")).toBeInTheDocument();
expect(screen.getByText("€1,299.00")).toBeInTheDocument();
});İpucu
userEvent tarayıcı gibi davranır. Devre dışı butona tıklamak onAddToCart fonksiyonunu çağırmaz.2
Fiyat metnini formatPrice ile üretmeyin. Testte "€1,299.00" gibi sabit metin yazın. Biçim bozulursa test başarısız olur ve hatayı gösterir.
Fiyat biçimi Intl için kullanılan ICU verisine bağlıdır. Bu veri Node.js derlemesine ve sisteme göre değişebilir. Takımınız farklı ortamlar kullanıyorsa CI ortamında bir kez çalıştırarak doğrulayın.5
Önce testi yazın, sonra component'i değiştirin (TDD). İndirimli ürün için yüzde bilgisi eklenecek.
Test: price 1299, oldPrice 1499 olan ürün kartında %13 indirim yazısı görünür.
Testin başarısız olduğunu görün.
ProductCard içine yüzdeyi hesaplayıp gösterin.
Testin geçtiğini görün.
Kaynaklar
`article` rolünün adı içerikten değil yazardan gelir, bu yüzden `aria-labelledby` gerekir.
`userEvent` tarayıcının izin vermediği etkileşimi, örneğin devre dışı alanı, yapmaz.
`render`, `screen` ve rol sorgularıyla örnek test.
`toBeVisible` ve `toBeDisabled` matcher'larının kuralları.
`Intl` çıktısının ICU verisine ve Node.js derlemesine bağlılığı.
İlerlemeniz yalnızca bu tarayıcıda saklanır.
Son güncelleme tarihi: 3 Kasım 2026