Skip to main content

Command Palette

Search for a command to run...

JEST Mock Testing

Published
View as Markdown
  1. Introduction
    Mock testing in Jest involves creating fake versions of functions, modules, or components that simulate the behavior of real ones. This allows you to isolate the code you are testing, making it easier to test in a controlled environment.
    i) Creating Mocks

    Manual Mocks: You can manually create a mock file in a __mocks__ directory next to the module you want to mock.

    Automatic Mocks: Jest can automatically mock all the functions in a module using jest.mock('module-name').
    ii) Mock Functions

    Basic Mock Functions: You can create a basic mock function using jest.fn(). These functions can track calls, arguments, instances, and results.

    Mock Implementations: You can provide custom implementations for mock functions using mockImplementation.
    iii) Mocking Modules

    You can mock entire modules to return controlled outputs and avoid calling real implementations. This is useful for external dependencies, like APIs.
    iv) Mocking Classes

    Jest allows you to mock classes and their methods to test class-based logic in isolation.
    v) Mocking Timers

    Jest provides functions to mock and control timers (setTimeout, setInterval, etc.), allowing you to test time-dependent code.
    vi) Clearing and Resetting Mocks

    Clearing Mocks: Use mockClear to clear the call history of mock functions.

    Resetting Mocks: Use mockReset to reset all information stored in a mock, including call history and implementation.

    Restoring Mocks: Use mockRestore to restore the original implementations of mocked functions.

  2. Example
    i) Mocking a Function

     const fetchData = require('./fetchData'); // assume this fetches data from an API
    
     test('fetches successfully data from an API', async () => {
       const mockFetch = jest.fn().mockResolvedValue({ data: 'mockData' });
       fetchData.fetch = mockFetch;
    
       const data = await fetchData.fetch();
       expect(data).toEqual({ data: 'mockData' });
       expect(mockFetch).toHaveBeenCalledTimes(1);
     });
    

    ii) Mocking a Module

     jest.mock('./fetchData'); // this will create an automatic mock
    
     const fetchData = require('./fetchData');
    
     fetchData.fetch.mockResolvedValue({ data: 'mockData' });
    
     test('fetches successfully data from an API', async () => {
       const data = await fetchData.fetch();
       expect(data).toEqual({ data: 'mockData' });
       expect(fetchData.fetch).toHaveBeenCalledTimes(1);
     });
    

    iii) Mocking a Class

     const MyClass = require('./MyClass');
     jest.mock('./MyClass'); // this will mock the entire MyClass
    
     test('should call methodA of MyClass', () => {
       const mockInstance = new MyClass();
       mockInstance.methodA = jest.fn();
    
       mockInstance.methodA();
    
       expect(mockInstance.methodA).toHaveBeenCalled();
     });
    

    iv) Mocking Timers

     jest.useFakeTimers();
    
     test('should call the callback after 1 second', () => {
       const callback = jest.fn();
    
       setTimeout(callback, 1000);
    
       // Fast-forward until all timers have been executed
       jest.runAllTimers();
    
       expect(callback).toHaveBeenCalledTimes(1);
     });
    

    Mock testing with Jest provides powerful tools to ensure that your code works correctly in isolation and that dependencies do not affect the outcome of your tests.