How do I configure jest tests to fail on warnings?
console.warn('stuff'); // fail test
To disable console inside unit tests with Jest, we can use the --silent option or set the console methods to mocked functions. to run jest with the --silient to disable console output when running tests.
rootDir [string] Default: The root of the directory containing the package.json or the pwd if no package.json is found. Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.
You can use this simple override :
let error = console.error console.error = function (message) { error.apply(console, arguments) // keep default behaviour throw (message instanceof Error ? message : new Error(message)) }
You can make it available across all tests using Jest setupFiles.
In package.json
:
"jest": { "setupFiles": [ "./tests/jest.overrides.js" ] }
Then put the snippet into jest.overrides.js
I implemented this recently using jest.spyOn
introduced in v19.0.0
to mock the warn
method of console
(which is accesses via the global
context / object).
Can then expect
that the mocked warn
was not called, as shown below.
describe('A function that does something', () => { it('Should not trigger a warning', () => { var warn = jest.spyOn(global.console, 'warn'); // Do something that may trigger warning via `console.warn` doSomething(); // ... i.e. console.warn('stuff'); // Check that warn was not called (fail on warning) expect(warn).not.toHaveBeenCalled(); // Cleanup warn.mockReset(); warn.mockRestore(); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With