12 / 12Proje
Ürün listesinden sepete tam akış testi.
Bu adımda önceki tüm parçaları birleştirirsiniz. Kullanıcı mağaza sayfasını açar. Ürünleri görür, sepete ekler, toplamı kontrol eder ve bir ürünü çıkarır.
| Parça | Görevi | Öğrenildiği adım |
|---|---|---|
ProductList | API'den ürünleri yükler ve gösterir. | Ürün Listesi |
CartProvider | Sepet durumunu paylaşır. | Provider ve Hook |
CartBadge | Sepetteki ürün adedini gösterir. | Provider ve Hook |
CartSummary | Ürünleri ve toplamı gösterir. | Provider ve Hook |
| MSW | API yanıtını taklit eder. | Mock |
Projenin çalışan hali GitHub'da: examples/vitest/project. Takıldığınızda karşılaştırın.
import { CartBadge, CartSummary } from "./cart-components";
import { useCart } from "./cart-context";
import { fetchProducts } from "./fetch-products";
import { ProductList } from "./ProductList";
export function ShopPage() {
const { addToCart } = useCart();
return (
<>
<CartBadge />
<ProductList loadProducts={fetchProducts} onAddToCart={addToCart} />
<CartSummary />
</>
);
}Sayfa gerçek fetchProducts fonksiyonunu kullanır. Testte MSW, API yanıtını verir. Hiçbir component mock'lanmaz. Bu, entegrasyon testidir.
import { screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { http, HttpResponse } from "msw/http";
import { server } from "./mocks/server";
import { ShopPage } from "./ShopPage";
import { renderWithProviders } from "./test-utils";http ve HttpResponse MSW 3'te msw/http yolundan import edilir.1
Konu: MSW, within,2 findByRole,3 userEvent, Context.
describe("ShopPage", () => {
test("the user adds products to the cart and sees the total", async () => {
const user = userEvent.setup();
renderWithProviders(<ShopPage />);
const keyboard = await screen.findByRole("article", {
name: "Mechanical Keyboard",
});
await user.click(
within(keyboard).getByRole("button", { name: "Add to cart" }),
);
await user.click(
within(keyboard).getByRole("button", { name: "Add to cart" }),
);
const headphones = screen.getByRole("article", {
name: "Wireless Headphones",
});
await user.click(
within(headphones).getByRole("button", { name: "Add to cart" }),
);
expect(screen.getByRole("link", { name: "Cart (3)" })).toBeInTheDocument();
const summary = screen.getByRole("region", { name: "Cart summary" });
expect(within(summary).getByText("Mechanical Keyboard × 2")).toBeInTheDocument();
expect(
within(summary).getByText("Wireless Headphones × 1"),
).toBeInTheDocument();
expect(within(summary).getByText("Total: €5,697.00")).toBeInTheDocument();
});Hesabı kontrol edin: 2 × 2.199 + 1.299 = 5.697. Beklenen değeri elle hesaplayın. Beklenen değeri koddaki formülle hesaplamayın.
İpucu
article ve region rollerinin erişilebilir adı içeriğinden değil, sizin verdiğiniz etiketten gelir. Bu yüzden ProductCard içinde aria-labelledby, CartSummary içinde aria-label bulunmalıdır. Etiket yoksa name ile sorgu eşleşmez.4
Konu: erişilebilir isim (aria-label) ve sepetin boşalması.
test("the user removes a product from the cart", async () => {
const user = userEvent.setup();
renderWithProviders(<ShopPage />);
const keyboard = await screen.findByRole("article", {
name: "Mechanical Keyboard",
});
await user.click(
within(keyboard).getByRole("button", { name: "Add to cart" }),
);
await user.click(
screen.getByRole("button", {
name: "Remove Mechanical Keyboard from cart",
}),
);
expect(screen.getByText("Your cart is empty.")).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Cart (0)" })).toBeInTheDocument();
});Konu: toBeVisible ve toBeDisabled.5
test("an out-of-stock product cannot be added to the cart", async () => {
renderWithProviders(<ShopPage />);
const mouse = await screen.findByRole("article", { name: "Gaming Mouse" });
expect(within(mouse).getByText("Out of stock")).toBeVisible();
expect(
within(mouse).getByRole("button", { name: "Add to cart" }),
).toBeDisabled();
});Konu: server.use ile tek test için farklı yanıt.6
test("the cart keeps working when the API fails", async () => {
server.use(
http.get(
"https://api.shop.test/products",
() => new HttpResponse(null, { status: 500 }),
),
);
renderWithProviders(<ShopPage />);
expect(await screen.findByRole("alert")).toHaveTextContent(
"Products could not be loaded.",
);
expect(screen.getByRole("link", { name: "Cart (0)" })).toBeInTheDocument();
expect(screen.getByText("Your cart is empty.")).toBeInTheDocument();
});
});Sepete Decrease butonu ekleyin. Önce testi yazın:
CartProvider içine decreaseQuantity(productId) fonksiyonu ekleyin. Adet 1 ise ürünü sepetten çıkarsın.
CartSummary içinde her ürün için erişilebilir adı "decrease
Test: Sepette 2 adet Mechanical Keyboard varken Decrease tıklanınca Mechanical Keyboard × 1 görünür. İkinci tıklamada ürün listeden kalkar ve Your cart is empty. görünür.
Kaynaklar
`http` ve `HttpResponse` için `msw/http` import yolu.
Sorguyu tek bir elemanın içine daraltma.
`getByRole` önceliği, `queryBy` ile yokluk ve `findBy` ile bekleme.
`article` ve `region` rollerinin adı yazardan gelir, `region` için ad zorunludur.
`toBeVisible` ve `toBeDisabled` matcher'larının kuralları.
Çalışma anında handler ekleme.
Testler yazılımın kullanılış biçimine ne kadar benzerse o kadar güven verir.
MSW ile ağ isteklerini mock'lama.
İlerlemeniz yalnızca bu tarayıcıda saklanır.
Son güncelleme tarihi: 3 Kasım 2026