Jest, React Testing Library, Mocking, E2E Testing aur bahut kuch!
๐ Testing Kya Hai Aur Kyun Zaroori Hai?
Testing matlab apne code ko verify karna ki wo expected tarike se kaam kar raha hai ya nahi. React applications mein testing bahut important hai kyunki:
๐ Bugs ko early catch kar sakte hain
๐ Code quality maintain hoti hai
โป๏ธ Refactoring safe ho jata hai
๐ Tests documentation ka kaam bhi karte hain
๐ Deployment confidence badhta hai
Testing Pyramid: Ek concept hai jo batata hai ki different levels of testing ka ratio kya hona chahiye. Neeche click karke explore karo!
๐บ Interactive Testing Pyramid - Click on Each Layer!
E2E Tests (10%)
Integration Tests (30%)
Unit Tests (60%)
๐ฏ End-to-End (E2E) Tests
Kya hai: Pura application ko user ki tarah test karna
Tools: Cypress, Playwright, Selenium
Example: Login โ Dashboard โ Create Post โ Logout
Pros: Real user experience test hota hai
Cons: Slow aur expensive, maintenance zyada
๐ Integration Tests
Kya hai: Multiple components/modules ko saath mein test karna
Tools: React Testing Library, Jest
Example: Form component + validation + API call
Pros: Components ki interaction verify hoti hai
Cons: Unit tests se slow, setup complex
โก Unit Tests
Kya hai: Individual functions/components ko isolation mein test karna
Tools: Jest, Vitest
Example: Single function, single component
Pros: Fast, easy to write, pinpoint issues
Cons: Integration issues miss ho sakte hain
๐ Jest Basics
Jest ek JavaScript testing framework hai jo Facebook ne banaya. Ye React ke saath out-of-the-box kaam karta hai aur bahut powerful features provide karta hai.
Jest Features: Zero config, snapshot testing, mocking, code coverage, parallel test execution
Basic Test Structure
// sum.js
export function sum(a, b) {
return a + b;
}
// sum.test.js
import { sum } from './sum';
describe('sum function', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
test('adds negative numbers', () => {
expect(sum(-1, -2)).toBe(-3);
});
});
describe: Test suite banane ke liye - related tests ko group karta hai
test/it: Individual test case define karne ke liye
expect: Assertion banane ke liye - kya expect kar rahe ho
React Testing Library (RTL) ek library hai jo React components ko test karne ke liye banayi gayi hai. Iska philosophy hai: "Test your components the way users interact with them"
Matlab implementation details ko test karne ki jagah, user behavior ko test karo!
Core Principle: "The more your tests resemble the way your software is used, the more confidence they can give you."
// getBy* - Element hona chahiye, nahi toh error
screen.getByText('Submit');
screen.getByRole('button');
screen.getByLabelText('Email');
screen.getByPlaceholderText('Enter name');
screen.getByTestId('custom-element');
// queryBy* - Element nahi hai toh null return karta
screen.queryByText('Not Found'); // null if not found
// findBy* - Async elements ke liye (returns Promise)
await screen.findByText('Loaded Data');
// getAllBy*, queryAllBy*, findAllBy* - Multiple elements
screen.getAllByRole('listitem');
๐ฏ Query Method Selector
Sample Component:
Login Form
Select Query Method:
๐ฌ Unit Testing
Unit Testing mein hum individual functions aur components ko isolation mein test karte hain. Ye sabse chhote level ka testing hai aur sabse zyada tests bhi yahi hote hain.
Integration Testing mein hum multiple components ya modules ko saath mein test karte hain. Ye verify karta hai ki different parts ek saath sahi se kaam kar rahe hain.
MSW ek powerful tool hai jo network level pe mocking karta hai. Ye actual HTTP requests ko intercept karke mock responses return karta hai. Development aur testing dono mein use ho sakta hai!
๐ธ Snapshot Testing
Snapshot Testing mein component ka rendered output save kar lete hain aur future tests mein compare karte hain. Agar output change hota hai toh test fail ho jata hai.
Ye UI regressions catch karne ke liye bahut useful hai!
Har test independent hona chahiye - ek test dusre pe depend nahi karna chahiye
4. Use Descriptive Test Names
Test name se hi samajh aana chahiye ki kya test ho raha hai
// โ Bad
test('button works', () => { ... });
// โ Good
test('submits form when submit button is clicked', () => { ... });
test('shows validation error when email is invalid', () => { ... });
5. Avoid Testing Third-Party Libraries
React, Redux, etc. already tested hain - apna code test karo
6. Mock External Dependencies
API calls, timers, random values - sab mock karo for consistent tests
7. Test Edge Cases
Sirf happy path nahi, error cases bhi test karo
Empty states
Loading states
Error states
Boundary values
Network failures
๐ฏ Interview Questions
1. Jest aur React Testing Library mein kya difference hai?
Easyโผ
Answer:
Jest ek testing framework hai jo test runner, assertion library, aur mocking capabilities provide karta hai. Ye kisi bhi JavaScript code ko test kar sakta hai.
React Testing Library ek library hai jo specifically React components ko test karne ke liye banayi gayi hai. Ye DOM queries aur user interactions simulate karne ke tools provide karta hai.
Relationship: RTL Jest ke saath use hota hai - Jest tests run karta hai aur RTL React components ko render aur query karta hai.
getBy*: Element immediately milna chahiye, nahi toh error throw karta hai. Synchronous hai.
queryBy*: Element nahi mila toh null return karta hai (no error). Negative assertions ke liye use hota hai.
findBy*: Async elements ke liye. Promise return karta hai aur element ke appear hone ka wait karta hai (default 1000ms timeout).
// Use getBy when element should be there
const button = screen.getByRole('button');
// Use queryBy to check element doesn't exist
expect(screen.queryByText('Error')).not.toBeInTheDocument();
// Use findBy for async elements
const data = await screen.findByText('Loaded Data');
3. API calls ko test karte waqt kya approach use karni chahiye?
Mediumโผ
Answer:
API calls ko test karne ke liye mainly 3 approaches hain: