Course contentsShow
← JavaScript
Lesson 2695 of 2,72354. Testing in JavaScriptFree lesson

Manual Mocks: Object Replacement

Create simple mock objects by hand to replace dependencies in tests without frameworks.

Manual Mocks: Object Replacement

You'll learn how to create simple, hand-written mock objects to replace real dependencies in your tests without using any mocking frameworks.

The Core Idea

When testing a function that depends on external objects (like a database connection, HTTP client, or file system), you don't want your tests to actually hit those real systems. Instead, you create a "fake" version of that dependency—a manual mock—that mimics only the behavior your test needs.

Think of it like a movie set: instead of filming in a real bank, you build a fake bank facade that looks real enough for the camera but costs nothing and requires no security clearance.

Creating Manual Mocks

You simply write plain JavaScript objects that have the same interface (same method names) as the real dependency, but with hardcoded or simplified behavior:

// Real dependency (in production)
const database = {
  getUser(id) {
    // actually queries database
  }
};

// Manual mock (in tests)
const mockDatabase = {
  getUser(id) {
    return { id: 123, name: 'Test User' };
  }
};

function getUserProfile(userId, db) {
  const user = db.getUser(userId);
  return `Profile: ${user.name}`;
}

// Test using the mock
const result = getUserProfile(123, mockDatabase);
// result === 'Profile: Test User'

You're literally just passing a different object that happens to have the right methods. No framework needed—just JavaScript objects doing what they do best: having properties and methods.

Key Takeaway: Manual mocks are hand-written replacement objects that mimic your dependencies' interfaces with predictable, test-friendly behavior—nothing more than plain JavaScript objects substituted where real ones would go.