JEST Mock Testing
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 MocksManual 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 FunctionsBasic 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 ModulesYou can mock entire modules to return controlled outputs and avoid calling real implementations. This is useful for external dependencies, like APIs.
iv) Mocking ClassesJest allows you to mock classes and their methods to test class-based logic in isolation.
v) Mocking TimersJest provides functions to mock and control timers (
setTimeout,setInterval, etc.), allowing you to test time-dependent code.
vi) Clearing and Resetting MocksClearing Mocks: Use
mockClearto clear the call history of mock functions.Resetting Mocks: Use
mockResetto reset all information stored in a mock, including call history and implementation.Restoring Mocks: Use
mockRestoreto restore the original implementations of mocked functions.Example
i) Mocking a Functionconst 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.