Skip to content
GraphQL

7. API Testing Kya Hai? Jest पहला Test API Testing Jest Hindi

June 1, 2026 17 min read

नमस्ते दोस्तों!

स्वागत है The Easy Master पर!

आपने REST API ya GraphQL API बना ली। FastAPI हो, ya Node.js Express – sab kuch चल रहा है। Lekin ek sawaal हमेशा रहता है – “Kya meri API production mein jaane se pehle sahi kaam karegi?”

Jab maine pehli baar ek feature add kiya, maine manually check kiya ki sab sahi hai। Sab green tha। Par us feature ने kisi aur endpoint ko tod diya – aur mujhe pata bhi nahi chala। Jab users ko problem aayi, tab jaake pata chala।

Tab maine seekha – API testing is not just a good practice; it’s a safety net। Tests aapka time बचाते हैं, confidence देते हैं, aur production bugs को early catch करते हैं।

Is API testing Jest aur Supertest Hindi guide mein main aapko sikhata hoon:

✅ API Testing kya hota hai – manual vs automated, unit vs integration
✅ Jest & Supertest kyun – comparison with Mocha, Chai, Pytest
✅ Jest & Supertest setup – Node.js/TypeScript project में
✅ Pehla test likhein – GET request, status code, JSON response
✅ POST request test – body validate karein, status code check
✅ Async testing – async/await use karein
✅ Mocking dependencies – database, external API calls
✅ Auth testing – JWT token mock karein
✅ Best practices – production-level tips
✅ Common mistakes – aur unka solution

Ye article beginners ke liye hai – agar aapko thodi si JavaScript ya TypeScript aati hai, to aap easily follow kar sakte ho। Chaliye API testing की दुनिया mein step rakhte hain! 🚀

1. API Testing Kya Hai? – क्यों जरूरी है?

API testing automated tests likhne ki process hai jo check karti hai ki aapki API sahi tarah se kaam kar rahi hai ya nahi – status codes, response body, headers, error messages, performance – sab kuch।

Manual testing ki problems:

ProblemExample
Time-consumingHar feature change ke baad saare endpoints manually check karna
Error-proneAadha testing reh jaata hai ya kuch miss ho jaata hai
Not scalable50 endpoints ho to manually test karna impossible hai

Automated testing ke benefits:

  • Fast execution – secondon mein saare tests चल जाते हैं
  • Early bug detection – feature add karte hi test fail ho jaata hai agar kuch toota hai
  • Confidence – changes karne se pehle pata hota hai ki sab sahi hai ya nahi
  • Documentation – tests yahan bataate hain ki API kaise behave karni chahiye

💡 Personal Experience: Maine ek baar ek feature add kiya – sab manual test kiya, sab sahi lag raha tha। Deploy kiya। Phir users ne complaint kiya ki login nahi ho raha। Pata chala ki mere change ne authentication middleware tod diya tha। Us din maine decide kiya – ab se tests mandatory honge।

2. Jest vs Mocha vs Pytest – कौनसा Choose करें?

Testing frameworks ke beech choose karna mushkil ho sakta hai। Let’s compare:

AspectJestMocha + ChaiPytest (Python)
SetupZero-config, out-of-the-boxManual configuration requiredEasy, pip install
EcosystemReact, Node.js, TypeScriptNode.js, flexiblePython (FastAPI, Django, Flask)
AssertionsBuilt-in (expect)Separate library (Chai)Built-in (assert)
MockingBuilt-in (jest.mock)Separate library (Sinon)Built-in (unittest.mock)
Parallel executionYes (default)Manual configurationYes (pytest-xdist)
Snapshot testingBuilt-inThird-partyNo
Best forJavaScript/TypeScript appsNode.js apps needing flexibilityPython/FastAPI apps

Yeh article mein Jest kyun? – Kyonki hum Node.js/TypeScript use kar rahe hain, Jest integrated hai, setup easy hai, aur Supertest ke saath perfect combination बनाता है। Agar aap FastAPI use kar rahe ho, to pytest better choice hai। But concepts same hain।

Supertest ek library hai jo HTTP requests ko simulate karti hai – Express app ke saath direct kaam karti hai bina server start kiye। Isse tests fast और reliable बनते हैं。Supertest simply lets you fire HTTP requests directly at your Express app without starting a server on a real port。

Kapde ki boli: Supertest woh dost hai jo actual request bhejta hai aur response laata hai। Jest woh judge hai jo check karta hai ki response sahi hai ya nahi।

3. Jest & Supertest Setup – Node.js + TypeScript Project

Chaliye practical start karte hain। Setup step-by-step:

3.1 Project Initialization

Bash
mkdir api-testing-demo
cd api-testing-demo
npm init -y

3.2 Install Dependencies

Bash
# Express app dependencies
npm install express

# Testing dependencies
npm install --save-dev jest supertest @types/jest @types/supertest typescript ts-jest @types/node

Har package kya karta hai:

PackagePurpose
jestTesting framework (assertions, mocks)
supertestHTTP request simulation
@types/jestTypeScript types for Jest
@types/supertestTypeScript types for Supertest
typescriptTypeScript compiler
ts-jestJest ke liye TypeScript preprocessor
@types/nodeNode.js TypeScript types

3.3 Configure Jest

jest.config.js file banayein:

JavaScript
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/*.test.ts'],
  collectCoverageFrom: ['src/**/*.ts', '!src/server.ts'],
  coverageDirectory: 'coverage',
};

Package.json mein scripts add karein:

JSON
"scripts": {
  "test": "jest",
  "test:watch": "jest --watch",
  "test:coverage": "jest --coverage"
}

3.4 Create Express App

Critical point: app aur server ko separate rakhna। Agar listen() app mein rahega to test files import karte time real port bind hoga aur conflicts honge।

src/app.ts:

TypeScript
import express from 'express';

const app = express();
app.use(express.json());

// Health check endpoint
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', timestamp: Date.now() });
});

// GET /users
app.get('/users', (req, res) => {
  res.json({ users: [] });
});

// POST /users
app.post('/users', (req, res) => {
  const { name, email } = req.body;
  if (!name || !email) {
    return res.status(400).json({ error: 'Name and email are required' });
  }
  res.status(201).json({ id: Date.now(), name, email });
});

export default app;

src/server.ts:

TypeScript
import app from './app';

const PORT = process.env.PORT || 3000;

const server = app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

export default server;

Folder structure:

text

Code
api-testing-demo/
├── src/
│   ├── app.ts
│   ├── server.ts
│   └── __tests__/
│       └── app.test.ts
├── jest.config.js
├── package.json
├── tsconfig.json
└── node_modules/

4. Pehla Test – GET Endpoint Ko Test Karein

Ab hum apna pehla test likhte hain। File banayein src/__tests__/app.test.ts:

TypeScript
import request from 'supertest';
import app from '../app';

describe('Health Check Endpoint', () => {
  it('GET /health should return 200 and status ok', async () => {
    const response = await request(app)
      .get('/health')
      .expect('Content-Type', /json/)
      .expect(200);
    
    expect(response.body).toHaveProperty('status', 'ok');
    expect(response.body).toHaveProperty('timestamp');
  });
});

describe('GET /users', () => {
  it('should return empty users array', async () => {
    const response = await request(app)
      .get('/users')
      .expect(200);
    
    expect(response.body).toHaveProperty('users');
    expect(response.body.users).toEqual([]);
  });
});

Code Explanation

CodeMeaning
request(app)Supertest को Express app instance pass karte hain
.get('/health')HTTP GET request bhejte hain
.expect(200)Assert karte hain ki status code 200 aana chahiye
.expect('Content-Type', /json/)Check karte hain ki response JSON format mein hai
expect(response.body).toHaveProperty('status', 'ok')Jest assertion ki response body mein ‘status’ field hai aur uska value ‘ok’ hai

Run Tests

Bash
npm test

Output kuch aisa hoga:

text

Code
 PASS  src/__tests__/app.test.ts
  Health Check Endpoint
    ✓ GET /health should return 200 and status ok
  GET /users
    ✓ should return empty users array

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total

🎉 Congratulations! Aapka pehla API test pass ho gaya!

5. POST Request Test – Body Validate Karein

POST endpoints ko test karna thoda interesting hai kyunki request body bhejni hoti hai aur validation check karni hoti hai।

