Do you want to request a feature or report a bug?
feature
What is the current behavior?
Due to the BufferedConsole
, it's impossible to overwrite console.error
, console.log
, console.warn
and console.info
.
Use Case: We'd like to be able to have console.error
and console.warn
throw errors and fail tests.
If the current behavior is a bug, please provide the steps to reproduce and either a repl.it demo through https://repl.it/languages/jest or a minimal repository on GitHub that we can yarn install
and yarn test
.
What is the expected behavior?
I expect that if I add console.error = (message) => { throw new Error(message); };
(globally, in a test, or in setupFiles/setupFramework), that any time console.error
is called in a test it would throw an error and fail a test.
In reality, nothing happens.
Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.
N/A
Use mocking function jest.fn()
:
console.warn = jest.fn(warn => {
throw new Error(warn);
});
@thymikee This isn't working as expected either, using a global setup file:
in "setupTestFrameworkScriptFile": "<rootDir>/tools/jest/setup-framework.js"
beforeEach(() => {
console.error = jest.fn((error) => {
throw new Error(error);
});
});
In test:
const somePromiseThatLogsConsoleError = () => {
return new Promise((resolve, reject) => {
console.error('foobar');
resolve();
});
});
it('test that has console.error', () => {
return somePromiseThatLogsConsoleError().then(() => {
expect(false).toBeTrue();
});
});
i just tried it and it worked:
// test file
test('lol', () => {
return new Promise((resolve) => {
console.log('lol');
resolve();
});
});
// setup file
global.console.log = () => {
throw new Error('hey!');
};
result:
__tests__/test-test.js
✕ lol (3ms)
● lol
hey!
at CustomConsole.Object.<anonymous>.global.console.log (setup.js:2:9)
at resolve (__tests__/test-test.js:3:13)
at Object.<anonymous>.test (__tests__/test-test.js:2:10)
at process._tickCallback (internal/process/next_tick.js:109:7)
Test Summary
› Ran all tests.
› 1 test failed, 0 tests passed (1 total in 1 test suite, run time 0.661s)
Most helpful comment
Use mocking function
jest.fn()
: