Skip to content
GraphQL

9. Integration Testing Node.js – Mock DB aur APIs Hindi

June 2, 2026 15 min read

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

स्वागत है 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! 🚀

1. Integration Testing Kya Hai? – Unit vs Integration vs E2E

Tests ke alag-alag levels hote hain:

TypeWhat it testsSpeedScope
Unit testEk single function ya moduleVery fastSmall
Integration testMultiple components ka interaction (API + DB + External API)MediumMedium
E2E testComplete user flow, browser, frontend + backendSlowLarge

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:

BenefitExplanation
SpeedReal database या network call slow होते हैं। Mocking से tests fast (milliseconds)
IsolationTests एक दूसरे पर depend नहीं करते। Real database mein data conflict हो सकता है
CostExternal API calls (paid) ko mock karke unlimited times test kar sakte ho
DeterministicMock predictable response देता है। Real API kabhi up, kabhi down – test flaky
Edge casesError 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

JavaScript
// 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

JavaScript
const mockGetUser = jest.fn().mockImplementation((id) => {
  if (id === '1') return { id: '1', name: 'Admin' };
  return null;
});

3.3 mockResolvedValue aur mockRejectedValue

JavaScript
// 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:

JavaScript
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:

  1. Mock the database layer – Fast, but doesn’t test actual queries
  2. Use a test database – Slower, but more realistic

Let’s cover both.

4.1 Mocking Mongoose (MongoDB ODM)

JavaScript
// 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:

Bash
npm install --save-dev mongodb-memory-server
JavaScript
// __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)

JavaScript
// __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

JavaScript
// 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

JavaScript
// __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

JavaScript
// 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:

JavaScript
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:

JavaScript
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)

JavaScript
// __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:

Bash
npm install --save-dev testcontainers
JavaScript
const { 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

JavaScript
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

JavaScript
// 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

JavaScript
// 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

Additional Resources

Views: 334

TheEasyMaster

Author at The Easy Master.

Related posts

Fetch API & REST APIs Cheat Sheet – Complete Guide in Hindi

The tutorial teaches it; the cheat sheet is for when you just need reminding.

Leave a Reply

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