Jest Fail On Console
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
-
Tests are unexpectedly failing with messages like 'A test failed due to console.error' even though I expect some console output.
cause The library's default behavior is to fail tests on `console.error` and `console.warn`. You are likely logging an error or warning that is not explicitly allowed or spied upon.fixFor expected `console.error`s or `console.warn`s, either use `jest.spyOn(console, 'error').mockImplementation()` and `expect(console.error).toHaveBeenCalledWith(...)`, or configure `failOnConsole({ allowMessage: (msg, methodName) => msg.includes('expected message') })`. -
ReferenceError: failOnConsole is not defined (or similar import errors) when running Jest tests.
cause The `failOnConsole()` function is not being imported or executed in your Jest test environment before tests run.fixEnsure you have a file configured in your `setupFilesAfterEnv` Jest option (e.g., `jest.setup.ts`) that contains `import failOnConsole from 'jest-fail-on-console'; failOnConsole();`. Verify the path in your `jest.config.js` or `jest.config.ts` matches. -
My tests are failing due to `console.log` messages, but I only want errors and warnings to fail.
cause The `shouldFailOnLog` option is likely enabled in your `failOnConsole` configuration, or a custom `allowMessage`/`silenceMessage` configuration is causing `console.log` to be treated as a failure.fixExplicitly configure `failOnConsole({ shouldFailOnLog: false })` if you want to ignore `console.log` messages and only fail on `error` or `warn`.
Warnings
- breaking Tests will fail by default for any `console.error()` or `console.warn()` calls. This can cause existing test suites to fail unexpectedly upon integration without explicit configuration.
- gotcha Jest's `injectGlobals: false` configuration can lead to compatibility issues if not properly handled by `jest-fail-on-console` versions older than `3.3.2`.
- gotcha Expected `console.error` or `console.warn` messages can still cause tests to fail unless explicitly handled, preventing legitimate error logging from being tested.
- breaking The peer dependency on `@jest/globals` requires `>=27.5.1`. Older versions of Jest or `@jest/globals` might cause installation issues or runtime errors.
Install
-
npm install jest-fail-on-console -
yarn add jest-fail-on-console -
pnpm add jest-fail-on-console
Imports
- failOnConsole
const failOnConsole = require('jest-fail-on-console')import failOnConsole from 'jest-fail-on-console'
Quickstart
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
});
});