Skip to content
Testing & QualityChapter 49 / 57Intermediate6 min read

Testing Pyramid

Testing pyramid unit, integration aur end to end tests ka balance, har layer kya sabit karti hai, real user se auth, aur vendors ko fake karna.

On this page

1. Yeh practice kya hai?

LayerKya sabit karti haiMisaal
UnitPure logic: parsers, validators, calculations, token helperscalculateTax(1000) sahi number deta hai
Endpoint / integrationAPI contract, har validation branch, auth failures, limitsPOST /api/orders ghalat body par 422
Browser (end to end)Poora user flow asli browser meinCheckout se payment tak

Neeche ki layer sasti, tez aur zyada. Upar ki mehngi, slow aur kam.

2. Kyun zaroori hai?

Agar sab kuch browser tests se check karein to suite ghanton chalti hai aur choti si UI change se das tests toot jate hain. Agar sirf unit tests hon to har function theek hai, lekin endpoint bina auth check ke production mein chala jata hai.

Ulta pyramid (ice cream cone)Sahi pyramid
Zyada tar browser testsZyada tar unit aur endpoint tests
Suite 40 minuteSuite chand minute
Flaky, retry par passDeterministic
Fail ho to pata nahi kahanFail ho to exact function ya endpoint
Shared databaseHar run ka apna isolated database

3. Kab follow karein?

LevelKitna zarooriKyun
Learning projectPure functions ke unit testsTesting ki aadat aur testable code likhna seekhna
Production codeUnit + har endpoint ke tests, browser tests critical flows ke liyeContract aur security har deploy par sabit
Senior levelLayers ka balance aur test infrastructureSuite tez aur bharose ke laiq rahe

4. Bura vs acha code

Bura: sab kuch mock

ts
vi.mock("@/lib/db");
vi.mock("@/lib/auth");

test("creates order", async () => {
  vi.mocked(getUser).mockResolvedValue({ id: "u1", role: "admin" });
  vi.mocked(db.order.create).mockResolvedValue({ id: "o1" });

  const res = await POST(new Request("http://x", { method: "POST", body: "{}" }));
  expect(res.status).toBe(201);
});

Auth mock hua, database mock hua, aur user hamesha admin. Yeh test sirf yeh sabit karta hai ke mocks chal rahe hain. Asli authorization kabhi test nahi hui.

Acha: unit test pure logic ka

ts
import { describe, expect, test } from "vitest";
import { calculateTax } from "./tax";

describe("calculateTax", () => {
  test("applies standard rate", () => {
    expect(calculateTax(1000)).toBe(170);
  });

  test("returns zero below threshold", () => {
    expect(calculateTax(50)).toBe(0);
  });
});

Acha: endpoint test real user ke saath

ts
import { expect, test } from "vitest";
import { signInAsSeededUser } from "../helpers/auth";

test("rejects order with empty items", async () => {
  const token = await signInAsSeededUser();

  const res = await fetch(`${process.env.TEST_BASE_URL}/api/orders`, {
    method: "POST",
    headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
    body: JSON.stringify({ items: [] }),
  });

  expect(res.status).toBe(422);
});

Seed script ek test user banata hai jis ka email pehle se confirmed hai. Test usi se sign in karta hai, is liye authorization aur tenant scoping bilkul production ki tarah chalti hai.

Farq kya hai?

CheezBuraAcha
AuthMock, hamesha adminSeeded real user ka token
DatabaseMockIsolated test database
Kya sabit huaMocks ka wiringAsli contract aur rules

5. Kaise apply karein?

Naye feature ke tests
Pure logic alag function mein nikalein
Us ke unit tests (har branch)
Endpoint ke success, validation, auth tests
Critical user flow ho to ek browser test
CI mein isolated database par sab chalayein

Rules jo har layer par lagte hain:

  • Tests kabhi production ya shared staging database ko nahi chhoote. CI service container (jaise Postgres ya MySQL) ya alag project use karta hai.
  • Bahar ke vendors (payment, SMS, email) boundary par fake hote hain. Jis test ko asli vendor key chahiye woh test nahi, scripts/ mein ek manual script hai.
  • Paid AI model calls CI suite mein nahi chalti. Prompt ke liye free contract test, aur paid evaluation sirf manually, cost estimate ke baad.
  • Tests kabhi mailbox ya SMS ka intezar nahi karte.

6. Exceptions aur common mistakes

Kab rule nahi lagta: chhota marketing site jis mein koi logic nahi, us par unit tests ka faida kam hai. Wahan build aur link check kaafi hai. Coverage percentage par bhi teams mukhtalif hain: kuch threshold enforce karti hain (jaise 80%), kuch sirf report karti hain taake number nazar aaye lekin log number poora karne ke liye bekaar tests na likhein. Dono ke paas dalil hai.

Galati: Har cheez browser test se check karna

Why? Suite slow aur flaky ho jati hai, aur fail hone par masla dhoondhna mushkil.

Behtar: Logic unit test mein, contract endpoint test mein, browser sirf critical flow ke liye.

Galati: Auth ko mock kar dena

Why? Phir authorization aur tenant scoping kabhi test nahi hoti, jo sab se khatarnak bugs hain.

Behtar: Seeded test user se asli sign in karein aur token bhejein.

Galati: Tests ka order par depend karna

Why? Ek test ka data doosre ko chahiye ho to akela chalane ya parallel par fail hota hai.

Behtar: Har test apna data khud banaye aur kisi doosre par na tike.

7. Pehle aur baad mein kya seekhein?

Final quick revision

CheckHaan?
Pure logic ke unit tests
Har endpoint ke contract tests
Browser tests sirf critical flows
Tests seeded real user se sign in
Isolated database, production kabhi nahi
Vendors fake, paid AI calls CI se bahar