Package Exports
- jest-fail-on-console
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (jest-fail-on-console) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
jest-fail-on-console
Utility to make jest tests fail when console.error() or console.warn() are used
What problem is this solving?
Jest doesn't fail the tests when there is a console.error
. In large codebase, we can end up with the test output overloaded by a lot of errors and warnings.
To prevent this, we want to fail each test that is logging an error or a warning to the console. We also want to conserve a clear output of the original error.
This is what this utility is doing.
Install
yarn add -D jest-fail-on-console
or
npm install -D jest-fail-on-console
How to use
In a file used in the setupFilesAfterEnv
option of Jest, add this code:
import failOnConsole from 'jest-fail-on-console'
failOnConsole()
// or with options:
failOnConsole({
shouldFailOnWarn: false,
})
But I have some expected console errors/warning
If a console.error()
is expected, then you should assert for it:
test('should log an error', () => {
jest.spyOn(console, 'error').mockImplementation()
// do your logic
expect(console.error).toHaveBeenCalledWith('your error message')
})
Options
You can pass an object with options to the function:
shouldFailOnWarn
Use this to make a test fail when a warning is logged.
- Type:
boolean
- Default:
true
shouldFailOnError
Use this to make a test fail when an error is logged.
- Type:
boolean
- Default:
true
silenceMessage
- Signature:
(message: string, methodName: 'warn' | 'error') => boolean
This function is called for every console warn/error. If true is returned, the message will not show in the console and the test won't fail.
Example:
failOnConsole({
silenceMessage: (errorMessage) => {
if (/Not implemented: navigation/.test(errorMessage)) {
return true
}
return false
},
})
Credits
Most of the logic is taken from React's setupTests file.