Posts

Showing posts from February, 2026

Mocking Unit Tests

Image
  Why I Avoid Mocking the Database in Unit Tests A green test should mean something. When a unit test mocks the database, it often doesn't. Mocks let a test pass even when the real thing is broken. That is the core problem. Here are three ways it shows up. 1. The test verifies the mock, not the code Say you replace a database call with a stub: db.select = vi.fn().mockResolvedValue([{ id: "abc" }]); Now your test proves the function called the stub in the right order. It does not prove: the SQL is valid the schema actually has that column the where clauses return the right rows on real data soft-delete or tenant filters are applied the transaction rolls back when it should a lock really prevents the race condition you added it for You get a green check that means almost nothing. 2. Mock drift: the silent decay A module mock only exposes the exports you listed when you wrote it. Months later, production code starts importing something new from the same module: a new operat...