Skip to content
EcosystemChapter 37 / 37Advanced5 min read

Testing React Apps

React testing library vitest Roman Urdu mein, Vitest setup, render, screen queries aur user-event se React components ko user ki tarah test karna.

On this page

1. Testing React Apps kya hai?

Aaj kal ka common stack yeh hai: Vitest (test runner, Vite ke saath fast), React Testing Library (component render aur UI dhoondna), aur user-event (asli user jaisa click aur typing).

React Testing Library ka falsafa simple hai: component ke andar ki state ya functions test na karo, balke wohi test karo jo user dekhta aur karta hai.

2. Kyun zaroori hai?

Har change ke baad haath se har page khol kar check karna slow hai aur cheezein reh jati hain. Tests yeh kaam seconds mein, har baar, ek jaisa karte hain.

Sirf manual testingAutomated tests ke saath
Har change par browser mein click clicknpm test se sab check
Purane features chupke se toot jate hainRegression foran pakra jata hai
Refactor karte darr lagta haiTests green hain to confidence
Bug production mein milta haiBug CI mein hi ruk jata hai

3. Kahan use hota hai?

Test typeKya check karta haiTool
UnitEk function ya hookVitest
ComponentEk component ka render aur interactionVitest + Testing Library
IntegrationKai components saath, jaise form + listVitest + Testing Library
End to endPoora app asli browser meinPlaywright

4. Kaise kaam karta hai?

Vitest Node mein chalta hai. jsdom environment ek nakli browser DOM deta hai. Testing Library component ko us DOM mein render karti hai, aur aap screen se elements dhoondte hain.

Ek test ka flow
render(component)
screen.getByRole se element dhoondo
user-event se click ya type
expect se result check
Test pass ya fail

Query priority yaad rakhein: pehle getByRole, phir getByLabelText, phir getByText. getByTestId sirf aakhri option.

5. Code example

Setup

bash
npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom
ts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    globals: true,
    setupFiles: "./vitest.setup.ts",
  },
});
ts
import "@testing-library/jest-dom/vitest";

Pehli file vitest.config.ts hai aur doosri vitest.setup.ts, jo toBeInTheDocument jaise matchers add karti hai.

Example 1: Counter test

tsx
import { useState } from "react";

export function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { Counter } from "./Counter";

describe("Counter", () => {
  it("click par count barhta hai", async () => {
    const user = userEvent.setup();
    render(<Counter />);

    const button = screen.getByRole("button", { name: /count: 0/i });
    await user.click(button);

    expect(screen.getByRole("button", { name: /count: 1/i })).toBeInTheDocument();
  });
});

Example 2: Async UI ka test

tsx
it("data aane par naam dikhata hai", async () => {
  render(<UserCard userId={1} />);

  expect(screen.getByText(/load ho raha hai/i)).toBeInTheDocument();
  expect(await screen.findByText("Ali")).toBeInTheDocument();
});

Code kaise kaam kar raha hai?

CheezMatlab
environment: "jsdom"Node mein browser jaisa DOM
globals: trueTesting Library har test ke baad khud cleanup kar sake
userEvent.setup()Har test ke shuru mein user instance
await user.click(...)user-event ke actions async hote hain
getByRole("button", ...)Accessible role aur naam se dhoondna
findByTextElement aane tak wait karta hai (async)
toBeInTheDocument()jest-dom ka matcher

Interview tip

getBy, queryBy aur findBy ka farq zaroor poocha jata hai. getBy na mile to error deta hai, queryBy null deta hai (cheez ke na hone ka test), aur findBy Promise deta hai jo element aane tak wait karta hai.

6. Common mistakes

Galati: Implementation details test karna

Why? State ya internal function ke naam badalne par test toot jata hai, halanke user ke liye kuch nahi badla.

Behtar: Wohi test karo jo user dekhta hai: text, roles, labels aur unka behaviour.

Galati: user-event ke actions par await na lagana

Why? Action poora hone se pehle expect chal jata hai aur test random fail hota hai.

Behtar: userEvent.setup() lo aur har user.click ya user.type ke aage await lagao.

Galati: Async UI ke liye getBy use karna

Why? Data abhi aaya nahi hota, is liye getBy foran fail ho jata hai.

Behtar: Aane wale elements ke liye await findBy use karo.

Galati: Har cheez ke liye data-testid lagana

Why? Tests accessibility check nahi karte aur user ke nazariye se door ho jate hain.

Behtar: Pehle getByRole aur getByLabelText try karo, testid aakhri option rakho.

7. Pehle aur baad mein kya seekhein?

Final quick revision

PointDetail
RunnerVitest, environment: "jsdom"
Renderrender() aur screen
QueriesgetByRole pehle, findBy async ke liye
InteractionuserEvent.setup() aur await user.click()
Matchers@testing-library/jest-dom/vitest