5.1 Test Valid Data

TypeScript
describe('POST /users', () => {
  it('should create a new user with valid data', async () => {
    const newUser = {
      name: 'Rahul Kumar',
      email: 'rahul@example.com'
    };
    
    const response = await request(app)
      .post('/users')
      .send(newUser)
      .expect('Content-Type', /json/)
      .expect(201);
    
    expect(response.body).toHaveProperty('id');
    expect(response.body.name).toBe(newUser.name);
    expect(response.body.email).toBe(newUser.email);
  });
});

5.2 Test Invalid Data (Validation)

TypeScript
it('should return 400 when name is missing', async () => {
  const invalidUser = { email: 'test@example.com' };
  
  const response = await request(app)
    .post('/users')
    .send(invalidUser)
    .expect(400);
  
  expect(response.body).toHaveProperty('error');
  expect(response.body.error).toContain('Name');
});

it('should return 400 when email is missing', async () => {
  const invalidUser = { name: 'Test User' };
  
  const response = await request(app)
    .post('/users')
    .send(invalidUser)
    .expect(400);
  
  expect(response.body.error).toContain('email');
});

5.3 Supertest Chaining Explained

Supertest allows chaining methods for complex requests:

TypeScript
await request(app)
  .post('/users')
  .set('Authorization', 'Bearer token123')  // Header set
  .send({ name: 'John', email: 'john@example.com' })  // Body
  .expect(201)
  .expect('Content-Type', /json/);

6. Async Testing – await aur try/catch ke saath

Jab aap multiple async operations handle kar rahe ho, tab async/await aur try/catch use karna chahiye。

6.1 Basic Async Test

Jab Supertest promises return karta hai, to await use karna best practice hai:

TypeScript
it('should handle async operations correctly', async () => {
  try {
    const response = await request(app).get('/users');
    expect(response.status).toBe(200);
  } catch (error) {
    throw new Error(`Test failed: ${error}`);
  }
});

6.2 Testing Async Error Scenarios

TypeScript
it('should handle 404 for non-existent route', async () => {
  const response = await request(app).get('/non-existent-route');
  expect(response.status).toBe(404);
});

6.3 Testing Database Operations (Mocked)

TypeScript
// Mock database function
jest.mock('../db', () => ({
  getUsers: jest.fn().mockResolvedValue([{ id: 1, name: 'Test' }])
}));

it('should fetch users from database', async () => {
  const response = await request(app).get('/users');
  expect(response.status).toBe(200);
  expect(response.body.users).toHaveLength(1);
});

💡 Pro Tip: Tests ko isolated rakho – ek test doosre test ke result par depend nahi hona chahiye। Use beforeEach and afterEach hooks to reset state before each test।

6.4 Jest Hooks for Test Setup

TypeScript
beforeEach(() => {
  // Runs before each test – reset database, clear mocks
  jest.clearAllMocks();
});

afterEach(() => {
  // Runs after each test – cleanup
});

beforeAll(() => {
  // Runs once before all tests – connect to test database
});

afterAll(() => {
  // Runs once after all tests – disconnect database
});

7. Mocking Dependencies – Database aur External APIs

Real APIs mein external dependencies hoti hain – database, third-party APIs, file system। Tests mein hum unhe mock karte hain taaki tests fast aur predictable rahein।

7.1 Jest Mocking Basics

TypeScript
// Mock an entire module
jest.mock('../database', () => ({
  createUser: jest.fn(),
  findUser: jest.fn(),
}));

// Mock a function
const mockCreateUser = jest.fn();
mockCreateUser.mockResolvedValue({ id: 1, name: 'Test User' });

7.2 Mocking Database in Integration Tests

TypeScript
// db.ts
export const db = {
  users: [] as any[],
  saveUser: (user: any) => {
    db.users.push(user);
    return { id: Date.now(), ...user };
  }
};

// app.test.ts
import { db } from '../db';

// Mock db before tests
jest.mock('../db', () => ({
  db: {
    users: [],
    saveUser: jest.fn().mockImplementation((user) => ({
      id: 999,
      ...user
    }))
  }
}));

7.3 Mocking External API Calls

Suppose aapka API kisi third-party weather API ko call karta hai – aap usse mock kar sakte ho:

