Skip to content

Utility to make jest tests fail when console.error() or console.warn() are used

License

Notifications You must be signed in to change notification settings

JCB-K/jest-fail-on-console

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jest-fail-on-console

Utility to make jest tests fail when console.error() or console.warn() are used

version Monthly downloads MIT License PRs Welcome

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. image

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

shouldFailOnLog

Use this to make a test fail when a message is logged.

  • Type: boolean
  • Default: false

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.

About

Utility to make jest tests fail when console.error() or console.warn() are used

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%