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.
npm install jest-fail-on-consoleVerified import paths — ran on the pinned version, not inferred.
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.
Configure `jest-fail-on-console` with `shouldFailOnError: false` or `shouldFailOnWarn: false` if this behavior is not desired globally, or use `allowMessage` / `silenceMessage` for specific expected outputs. Alternatively, refactor code to avoid console calls or explicitly spy on `console` methods in tests.
Upgrade to `jest-fail-on-console@3.3.2` or higher to ensure compatibility with Jest's `injectGlobals: false` setting. Alternatively, ensure `injectGlobals` is `true` in your Jest config if possible.
For expected console output, use `jest.spyOn(console, 'error').mockImplementation()` and assert on its calls, or utilize `allowMessage` or `silenceMessage` options within `failOnConsole` to explicitly permit or suppress specific messages.
Ensure your project's Jest and `@jest/globals` versions meet the peer dependency requirement of `>=27.5.1`. Update Jest to a compatible version if necessary.
For 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') })`.Ensure 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.
Explicitly configure `failOnConsole({ shouldFailOnLog: false })` if you want to ignore `console.log` messages and only fail on `error` or `warn`.