नमस्ते दोस्तों!
स्वागत है The Easy Master पर!
आपने unit testing and basic API testing seekh liya। Lekin ab ek problem hai – aapki API database se connect hoti hai, external API (जैसे payment gateway, weather service) call karti hai। Ab aap tests kaise likhein bina real database ya external API ko hit kiye?
Jab maine pehli baar integration test likhne ki koshish ki, toh maine real database use kiya। Har test ke baad database mein junk data जमा होता गया। Tests slow थे, और kabhi kabhi वो fail ho jaate the kyunki external API down thi। Tab maine mocking seekha – aur testing fast, reliable, aur independent हो गई।
इस Integration testing Node.js Hindi article mein main aapko sikhata hoon:
✅ Integration testing kya hai? – unit vs integration vs e2e
✅ Kyun mock karein? – speed, isolation, cost
✅ Jest mocking – jest.mock(), mockImplementation, mockResolvedValue
✅ Database mock karein – MongoDB, PostgreSQL ke examples
✅ External API mock – Axios, fetch, third-party services
✅ Supertest ke saath integration tests – real HTTP requests
✅ Test database setup – in-memory MongoDB, test containers
✅ Best practices aur common mistakes
Chaliye real-world integration testing seekhte hain! 🚀
Table of Contents
1. Integration Testing Kya Hai? – Unit vs Integration vs E2E
Tests ke alag-alag levels hote hain:
| Type | What it tests | Speed | Scope |
|---|---|---|---|
| Unit test | Ek single function ya module | Very fast | Small |
| Integration test | Multiple components ka interaction (API + DB + External API) | Medium | Medium |
| E2E test | Complete user flow, browser, frontend + backend | Slow | Large |
Integration test check karta hai ki aapke modules (routes, controllers, database, external APIs) sahi se aapas mein kaam kar rahe hain ya nahीं।
Integration tests ensure that the interactions between different parts of your application (database, external services, other modules) work correctly.
Example: User registration API test – ye check karega ki:
- Request aati hai
- Validation hoti hai
- Database mein user insert hota hai
- Success response bheja jaata hai
- External email service को trigger kiya jaata hai (mock)
2. क्यों Mock करें? – Benefits of Mocking
Mocking ka matlab hai real dependency (database, external API) की जगह fake version use karna jo aap control kar sakte ho।
Benefits of mocking in integration tests:
| Benefit | Explanation |
|---|---|
| Speed | Real database या network call slow होते हैं। Mocking से tests fast (milliseconds) |
| Isolation | Tests एक दूसरे पर depend नहीं करते। Real database mein data conflict हो सकता है |
| Cost | External API calls (paid) ko mock karke unlimited times test kar sakte ho |
| Deterministic | Mock predictable response देता है। Real API kabhi up, kabhi down – test flaky |
| Edge cases | Error scenarios (timeout, 500 error) 쉽게 simulate kar sakte ho |
Mocking matlab – “Mujhe real चीज़ नहीं चाहिए, mujhe bas itna pata hai ki ये function ये return karega”
3. Jest Mocking Basics – jest.mock, mockImplementation
Jest built-in mocking provide karta hai। Let’s understand the basics.
3.1 Mock a Module
// db.js
export const getUser = (id) => { ... actual DB call };
// test.js
jest.mock('../db'); // Automatically mocks all functions
import { getUser } from '../db';
// Now getUser is a mock function
getUser.mockResolvedValue({ id: 1, name: 'Rahul' });3.2 mockImplementation – Custom Logic
const mockGetUser = jest.fn().mockImplementation((id) => {
if (id === '1') return { id: '1', name: 'Admin' };
return null;
});3.3 mockResolvedValue aur mockRejectedValue
// Success case
mockApiCall.mockResolvedValue({ data: { success: true } });
// Error case
mockApiCall.mockRejectedValue(new Error('Network failed'));3.4 Partial Mocking
Module ke kuch functions ko real rakho, kuch ko mock:
jest.mock('../db', () => ({
...jest.requireActual('../db'), // real functions
saveUser: jest.fn().mockResolvedValue({ id: 'new' }) // only mock saveUser
}));4. Database Mocking – MongoDB aur PostgreSQL Ke Saath
Database mocking ke do approaches hain:
- Mock the database layer – Fast, but doesn’t test actual queries
- Use a test database – Slower, but more realistic
Let’s cover both.
4.1 Mocking Mongoose (MongoDB ODM)
// models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: String, email: String });
module.exports = mongoose.model('User', userSchema);
// __tests__/user.test.js
jest.mock('../models/User');
const User = require('../models/User');
// Mock the save method
User.prototype.save = jest.fn().mockResolvedValue({ id: '123', name: 'Test' });
// Mock find method
User.find = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue([{ name: 'User1' }, { name: 'User2' }])
});4.2 Using MongoDB Memory Server (Realistic)
Better approach – use mongodb-memory-server for real in-memory MongoDB:
npm install --save-dev mongodb-memory-server// __tests__/db.test.js
const { MongoMemoryServer } = require('mongodb-memory-server');
const mongoose = require('mongoose');
const request = require('supertest');
const app = require('../app');
let mongoServer;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const uri = mongoServer.getUri();
await mongoose.connect(uri);
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
it('should create user in real test database', async () => {
const response = await request(app)
.post('/users')
.send({ name: 'Test', email: 'test@test.com' });
expect(response.status).toBe(201);
// Now check database directly
const user = await User.findOne({ email: 'test@test.com' });
expect(user.name).toBe('Test');
});4.3 Mocking Prisma (PostgreSQL)
// __tests__/prisma.mock.js
jest.mock('@prisma/client', () => {
return {
PrismaClient: jest.fn().mockImplementation(() => ({
user: {
findMany: jest.fn().mockResolvedValue([{ id: 1, name: 'Mock' }]),
create: jest.fn().mockResolvedValue({ id: 1, name: 'New' }),
delete: jest.fn().mockResolvedValue({ id: 1 }),
}
}))
};
});5. External API Mocking – Axios aur fetch Ke Examples
External API calls ko mock karna essential hai – kyunki aap real API पर depend nahi kar sakte।
5.1 Mocking Axios
// services/weather.js
const axios = require('axios');
const getWeather = async (city) => {
const response = await axios.get(`https://api.weather.com/${city}`);
return response.data;
};
// __tests__/weather.test.js
jest.mock('axios');
const axios = require('axios');
const { getWeather } = require('../services/weather');
it('should return weather data', async () => {
const mockWeather = { temp: 25, condition: 'Sunny' };
axios.get.mockResolvedValue({ data: mockWeather });
const result = await getWeather('Mumbai');
expect(result).toEqual(mockWeather);
expect(axios.get).toHaveBeenCalledWith('https://api.weather.com/Mumbai');
});
it('should handle API error', async () => {
axios.get.mockRejectedValue(new Error('API down'));
await expect(getWeather('Mumbai')).rejects.toThrow('API down');
});5.2 Mocking Global fetch
// __tests__/fetch.test.js
global.fetch = jest.fn();
beforeEach(() => {
fetch.mockClear();
});
it('should fetch posts', async () => {
const mockPosts = [{ id: 1, title: 'Post 1' }];
fetch.mockResolvedValue({
ok: true,
json: async () => mockPosts,
});
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
expect(data).toEqual(mockPosts);
expect(fetch).toHaveBeenCalledTimes(1);
});5.3 Mocking Specific External Service
// services/payment.js (Stripe)
const stripe = require('stripe')(process.env.STRIPE_KEY);
exports.createPayment = async (amount) => {
const paymentIntent = await stripe.paymentIntents.create({ amount, currency: 'usd' });
return paymentIntent;
};
// __tests__/payment.test.js
jest.mock('stripe', () => {
return jest.fn().mockImplementation(() => ({
paymentIntents: {
create: jest.fn().mockResolvedValue({ id: 'pi_test', amount: 100 }),
},
}));
});
const stripe = require('stripe');
const { createPayment } = require('../services/payment');
it('should create payment intent', async () => {
const result = await createPayment(100);
expect(result.id).toBe('pi_test');
});6. Supertest ke Saath Integration Tests – Real HTTP
Integration tests often use Supertest to send actual HTTP requests to your Express app, while mocking only the external dependencies.
Complete Example: User Registration API
app.js:
const express = require('express');
const app = express();
app.use(express.json());
const User = require('./models/User');
const emailService = require('./services/email');
app.post('/register', async (req, res) => {
const { name, email, password } = req.body;
if (!name || !email || !password) {
return res.status(400).json({ error: 'Missing fields' });
}
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(409).json({ error: 'Email already exists' });
}
const user = new User({ name, email, password });
await user.save();
await emailService.sendWelcomeEmail(email, name);
res.status(201).json({ id: user._id, name, email });
});
module.exports = app;__tests__/register.test.js:
const request = require('supertest');
const app = require('../app');
const User = require('../models/User');
const emailService = require('../services/email');
// Mock dependencies
jest.mock('../models/User');
jest.mock('../services/email');
describe('POST /register - Integration Test', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should register a new user successfully', async () => {
// Mock database responses
User.findOne.mockResolvedValue(null);
User.prototype.save = jest.fn().mockResolvedValue({
_id: '123',
name: 'Rahul',
email: 'rahul@example.com'
});
emailService.sendWelcomeEmail.mockResolvedValue(true);
const response = await request(app)
.post('/register')
.send({ name: 'Rahul', email: 'rahul@example.com', password: 'secret' });
expect(response.status).toBe(201);
expect(response.body).toHaveProperty('id');
expect(User.findOne).toHaveBeenCalledWith({ email: 'rahul@example.com' });
expect(emailService.sendWelcomeEmail).toHaveBeenCalledWith('rahul@example.com', 'Rahul');
});
it('should return 400 if fields missing', async () => {
const response = await request(app)
.post('/register')
.send({ name: 'Rahul' });
expect(response.status).toBe(400);
expect(response.body.error).toBe('Missing fields');
});
it('should return 409 if email already exists', async () => {
User.findOne.mockResolvedValue({ id: 'existing', email: 'rahul@example.com' });
const response = await request(app)
.post('/register')
.send({ name: 'Rahul', email: 'rahul@example.com', password: 'secret' });
expect(response.status).toBe(409);
expect(response.body.error).toBe('Email already exists');
});
});7. Test Database Setup – MongoDB Memory Server aur Testcontainers
7.1 MongoDB Memory Server (In-Memory)
// __tests__/setup.js
const { MongoMemoryServer } = require('mongodb-memory-server');
const mongoose = require('mongoose');
let mongoServer;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const uri = mongoServer.getUri();
await mongoose.connect(uri);
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
afterEach(async () => {
const collections = mongoose.connection.collections;
for (const key in collections) {
await collections[key].deleteMany();
}
});7.2 Testcontainers (Docker-based)
For PostgreSQL, MySQL, or real database features:
npm install --save-dev testcontainersconst { GenericContainer } = require('testcontainers');
let container;
beforeAll(async () => {
container = await new GenericContainer('postgres:15')
.withExposedPorts(5432)
.start();
const host = container.getHost();
const port = container.getMappedPort(5432);
process.env.DATABASE_URL = `postgresql://postgres:password@${host}:${port}/test`;
// Initialize database connection and run migrations
});
afterAll(async () => {
await container.stop();
});8. Authentication Mocking – JWT aur Session Mock
8.1 Mock JWT Verify
jest.mock('jsonwebtoken', () => ({
verify: jest.fn().mockReturnValue({ userId: 'test-user', role: 'admin' }),
sign: jest.fn().mockReturnValue('mocked-token'),
}));
// In test
const jwt = require('jsonwebtoken');
expect(jwt.verify).toHaveBeenCalled();8.2 Mock Auth Middleware in Supertest
// Override middleware in test only
app.use((req, res, next) => {
req.user = { id: 'test-id', role: 'admin' };
next();
});9. Best Practices – Production-Level Tips
✅ Mock external dependencies – Database, APIs, file system, email, queue – sabko mock करो। Tests fast और reliable rahenge।
✅ Use real test database for critical queries – Agar complex queries hai (aggregation, joins), to real test database better है (in-memory ya testcontainers)。
✅ Reset state between tests – beforeEach / afterEach hooks use karo database clean karne ke liye।
✅ Test both happy and sad paths – Success ke saath network errors, validation failures, duplicate data bhi test करो।
✅ Use jest.clearAllMocks() before each test – Mock calls aur implementations reset karne ke liye।
✅ Keep tests independent – Ek test doosre test ke data पर depend नहीं होना चाहिए।
✅ Avoid testing framework internals – Don’t test if Jest called mock correctly; test your business logic only।
✅ Run tests in CI with same mocks – Ensure CI environment has all mocks configured।
✅ Use meaningful test descriptions – it('should return 400 when email missing') not it('works')
✅ Maintain coverage but don’t obsess – 70-80% coverage is good enough। Focus on critical paths and error cases।
💡 Personal Experience: Maine ek baar real API call mock karna bhool gaya। Test सब green थे, लेकिन production mein API down hone पर pata chala। Tab maine ensure kiya ki har external dependency mock ho। Ab tests flaky nahi hote।
10. Resources – Cheat Sheet & Practice Prompts
Jest Mocking Cheat Sheet
// Mock entire module
jest.mock('../db');
// Mock with custom implementation
jest.mock('../api', () => ({
fetchData: jest.fn().mockResolvedValue({ data: 'mocked' })
}));
// Mock functions
const mockFn = jest.fn();
mockFn.mockReturnValue('sync');
mockFn.mockResolvedValue('async');
mockFn.mockRejectedValue(new Error('fail'));
// Spy on module
const spy = jest.spyOn(console, 'log');
expect(spy).toHaveBeenCalledWith('Hello');
// Clear mocks between tests
beforeEach(() => {
jest.clearAllMocks();
});Practice Prompts
Beginner:
- Simple Express API banayein jo JSONPlaceholder से posts fetch kare। Axios mock karein aur test likhein for success and error cases।
Intermediate:
- User registration API banayein with MongoDB (use mongoose)। Mongoose mock karein ya mongodb-memory-server use karein। Tests likhein for duplicate email, missing fields, success case।
Advanced:
- Payment API banayein jo Stripe API call kare। Stripe module mock karein। Write integration tests with Supertest that mock both database and Stripe। Test payment success and failure scenarios (card declined, insufficient funds) by mocking different responses।
11. FAQ
Q1: Unit test aur integration test mein kya antar hai?
Unit test – ek function ya class ko isolate karke test karta hai (mock everything around it)। Integration test – multiple components (routes, database, external API) ek saath test karta hai, but still mocks external dependencies like third-party APIs।
Q2: Real database use karna better hai ya mock?
Real database (in-memory or testcontainers) zyada realistic hota hai – actual queries test hoti hain। Mock faster hota hai। Recommendation: complex queries के लिए real test database, simple CRUD के लिए mock।
Q3: External API ko mock kaise karein bina real network call ke?
Axios ya fetch को mock karo using jest.mock()। Mock function को mockResolvedValue / mockRejectedValue provide karo। Isse network call nahi hogi।
Q4: Tests slow ho rahe hain – kya karein?
Check karo ki real database या external API call to nahi ho rahi। Mock them। Agar real database use kar rahe ho to in-memory database use karo (MongoDB Memory Server, SQLite in-memory)। Tests parallel run karo (--maxWorkers)。
Q5: CI pipeline mein tests kaise run karein?
Mocked dependencies ke saath tests fast run ho jayenge। Real database ke liye ensure CI environment mein test database available hai (GitHub Actions services feature use kar sakte ho)। MongoDB Memory Server works without external setup।
Q6: Flaky tests se kaise bachein?
Flaky tests usually asynchronous code ya un-mocked external dependencies ke karan hote hain। Ensure all async code is properly awaited। Mock all network calls। Use jest.setTimeout for long-running tests। Avoid sharing state between tests।
12. Conclusion – Ab Aapki Baari!
Bahut badhiya! Aapne aaj seekh liya:
✅ Integration testing Node.js Hindi – complete guide with mocking
✅ Unit vs integration vs E2E – difference samjhe
✅ Kyun mock karein – speed, isolation, cost benefits
✅ Jest mocking basics – jest.mock, mockImplementation, mockResolvedValue
✅ Database mocking – MongoDB (mongoose, memory-server), PostgreSQL (Prisma)
✅ External API mocking – Axios, fetch, Stripe
✅ Supertest ke saath integration tests – real HTTP requests
✅ Test database setup – MongoDB Memory Server, Testcontainers
✅ Authentication mocking – JWT, middleware
✅ Best practices aur common mistakes
Integration testing aapke application ko robust banata hai। Mocking se tests fast, reliable, aur independent rehte hain।
Aapki challenge: Ek simple Todo API banayein with Express + MongoDB (mongoose)। Write integration tests using mongodb-memory-server। Test create, read, update, delete operations। Mock external email service। Setup CI with GitHub Actions। Apna code comment mein share karo!
Next topic kya chahiye?
- End-to-end Testing with Cypress?
- Performance Testing with k6?
- Load Testing APIs with Artillery?
Comment mein batao!
The Easy Master ke saath integration testing seekhte raho। Happy testing! 🚀
Resources
- Jest Mocking Documentation
- MongoDB Memory Server
- Testcontainers for Node.js
- Supertest Documentation
- Mocking Axios with Jest (Testing Library)
Additional Resources
- MongoDB Setup – CRUD Operations समझे (Beginner Guide) 2026
- MongoDB Compass से GUI Database Manage करने का आसान तरीका | Beginner Tutorial 2026
- Node.js MongoDB Connection – Mongoose Setup समझे 2026
- MongoDB Data Modeling – Embedded Documents vs References 2026
- MongoDB Indexing – Query Speed बढ़ने करने का आसान तरीका
- MongoDB Aggregation Pipeline – Stages समझे | Practical Examples
- Express MongoDB CRUD – Complete REST API Example
- Mongoose ODM – Schema, Model, and Validation समझे 2026
- MongoDB Atlas – Cloud Database Free में Deploy करें 2026
- JWT Authentication MongoDB – User Login System कैसे बनाएं 2026
- Next.js App Router – Pages Router से क्या बदला? Complete Guide 2026
- Next.js Server Components – ‘use client’ कब और कहां Use करें
- Next.js Routing – Layouts, Dynamic Routes and Nested Routes 2026
- Next.js 16 New Features – Turbopack, Cache Components and proxy.ts
- Next.js Partial Prerendering – Static and Dynamic Content साथ में
- Next.js Authentication – JWT Session Management (App Router) 2026
- Next.js SEO – Metadata API and Image Optimization समझे 2026
- Next.js TypeScript – Full-Stack Type-Safe App कैसे बनाएं
- FastAPI Kya Hai? FastAPI Python Setup Aur Pehla API Hindi 2026
- FastAPI Path Parameters Hindi – शून्य से हीरो तक गाइड 2026
- Pydantic v2 Tutorial Hindi – Data Validation Master 2026
- FastAPI dependency injection Hindi – Code Reuse Ka Magic
- FastAPI Async Await Hindi – Non-Blocking Code 2026
- FastAPI PostgreSQL SQLModel Hindi – Async Guide 2026
- FastAPI JWT Authentication Hindi – Secure API Login
- FastAPI OpenAI Integration Hindi – AI Chatbot API 2026
- FastAPI Multi-Agent AI Hindi – LangGraph Zero to Hero
- FastAPI Deployment Hindi – Railway Zero to Hero 2026
- Docker Introduction in Hindi? Containers vs Virtual Machines
- Docker Images and Containers Hindi – Pehla Container
- Docker Compose Tutorial Hindi – Node.js + MongoDB
- Docker Volumes Networking Hindi – Data Persist कैसे करें
- Kubernetes Architecture Hindi – Pods, Nodes, Cluster
- Minikube Tutorial Hindi – Local Cluster कैसे बनाए
- Kubernetes Deployments Services Hindi – App Expose Karein
- K8s Ingress Tutorial Hindi – Domain se App Access
- Helm Kya Hai? – Kubernetes Charts Se App Deploy
- GraphQL Introduction in Hindi – REST vs GraphQL Comparison
- GraphQL Schema Tutorial Hindi – Types Queries Resolvers
- GraphQL Queries Mutations Hindi – Frontend Integration
- GraphQL Advanced Features Hindi – Fragments Aliases Variables
- Apollo Server GraphQL Node.js TypeScript Hindi – API Kaise Banaye
- Apollo Client React Hindi – GraphQL Queries Use Kaise Karein
- GraphQL Testing Supertest Hindi – Queries Mutations Test
Views: 334