Jest's jest.fn() for Function Mocks
You'll learn how Jest's jest.fn() creates intelligent function mocks that automatically record every detail about how they're called.
What is jest.fn()?
While manual mocks require you to build replacement objects by hand, jest.fn() creates a special mock function that acts like a spy camera—it not only stands in for the real function but also records everything: how many times it was called, what arguments were passed each time, what it returned, and more.
Think of jest.fn() like a receptionist who not only greets visitors but also keeps a detailed logbook of every interaction.
How It Works
When you create a mock with jest.fn(), you get a function you can call normally, but it comes with built-in properties that track its usage:
const mockCallback = jest.fn();
// Call it like a normal function
mockCallback('hello');
mockCallback('world', 42);
// Inspect how it was used
expect(mockCallback).toHaveBeenCalledTimes(2);
expect(mockCallback).toHaveBeenCalledWith('hello');
expect(mockCallback).toHaveBeenLastCalledWith('world', 42);
You can also control what the mock returns:
const mockFn = jest.fn().mockReturnValue(100);
const result = mockFn(); // returns 100
const mockAsync = jest.fn().mockResolvedValue('success');
const data = await mockAsync(); // returns 'success'
Why This Matters
Instead of writing custom tracking logic, jest.fn() gives you inspection superpowers out of the box. You can verify functions were called correctly without modifying your actual code or building complex manual mocks.
Key Takeaway: jest.fn() creates trackable mock functions that record calls, arguments, and return values automatically, making it easy to verify function interactions in your tests.