Mock Return Values and Implementations
You'll learn how to control exactly what your mock functions return and how they behave when called during tests.
The Problem with Basic Mocks
When you create a mock with jest.fn(), it's like hiring a stunt double who just stands there. They don't do anything useful by default. To make your tests meaningful, you need to tell your mocks what values to return or what actions to perform when called.
mockReturnValue: Set a Static Return
mockReturnValue() makes your mock return the same value every time it's called:
const mockCalculate = jest.fn();
mockCalculate.mockReturnValue(42);
console.log(mockCalculate()); // 42
console.log(mockCalculate()); // 42 (always the same)
Think of it as programming a robot to always say the same thing, no matter what you ask.
mockReturnValueOnce: Sequential Returns
mockReturnValueOnce() lets you queue up different return values for successive calls:
const mockFetch = jest.fn();
mockFetch.mockReturnValueOnce('first')
.mockReturnValueOnce('second')
.mockReturnValue('default');
console.log(mockFetch()); // 'first'
console.log(mockFetch()); // 'second'
console.log(mockFetch()); // 'default'
console.log(mockFetch()); // 'default'
Perfect for testing scenarios where behavior changes over time.
mockImplementation: Full Control
mockImplementation() gives you complete control by providing an actual function body:
const mockGreet = jest.fn();
mockGreet.mockImplementation((name) => `Hello, ${name}!`);
console.log(mockGreet('Alice')); // 'Hello, Alice!'
console.log(mockGreet('Bob')); // 'Hello, Bob!'
This is like writing a full script for your stunt double instead of just telling them what to say.
Key Takeaway: Use mockReturnValue for static returns, mockReturnValueOnce for sequenced behavior, and mockImplementation when you need dynamic logic in your mocks—each gives you increasing control over how your test doubles behave.