TypeScript
// Mock fetch globally
global.fetch = jest.fn();

beforeEach(() => {
  (global.fetch as jest.Mock).mockClear();
});

it('should return weather data', async () => {
  // Mock successful response
  (global.fetch as jest.Mock).mockResolvedValue({
    ok: true,
    json: async () => ({ temp: 25, condition: 'Sunny' })
  });
  
  const response = await request(app).get('/weather?city=Mumbai');
  expect(response.body).toHaveProperty('temp', 25);
});

7.4 Mocking Middleware

Middleware ko mock karna important hai jab aap auth layer skip karna chahte ho:

TypeScript
// Mock auth middleware
jest.mock('../middleware/auth', () => ({
  authenticate: (req: any, res: any, next: any) => {
    req.user = { id: '123', role: 'admin' };
    next();
  }
}));

8. Authentication Testing – JWT Token Mock Kaise Karein

APIs often have protected routes requiring authentication or specific middleware behavior। Integration tests allow you to send real HTTP requests into your API and assert against the responses – just like a real client would。

8.1 Mock JWT Verification

TypeScript
// Mock jsonwebtoken module
jest.mock('jsonwebtoken', () => ({
  verify: jest.fn().mockReturnValue({ userId: '123', email: 'test@example.com' }),
  sign: jest.fn().mockReturnValue('mocked-token')
}));

it('should access protected route with valid token', async () => {
  const response = await request(app)
    .get('/protected')
    .set('Authorization', 'Bearer any-token-will-work');
  
  expect(response.status).toBe(200);
});

8.2 Testing Protected Endpoints

TypeScript
describe('Protected endpoints', () => {
  let authToken: string;
  
  beforeAll(async () => {
    // First, get a real token via login endpoint
    const loginResponse = await request(app)
      .post('/login')
      .send({ email: 'test@example.com', password: 'password123' });
    
    authToken = loginResponse.body.token;
  });
  
  it('should access profile with valid token', async () => {
    const response = await request(app)
      .get('/profile')
      .set('Authorization', `Bearer ${authToken}`);
    
    expect(response.status).toBe(200);
    expect(response.body).toHaveProperty('email');
  });
  
  it('should return 401 without token', async () => {
    const response = await request(app).get('/profile');
    expect(response.status).toBe(401);
  });
});

8.3 Bypassing Authentication in Integration Tests

Jab aap sirf business logic test karna chahte ho, tab auth middleware bypass kar sakte ho:

TypeScript
// Create a test version of app without auth
const testApp = express();
testApp.use(express.json());

// Add mock user to request
testApp.use((req, res, next) => {
  (req as any).user = { id: 'test-user-id', role: 'admin' };
  next();
});

// Add your routes
testApp.use('/api', routes);

9. Best Practices – Production-Level Tips

✅ Name your test suites and cases clearly – describe('POST /users') and it('should return 400 when email missing')। Isse failure होने पर pata chal jaata hai kya toota hai।

✅ Use testEnvironment: "node" in Jest config – Jest defaults to jsdom (browser environment), jo Node.js globals ko sahi se handle nahi karta।

✅ Separate app and server files – app.ts exports the Express app, server.ts calls listen()। Agar listen() app mein रहता है to test files import karte time real port bind hoga।

✅ Keep tests isolated – Ek test doosre test ke result par depend nahi hona chahiye। Use beforeEach and afterEach to reset state।

✅ Mock external dependencies – Database, external APIs, file system – sabko mock karo taaki tests fast aur predictable rahein。

✅ Test both happy and unhappy paths – Success cases ke saath validation errors, 404, 401, edge cases bhi test karo।

✅ Use expect.assertions for async tests – Ensure that certain number of assertions are actually called।

✅ Run tests in CI/CD – GitHub Actions, GitLab CI, ya Jenkins mein tests automatically chalao।

✅ Maintain good test coverage (70-80%) – Not 100%, but enough to catch critical bugs।

💡 Personal Experience: 100% coverage chase karna time-wasting ho sakta hai। Focus on critical paths and error cases that actually matter to your users।

10. Resources – Cheat Sheet & Practice Prompts

Jest + Supertest Cheat Sheet

