or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-jest-mock-console

Jest utility to mock the console

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jest-mock-console@2.0.x

To install, run

npx @tessl/cli install tessl/npm-jest-mock-console@2.0.0

index.mddocs/

Jest Mock Console

Jest Mock Console is a Jest testing utility that enables developers to mock console methods (log, warn, error) during test execution to prevent console output from cluttering test reports while still allowing verification that console methods were called with expected arguments.

Package Information

  • Package Name: jest-mock-console
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install --save-dev jest-mock-console

Core Imports

import mockConsole from "jest-mock-console";

For CommonJS:

const mockConsole = require("jest-mock-console");

With TypeScript types:

import mockConsole, { RestoreConsole } from "jest-mock-console";

Basic Usage

Manual Console Restoration

import mockConsole from "jest-mock-console";

describe("My tests", () => {
  it("should mock console output", () => {
    const restoreConsole = mockConsole();
    
    console.error("This will not show in test output");
    console.log("This will also not show");
    
    expect(console.error).toHaveBeenCalledWith("This will not show in test output");
    expect(console.log).toHaveBeenCalledWith("This will also not show");
    
    restoreConsole(); // Restore original console
  });
});

Automatic Console Restoration with Setup Framework

Jest configuration (jest.config.js):

module.exports = {
  setupFilesAfterEnv: ["jest-mock-console/dist/setupTestFramework.js"]
};

Then in tests:

import mockConsole from "jest-mock-console";

describe("My tests", () => {
  it("should mock console output", () => {
    mockConsole(); // No need to call restore function
    
    console.error("This will not show in test output");
    expect(console.error).toHaveBeenCalledWith("This will not show in test output");
    
    // Console automatically restored after each test
  });
});

Architecture

Jest Mock Console is designed to work with different Jest test runner environments:

  • Jest Globals Detection: Automatically detects if Jest globals are available and requires them if needed
  • Test Runner Compatibility: Supports both Jasmine (Jest < 27) and Circus (Jest >= 27) test runners
  • Console State Management: Preserves original console state and restores it after mocking
  • Flexible Mocking Strategy: Supports selective mocking (specific methods) or complete mocking (all console methods)

The setup test framework provides automatic console restoration by hooking into Jest's test lifecycle:

  • Jasmine Mode: Uses jasmine.getEnv().describe to inject cleanup hooks
  • Circus Mode: Decorates global describe functions and their variants (skip, only, each)
  • Lifecycle Hooks: Automatically adds beforeEach/afterEach and beforeAll/afterAll hooks for console restoration

Capabilities

Console Mocking Function

Main function that mocks console methods and returns a restore function.

/**
 * Mock console methods to prevent output during tests
 * @param mockArg - Determines which console methods to mock and how
 * @returns Function to restore original console
 */
declare function mockConsole(): RestoreConsole;
declare function mockConsole(mockArg: ConsoleProps): RestoreConsole;
declare function mockConsole(mockArg: ConsoleProps[]): RestoreConsole;
declare function mockConsole(mockArg: MockObj): RestoreConsole;

export default mockConsole;

type ConsoleProps = keyof Console;
type MockObj = {[key in ConsoleProps]?: Console[key]};
type RestoreConsole = () => void;

Parameter Options:

  • No argument: Mocks default console methods ['log', 'warn', 'error'] with jest.fn()
  • String: Mocks a single console method (e.g., 'error')
  • Array: Mocks multiple console methods (e.g., ['log', 'warn'])
  • Object: Provides custom implementations for console methods

Usage Examples:

import mockConsole from "jest-mock-console";

// Mock default methods (log, warn, error)
const restore1 = mockConsole();

// Mock only error method
const restore2 = mockConsole("error");

// Mock specific methods
const restore3 = mockConsole(["error", "warn"]);

// Custom implementations
const restore4 = mockConsole({
  error: (msg: string) => `Error: ${msg}`,
  warn: (msg: string) => `Warning: ${msg}`
});

// Always restore when done
restore1();
restore2();
restore3();
restore4();

Setup Test Framework

Automatic console restoration between tests when included in Jest configuration.

Configuration:

// jest.config.js
module.exports = {
  setupFilesAfterEnv: ["jest-mock-console/dist/setupTestFramework.js"]
};

Features:

  • Automatically restores console between it() blocks
  • Supports both Jasmine (Jest < 27) and Circus (Jest >= 27) test runners
  • Works with describe, describe.skip, describe.only, and describe.each
  • Provides beforeEach/afterEach and beforeAll/afterAll hooks for restoration

Behavior:

  • Saves original console state before each test
  • Restores console state after each test completes
  • No manual restoration required when using mockConsole()

Mock Verification

Since console methods are mocked with jest.fn(), you can use standard Jest assertions:

import mockConsole from "jest-mock-console";

describe("Console verification", () => {
  it("should verify console calls", () => {
    const restoreConsole = mockConsole();
    
    console.error("Test error message");
    console.log("Test log message");
    
    // Verify calls
    expect(console.error).toHaveBeenCalledWith("Test error message");
    expect(console.error).toHaveBeenCalledTimes(1);
    expect(console.log).toHaveBeenCalledWith("Test log message");
    
    // Verify all calls
    expect(console.error.mock.calls).toEqual([["Test error message"]]);
    
    restoreConsole();
  });
});

Types

Complete TypeScript type definitions for the package.

type DefaultConsole = Console;

type ConsoleProps = keyof DefaultConsole;

type MockObj = {[key in ConsoleProps]?: DefaultConsole[key]};

type RestoreConsole = () => void;

declare module 'jest-mock-console' {
  export default function MockConsole(): RestoreConsole;
  export default function MockConsole(mockArg: ConsoleProps): RestoreConsole;
  export default function MockConsole(mockArg: ConsoleProps[]): RestoreConsole;
  export default function MockConsole(mockArg: MockObj): RestoreConsole;
}

Common Use Cases

Preventing Console Clutter in Tests

describe("Component with console output", () => {
  it("should not clutter test output", () => {
    const restoreConsole = mockConsole();
    
    // Component that logs internally
    const component = new MyComponent();
    component.debugInfo(); // Calls console.log internally
    
    // Test passes without console output
    expect(component.isInitialized).toBe(true);
    
    restoreConsole();
  });
});

Testing Console Output

describe("Logger component", () => {
  it("should log error messages", () => {
    const restoreConsole = mockConsole(["error"]);
    
    const logger = new Logger();
    logger.error("Something went wrong");
    
    expect(console.error).toHaveBeenCalledWith("Something went wrong");
    
    restoreConsole();
  });
});

Custom Console Behavior

describe("Console redirection", () => {
  it("should redirect console to custom handler", () => {
    const logs: string[] = [];
    const restoreConsole = mockConsole({
      log: (msg: string) => logs.push(msg)
    });
    
    console.log("Test message");
    
    expect(logs).toEqual(["Test message"]);
    
    restoreConsole();
  });
});