Testing Models with Mocks
In this lesson, you will learn how to isolate your model logic by simulating database responses using mocks, ensuring your unit tests remain fast and independent of an actual database connection.
The Problem with Real Databases
When you test your model’s business logic—like a method that calculates a user’s discount based on their order history—you don’t necessarily want to query the database every time. Connecting to a database makes tests slow, fragile, and difficult to set up. If the database goes offline or the data changes, your test might fail even if your code logic is perfect.
What is a Mock?
A mock is a "fake" version of your database interaction. Instead of letting your model reach out to a real MySQL or PostgreSQL instance, you replace the database layer with an object that simply returns the data you tell it to return. This allows you to test "what happens if the database returns an empty list" or "what happens if the database throws a connection error," all without actually needing a database.
Illustrating the Concept
Imagine a method User.getActiveUsers() that fetches data from the database. Instead of running a real query, we mock the library’s find method:
// Example of mocking a database call in a test
const User = require('./models/User');
test('should filter only active users', async () => {
// We tell the model to return this fake data instead of querying SQL
const mockFind = jest.spyOn(User, 'findAll').mockResolvedValue([
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: true }
]);
const activeUsers = await User.getActiveUsers();
expect(activeUsers.length).toBe(2);
expect(mockFind).toHaveBeenCalled(); // Ensure the model actually called the DB layer
});
By intercepting the call to the ORM, we verify that our logic inside getActiveUsers() handles the incoming data correctly. This keeps your test suite focused strictly on your application's rules rather than the infrastructure.
Key Takeaway: Mocks allow you to verify your model's behavior by providing predictable, fake database responses, making your unit tests faster and more reliable.