Jest Console Mocking Utility

2.0.0 · active · verified Sun Apr 19

jest-mock-console is a Jest utility designed to temporarily silence or capture console output (like `console.log`, `console.warn`, `console.error`) during unit tests. This prevents noisy test reports where successful tests might display 'red' output due to expected warnings or errors, which can obscure actual test failures. The package is currently at version 2.0.0 and is actively maintained, providing a stable solution for managing console output in Jest environments. Its key differentiators include a simple API for mocking individual or multiple console methods, the provision of a `restoreConsole()` function to revert mocks, and a convenient `setupFilesAfterEnv` integration for automatic cleanup after each test. It primarily focuses on reducing visual clutter and enabling specific assertions on console calls, making test results clearer and easier to parse.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage with `beforeEach` and `afterEach` hooks to mock and restore the console, capturing a `console.error` call and asserting its arguments.

import mockConsole from 'jest-mock-console';

describe('My Feature', () => {
  let restoreConsole: () => void;

  beforeEach(() => {
    // Mocks console.log, console.warn, and console.error by default.
    // Returns a function to restore the console to its original state.
    restoreConsole = mockConsole();
  });

  afterEach(() => {
    // It is CRITICAL to restore the console after each test to prevent Jest
    // from breaking in subsequent tests or producing unexpected behavior.
    restoreConsole();
  });

  it('should capture console.error calls without displaying them in output', () => {
    const errorMessage = 'An expected error occurred!';
    console.error(errorMessage);
    expect(console.error).toHaveBeenCalledTimes(1);
    expect(console.error).toHaveBeenCalledWith(errorMessage);
    expect(console.log).not.toHaveBeenCalled(); // Other methods are also mocked by default
  });

  it('can be configured to mock specific console methods only', () => {
    restoreConsole(); // Restore previous mock to apply a new, specific one
    restoreConsole = mockConsole(['info', 'debug']); // Only mock 'info' and 'debug'
    console.info('This is debugging information.');
    expect(console.info).toHaveBeenCalledWith('This is debugging information.');
    expect(console.warn).not.toHaveBeenCalled(); // console.warn is no longer mocked
  });
});

view raw JSON →