Mocking Functions
Mocking is one of those things that sounds scary until someone explains it simply. Think of a mock as a stand-in actor. It pretends to be the real thing so you can test your code without dealing with the real thing.
Why would you do this? Because you do not want your unit tests hitting a real database or calling a real API. That would be slow, unpredictable, and expensive.
Creating a Mock Function
jest.fn() creates a fake function that you control. You decide what it returns and what arguments it receives.
const mockCallback = jest.fn();
mockCallback('hello');
expect(mockCallback).toHaveBeenCalledTimes(1);
expect(mockCallback).toHaveBeenCalledWith('hello');
See that? You created a function, called it once, and then checked that it was called with the right arguments. That is mocking in a nutshell.
Mock Return Values
You can tell your mock what to return. This is how you control the behavior of dependencies.
const mockFetch = jest.fn()
.mockReturnValue({ name: 'Alice' })
.mockReturnValueOnce({ name: 'Bob' });
it('returns different values', () => {
expect(mockFetch()).toEqual({ name: 'Bob' });
expect(mockFetch()).toEqual({ name: 'Alice' });
expect(mockFetch()).toEqual({ name: 'Alice' });
});
Mock Implementations
For more complex behavior, use mockImplementation. It lets you write actual logic inside your mock.
const mockAdd = jest.fn((a, b) => a + b);
expect(mockAdd(2, 3)).toBe(5);
expect(mockAdd).toHaveBeenCalledTimes(1);
Clearing Mocks
Between tests, you often want to reset your mocks. Jest makes this easy.
const mockFn = jest.fn();
beforeEach(() => {
mockFn.mockClear();
});
it('first test', () => {
mockFn('a');
expect(mockFn).toHaveBeenCalledTimes(1);
});
it('second test', () => {
expect(mockFn).toHaveBeenCalledTimes(0);
});
Try it Yourself →
Key Takeaways
- jest.fn() creates a mock function you fully control
- mockReturnValue sets what the mock returns
- mockReturnValueOnce sets a one-time return value
- mockImplementation lets you write custom logic in your mock
- Clear mocks between tests to avoid contamination