Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop Jest wrapping `console.log` in test output?

I'm making a Jest test with request

describe("GET /user ", () => {
    test("It should respond with a array of users", done => {
        return request(url, (err, res, body) => {
            if (err) {
                console.log(err)
            } else {
                console.log("GET on " + url);
                body = JSON.parse(body);
                expect(body.length).toBeGreaterThan(0);
                done();
            }
        })
    })
});

and it's weird because in the terminal, jest is showing console.log line as part of the output:

 ...test output...

  console.log test/modules/user.test.js:18
    GET on https://xpto/api/user

...more test output...

I need to hide the line:

console.log test/modules/user.test.js:18

How to hide console.log line in Jest output?

like image 393
Marcos Vinícius Franco Avatar asked Jun 04 '19 17:06

Marcos Vinícius Franco


Video Answer


2 Answers

You can replace Jest's console implementation with the "normal" console like this:

const jestConsole = console;

beforeEach(() => {
  global.console = require('console');
});

afterEach(() => {
  global.console = jestConsole;
});
like image 110
Andrey Vetlugin Avatar answered Sep 28 '22 08:09

Andrey Vetlugin


If it's a test you've written, why do you even need to log the error? You can rely on jest assertions for that.
If you have no other solution, you can stub out the console.log function like so:

const log = console.log;
console.log = () => {};

/** Test logic goes here **/

console.log = log; // Return things to normal so other tests aren't affected. 

like image 42
Dor Shinar Avatar answered Sep 28 '22 07:09

Dor Shinar