Mocking the database layer in Jest unit tests
Whether you isolate units from slow, stateful dependencies.
A live DB makes tests slow, flaky, and order-dependent; use jest.mock on the model so methods return controlled fakes.
WHAT THIS TESTS: The interviewer wants to know if you understand the difference between unit and integration tests, and whether you can deliberately sever a unit under test from its collaborators. The DB is a collaborator; the route handler is the unit.
A GOOD ANSWER COVERS: A live database introduces problems: tests become slow because of network and disk IO, they become flaky when shared state leaks between cases, they require a running server and seeded fixtures, and they couple test outcomes to test execution order. To isolate, you replace the model with a test double. In Jest you call jest.mock on the module that exports the model, then configure its methods with mockResolvedValue or mockRejectedValue to simulate found rows, empty results, and thrown errors. You then invoke the handler with fake req and res objects (or supertest) and assert on res.status and res.json. This proves the handler's branching logic, error mapping, and serialization without any database.
COMMON WRONG ANSWERS: Connecting to production or a shared dev database; spinning up a real database for what should be a fast unit test; mocking so aggressively that the handler is reduced to a pass-through and the assertion proves nothing; forgetting to clear mocks between tests so state bleeds.
LIKELY FOLLOW-UPS: When would you NOT mock and instead run a real integration test against an in-memory or containerized database? How do you reset mocks between tests with clearMocks or resetMocks? How do you assert a method was called with the right query arguments?
ONE CONCRETE EXAMPLE: For a GET /users/:id handler, jest.mock the User model, set User.findById.mockResolvedValue(null), call the handler, and assert the response is 404. Then set mockResolvedValue to a fake user and assert 200 with the serialized body. Two fast deterministic tests, zero database.
Read the original → jestjs.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.