Utility to make jest tests fail when console.error() or console.warn() are used
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.
yarn add -D jest-fail-on-console
or
npm install -D jest-fail-on-console
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,
})
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')
})
You can pass an object with options to the function:
Use this to make a test fail when a warning is logged.
- Type:
boolean
- Default:
true
Use this to make a test fail when an error is logged.
- Type:
boolean
- Default:
true
Use this to make a test fail when a message is logged.
- Type:
boolean
- Default:
false
- 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
},
})
Use this if you want to override the default error message of this library.
- Signature:
(methodName: string, bold: (string) => string) => string
Most of the logic is taken from React's setupTests file.