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

How to configure jest tests to fail on warning?

console.warn('stuff');
// fail test
+7
source share
3 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 in all tests using Jest setupFiles.

In package.json:

"jest": {
    "setupFiles": [
      "./tests/jest.overrides.js"
    ]
}

Then put the fragment in jest.overrides.js

+2
source

I implemented this recently, using jest.spyOn, introduced in v19.0.0, to make fun of a method warn console(which is accessed through a context / object global).

Can make expectfun of warnas 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();
  });
});
0
source

, create-response-app, npm run eject, ./src/setupTests.js:

global.console.warn = (message) => {
  throw message
}

global.console.error = (message) => {
  throw message
}

jest , console.warn console.error.

Documents create-respond to the application - Initialization of the test environment

0
source

All Articles