Created
December 24, 2018 00:02
-
-
Save agwells/ea40ecc513c1ecfe11c2331fd778ca26 to your computer and use it in GitHub Desktop.
Make Jest tests fail if tests emit any console messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Fail the test if it prints ANYTHING to the console! | |
// | |
// Warning & log messages in test output are an anti-pattern. Also, testing | |
// for console messages is the only way to check for PropTypes failures | |
// (because all PropTypes does is print a console warning) | |
const realConsole = global.console; | |
// TODO: It's possible that some of the functions under global.console may | |
// have legitimate uses during test runs. If so, we'll need to be more picky. | |
global.console = Object.keys(realConsole).reduce( | |
(acc, consoleFunctionName) => ({ | |
...acc, | |
[consoleFunctionName]: (...args) => { | |
realConsole[consoleFunctionName](args); | |
// expect().alwaysFail() is a custom Jest matcher that automatically fails. | |
// It's at the end of this file. | |
expect(args).alwaysFail( | |
`Test invoked "console.${consoleFunctionName}()"! Tests should NOT emit messages to the console. >:(` | |
); | |
}, | |
}), | |
{} | |
); | |
// A custom Jest matcher to force a failure and print an informative message | |
// about it. | |
expect.extend({ | |
alwaysFail(received, failureMessage) { | |
return { | |
pass: false, | |
message: () => | |
failureMessage + | |
(received ? '\n\nDetails:\n' + this.utils.printReceived(received) : ''), | |
}; | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment