Jest Fail On Console

3.3.4 · active · verified Sun Apr 19

jest-fail-on-console is a utility library for Jest that enhances test suite robustness by automatically failing tests whenever `console.error()` or `console.warn()` methods are invoked during their execution. This helps developers identify and resolve unintended console output, which often indicates underlying issues or unnecessary noise in large codebases. The package is currently at version 3.3.4 and receives regular maintenance and feature updates, as evidenced by its recent patch releases addressing Jest compatibility and adding new configuration options. Its key differentiators include configurable options to fail on other console methods (`log`, `info`, `debug`, `assert`), advanced filtering with `allowMessage` and `silenceMessage` callbacks, and the ability to skip checks for specific tests, providing fine-grained control over console behavior during testing. It explicitly addresses a common pain point where Jest does not inherently fail tests for console output.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `jest-fail-on-console` into a Jest setup file, configure its options, and show examples of how it affects test outcomes, including how to handle expected console output.

import failOnConsole from 'jest-fail-on-console';

// Basic usage: fail on console.error and console.warn
failOnConsole();

// Or with options for more granular control:
failOnConsole({
  shouldFailOnWarn: false, // Don't fail on warnings
  shouldFailOnLog: true,   // Do fail on console.log
  allowMessage: (message, methodName) => {
    // Allow specific messages to pass without failing tests
    if (methodName === 'error' && message.includes('Expected error message')) {
      return true;
    }
    return false;
  },
  silenceMessage: (message) => {
    // Prevent specific messages from even showing up in the console
    if (message.includes('Ignore this log')) {
      return true;
    }
    return false;
  }
});

// Example test file (e.g., my-component.test.ts)
describe('My Component', () => {
  it('should not log errors or warnings', () => {
    // Simulate some logic that might accidentally log
    console.log('This is a log that might fail if shouldFailOnLog is true');
    console.warn('This is a warning that will fail by default');
    console.error('This is an error that will always fail by default');
    // ... your actual test logic ...
  });

  it('should handle expected errors gracefully', () => {
    // To test an expected console.error without failing the test
    const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
    console.error('Expected error message');
    expect(spy).toHaveBeenCalledWith('Expected error message');
    spy.mockRestore(); // Important to restore the spy after the test
  });
});

view raw JSON →