0
0
ExpressHow-ToBeginner · 4 min read

How to Mock Database in Express Test: Simple Guide

To mock a database in an Express test, replace real database calls with fake functions using libraries like Sinon or Jest mocks. This lets you test your routes without needing a real database connection.
📐

Syntax

Mocking a database in Express tests usually involves these parts:

  • Import your database module: The module that handles database calls.
  • Stub or mock database methods: Replace real methods with fake ones that return test data.
  • Write tests: Use the mocked methods to test your Express routes or controllers.
javascript
import sinon from 'sinon';
import * as db from './db';

// Stub a database method
sinon.stub(db, 'getUserById').resolves({ id: 1, name: 'Test User' });

// Your test code here
// After tests, restore the stub
// sinon.restore();
💻

Example

This example shows how to mock a database call in an Express route test using Jest and supertest. The database module is mocked to return a fake user without connecting to a real database.

javascript
import request from 'supertest';
import express from 'express';
import * as db from './db';

jest.mock('./db');

const app = express();
app.get('/user/:id', async (req, res) => {
  const user = await db.getUserById(req.params.id);
  if (user) {
    res.json(user);
  } else {
    res.status(404).send('User not found');
  }
});

db.getUserById.mockImplementation(async (id) => {
  if (id === '1') return { id: 1, name: 'Mocked User' };
  return null;
});

test('GET /user/1 returns mocked user', async () => {
  const response = await request(app).get('/user/1');
  expect(response.status).toBe(200);
  expect(response.body).toEqual({ id: 1, name: 'Mocked User' });
});

test('GET /user/2 returns 404', async () => {
  const response = await request(app).get('/user/2');
  expect(response.status).toBe(404);
  expect(response.text).toBe('User not found');
});
Output
PASS GET /user/1 returns mocked user PASS GET /user/2 returns 404
⚠️

Common Pitfalls

Common mistakes when mocking databases in Express tests include:

  • Not restoring mocks or stubs after tests, causing side effects in other tests.
  • Mocking the wrong module or method, so the real database call still runs.
  • Returning incorrect or incomplete mock data that breaks the test logic.
  • Not handling asynchronous mocks properly, leading to tests that hang or fail unexpectedly.
javascript
import sinon from 'sinon';
import * as db from './db';

// Wrong: forgetting to restore stub
sinon.stub(db, 'getUserById').resolves({ id: 1, name: 'User' });

// Right: restore after test
// afterEach(() => {
//   sinon.restore();
// });
📊

Quick Reference

Tips for mocking databases in Express tests:

  • Use jest.mock() or sinon.stub() to replace database calls.
  • Always restore mocks after tests to avoid interference.
  • Return realistic mock data matching your schema.
  • Test both success and failure cases.
  • Use supertest to test Express routes easily.

Key Takeaways

Mock database calls by replacing real methods with fake ones using Jest or Sinon.
Always restore mocks after tests to keep tests isolated and reliable.
Return realistic mock data to properly test your Express routes.
Use supertest to simulate HTTP requests in your Express tests.
Test both success and error scenarios for complete coverage.