Assertion Matchers for Mocks
You'll learn how to verify that your mocked functions were actually called correctly during tests.
Why Verify Mock Interactions?
Creating a mock function is only half the story. You also need to prove it was invoked as expected. Did your code call the API function? Did it pass the right arguments? How many times was it called? Assertion matchers answer these questions, turning mocks from passive stand-ins into active witnesses of your code's behavior.
Core Mock Assertion Matchers
toHaveBeenCalled() — Verifies the mock was called at least once:
const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled(); // ✓ passes
toHaveBeenCalledWith(...args) — Verifies the mock was called with specific arguments:
const mockSave = jest.fn();
mockSave('user123', { name: 'Alice' });
expect(mockSave).toHaveBeenCalledWith('user123', { name: 'Alice' }); // ✓ passes
Call count matchers — Verify exactly how many times a mock was invoked:
const mockLog = jest.fn();
mockLog('error 1');
mockLog('error 2');
expect(mockLog).toHaveBeenCalledTimes(2); // ✓ passes
Practical Pattern
These matchers work together to create complete behavioral tests:
const mockFetch = jest.fn().mockResolvedValue({ status: 200 });
await fetchUserData('user-456');
expect(mockFetch).toHaveBeenCalled();
expect(mockFetch).toHaveBeenCalledWith('/api/users/user-456');
expect(mockFetch).toHaveBeenCalledTimes(1);
Think of these matchers as reviewing security camera footage: you're checking if something happened, what exactly occurred, and how many times it repeated.
Key Takeaway: Mock assertion matchers like toHaveBeenCalled(), toHaveBeenCalledWith(), and toHaveBeenCalledTimes() verify that your code interacted with dependencies correctly, transforming mocks from simple replacements into powerful test validators.