Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a jest config that will fail tests on console.warn?

Tags:

How do I configure jest tests to fail on warnings?

console.warn('stuff'); // fail test 
like image 408
limscoder Avatar asked Feb 19 '15 19:02

limscoder


People also ask

How do I get rid of console error in Jest?

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.

What is rootDir in Jest?

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.


2 Answers

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

like image 190
miki noidea Avatar answered Oct 10 '22 04:10

miki noidea


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();   }); }); 
like image 36
user1823021 Avatar answered Oct 10 '22 04:10

user1823021