Function Mocks in Jest

From the Jest cheat sheet · Mocking · verified Jul 2026

Function Mocks

Creating and using mock functions (spies)

javascript
// Create a mock function
const mockFn = jest.fn()
mockFn('arg1', 'arg2')

// Mock with return value
const mockCallback = jest.fn(x => x * 2)
expect(mockCallback(5)).toBe(10)

// Mock implementation
const mockImplementation = jest.fn()
  .mockImplementation((x) => x + 1)
  .mockImplementationOnce((x) => x + 2)  // First call only

// Assertions on mocks
expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledTimes(1)
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2')
expect(mockFn).toHaveBeenLastCalledWith('arg1', 'arg2')
💡 Use mockImplementationOnce for different behavior per call
⚡ mockClear vs mockReset vs mockRestore have different scopes
📌 Access .mock property for detailed call information
🟢 jest.spyOn preserves original implementation by default
mockingfunctions

Continue with Jest

Save the full cheat sheet or work through every related task.

More Jest tasks

Back to the full Jest cheat sheet