JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
Next
testing
mid
mocking

How do you mock functions, modules, and API calls in Jest?

mocking
jest.fn
jest.mock
spyOn
isolation
Quick Answer

Jest provides jest.fn() for mock functions, jest.mock() for modules, and jest.spyOn() for spying on methods. For API calls, mock fetch/axios or use libraries like MSW. Mocks isolate code under test and allow controlling dependencies.

Detailed Explanation

Mock Types:

  1. jest.fn(): Create mock function

    • Track calls and arguments
    • Control return values
    • Implement custom behavior
  2. jest.mock(): Mock entire module

    • Auto-mock all exports
    • Provide manual implementation
    • Hoisted to top of file
  3. jest.spyOn(): Spy on existing method

    • Watch method calls
    • Optionally mock implementation
    • Restore original afterward

API Mocking:

  • Mock fetch globally
  • Mock axios module
  • Use MSW for realistic API mocking

Code Examples

Mock functions (jest.fn)
describe('Mock functions', () => {
  test('basic mock function', () => {
    const mockFn = jest.fn();
    
    mockFn('hello');
    mockFn('world');
    
    expect(mockFn).toHaveBeenCalledTimes(2);
    expect(mockFn).toHaveBeenCalledWith('hello');
    expect(mockFn).toHaveBeenLastCalledWith('world');
  });

  test('mock with return value', () => {
    const mockFn = jest.fn()
      .mockReturnValue('default')
      .mockReturnValueOnce('first')
      .mockReturnValueOnce('second');
    
    expect(mockFn()).toBe('first');
    expect(mockFn()).toBe('second');
    expect(mockFn()).toBe('default');
  });

  test('mock with implementation', () => {
    const mockFn = jest.fn((x) => x * 2);
    
    expect(mockFn(5)).toBe(10);
    expect(mockFn).toHaveBeenCalledWith(5);
  });

  test('mock async function', async () => {
    const mockFn = jest.fn().mockResolvedValue({ id: 1, name: 'Alice' });
    
    const result = await mockFn();
    expect(result.name).toBe('Alice');
  });
});

Resources

Jest - Mock Functions

docs

MSW - Mock Service Worker

docs

Related Questions

How do you test asynchronous code in Jest?

junior
async

How do you test React components with React Testing Library?

mid
react-testing-library
Next
How do you test React components with React Testing Library?