Skip to main content

Command Palette

Search for a command to run...

JEST Mock Functions

Published
View as Markdown
  1. Introduction
    Mock functions are an essential part of testing in the Jest framework. They allow you to test the behavior of your code by simulating the behavior of real functions or modules.

    Mock functions are functions that you can use in place of real ones during testing. They can capture calls made to them, the arguments passed, the return values, and they can also provide fake implementations for the functions they mock. This is useful for isolating the code you want to test and ensuring that your tests are focused and reliable.

  2. Key Features
    i) Capturing Calls: Mock functions record all the calls made to them, including the arguments passed in each call. This allows you to make assertions about how the function was called during the test.

    ii) Return Values: You can specify the return value of a mock function for specific calls or set a default return value.

    iii) Implementations: Mock functions can be given custom implementations. This is useful when you want the mock to exhibit specific behavior based on the input.

    iv) Resetting and Clearing: You can reset or clear mock functions to remove call history and return values between tests.

  3. Creating Mock Functions
    There are a few ways to create mock functions in Jest:

    jest.fn(): This creates a new, unnamed mock function.

    jest.mock(): This is used to mock entire modules.

    jest.spyOn(): This is used to mock specific methods of existing objects.

  4. Basic Usage
    Using jest.fn()

     const myMock = jest.fn();
    
     myMock();
     myMock(1);
    
     console.log(myMock.mock.calls); 
     // Output: [ [], [1] ]
    

    Specifying Return Values

     const myMock = jest.fn().mockReturnValue('default');
    
     console.log(myMock()); // Output: 'default'
    
     myMock.mockReturnValueOnce('first call').mockReturnValueOnce('second call');
    
     console.log(myMock()); // Output: 'first call'
     console.log(myMock()); // Output: 'second call'
     console.log(myMock()); // Output: 'default'
    

    Using Custom Implementations

     const myMock = jest.fn((x, y) => x + y);
    
     console.log(myMock(1, 2)); // Output: 3
     console.log(myMock(3, 4)); // Output: 7
    
  5. Mocking Modules
    You can mock entire modules using jest.mock()

     // file: math.js
     export const add = (a, b) => a + b;
     export const subtract = (a, b) => a - b;
    
     // file: math.test.js
     import * as math from './math';
    
     jest.mock('./math');
    
     test('adds 1 + 2 to equal 3', () => {
       math.add.mockReturnValue(3);
       expect(math.add(1, 2)).toBe(3);
     });
    

    Mocking Specific Methods with jest.spyOn()

     const myObject = {
       myMethod: () => 'real implementation',
     };
    
     jest.spyOn(myObject, 'myMethod').mockImplementation(() => 'fake implementation');
    
     console.log(myObject.myMethod()); // Output: 'fake implementation'
    
  6. Resetting and Clearing Mocks
    To clear mock calls and instances

     const myMock = jest.fn();
    
     myMock();
     expect(myMock).toHaveBeenCalledTimes(1);
    
     myMock.mockClear(); 
     expect(myMock).toHaveBeenCalledTimes(0);
    

    To reset mock implementations

     const myMock = jest.fn().mockImplementation(() => 'default');
    
     myMock();
     expect(myMock()).toBe('default');
    
     myMock.mockReset();
     expect(myMock()).toBeUndefined();
    

    Mock functions are a powerful tool in Jest that enable you to write comprehensive tests by isolating the code you want to test. They help you verify that functions are called with the correct arguments, return the expected values, and can be reset between tests to ensure clean test environments.