TypeScript
// Basic GET test
await request(app).get('/endpoint').expect(200);

// POST with body
await request(app)
  .post('/endpoint')
  .send({ key: 'value' })
  .expect(201)
  .expect('Content-Type', /json/);

// With headers
await request(app)
  .get('/protected')
  .set('Authorization', 'Bearer token')
  .expect(200);

// Common assertions
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('id');
expect(response.body.users).toHaveLength(3);
expect(response.body.error).toContain('required');

// Mocking
jest.mock('../module');
const mockFn = jest.fn().mockReturnValue('value');
mockFn.mockResolvedValue({ data: 'async' });

Practice Prompts

Beginner:

  • Express app banayein jisme /ping endpoint ho jo { message: 'pong' } return kare। Uska test likhein jo status 200 aur message check kare।
  • /users GET endpoint banayein jo array return kare। Test likhein jo empty array check kare।

Intermediate:

  • POST /register endpoint banayein jo username, email, password accept kare aur validation errors handle kare। Tests likhein for success case, missing fields, aur invalid email format।
  • Database layer ko mock karein aur tests likhein jo verify karein ki data sahi se save ho raha hai।

Advanced:

  • JWT authentication implement karein। Tests likhein for login (success/failure), protected routes (with/without token), token expiration scenarios।
  • Third-party API call ko mock karein (e.g., weather API)। Tests likhein for API success, API failure, and timeout scenarios।

11. FAQ

Q1: Unit test aur integration test mein kya antar hai?

Unit test – kisi ek function ya module ko isolate karke test karta hai। Integration test – multiple components (routes, controllers, database) ko saath mein test karta hai। Yeh article integration testing focus karta hai。

Q2: Supertest aur Postman mein kya antar hai?

Postman manual testing tool hai, Supertest automated testing library hai। Supertest tests code mein likhe jaate hain aur CI pipeline mein automated run ho sakte hain। Postman ki tests manual trigger karni padti hain।

Q3: testEnvironment: node kyun set karna zaroori hai?

Jest default jsdom environment use karta hai (browser simulation), jo Node.js globals ko sahi se handle nahi karta। Node.js API testing ke liye node environment set karna zaroori hai।

Q4: Tests slow ho rahe hain – kya karein?

  • Mock external dependencies (database, APIs)
  • Use --watch mode for development
  • Run tests in parallel (Jest does this by default)
  • Use in-memory database for tests

Q5: Real database ke saath tests kaise likhein?

Integration tests mein sometimes real database use karna acceptable hai। Use a test database (not development/production database), use transactions to rollback after each test, or use mongodb-memory-server for MongoDB。

Q6: CI/CD pipeline mein tests kaise run karein?

GitHub Actions mein npm test command add karo। Ensure tests don’t rely on external services that aren’t available in CI environment. Mock everything that’s not under your control.

12. Conclusion – Ab Aapki Baari!

Bahut badhiya! Aapne aaj seekh liya:

✅ API testing kya hai – manual vs automated, unit vs integration
✅ Jest vs Mocha vs Pytest – comparison and recommendation
✅ Jest & Supertest setup – Node.js + TypeScript project mein configuration
✅ Pehla test – GET request, status code, JSON validation
✅ POST request test – body validation, error cases
✅ Async testing – async/await and Jest hooks
✅ Mocking dependencies – database, external APIs, middleware
✅ Authentication testing – JWT token mock, protected routes
✅ Best practices – production-level tips

API testing is not optional anymore – it’s a necessity। Jest aur Supertest ke saath aap production-grade tests likh sakte ho jo confidence देते हैं aur bugs को early catch करते हैं।

Aapki challenge: Ek simple Task API banayein (Express + in-memory storage)। Iske liye tests likhein – GET /tasks, POST /tasks, validation errors, aur 404 scenarios। Tests pass karo aur coverage report generate karo। Apna code comment mein share karo!

Next topic kya chahiye?

  • GraphQL API Testing with Jest?
  • CI/CD Pipeline with GitHub Actions?
  • Performance Testing with k6 or Artillery?

Comment mein batao!

The Easy Master ke saath API testing seekhte raho। Happy testing! 🚀

Resources

Additional Resources

Views: 194

TheEasyMaster

Author at The Easy Master.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *