Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Jest `console.log` tags

Tags:

node.js

jestjs

I have some NodeJS logging done via console.log() internally (its actually loglevel) and as I see it, Jest tags console.log output with console.log ../path/to/string/with/console.log/call:line# for whatever reason:

enter image description here

I haven't found any related options in the docs. How can I disable it?

like image 285
yentsun Avatar asked Jun 20 '18 07:06

yentsun


People also ask

How do I get rid of console log from 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.

How do I cover console log in jest?

If using Jest test framework, you can turn off all console messages by one command: jest --silent .

How do I avoid console error in jest?

Here is my current approach: describe("Some description", () => { let consoleSpy; beforeEach(() => { if (typeof consoleSpy === "function") { consoleSpy. mockRestore(); } }); test("Some test that should not output errors to jest console", () => { expect. assertions(2); consoleSpy = jest.


3 Answers

IMPORTANT:

I had the curiosity to take a look to the answer mentioned in the first answer, wich it says:

Looking at the source code for Jest, it doesn't seem like there is a neat way to turn those messages off.

And I noticed an update marked on the answer and resolves the problem.

Solution:

Just add this code to your test:

beforeEach(() => {
    global.console = require('console');
  });
like image 133
Ahmad MOUSSA Avatar answered Oct 09 '22 18:10

Ahmad MOUSSA


Thanks @Anders Carstensen, I've looked at the answer you mentioned and it says:

Looking at the source code for Jest, it doesn't seem like there is a neat way to turn those messages off.

Not an option for me to write my own console, so I'll just stick with Mocha/Sinon for now.

like image 33
yentsun Avatar answered Oct 09 '22 19:10

yentsun


Create a global configuration test file e.g. src/test/config.js, add this line to that file:

jest.spyOn(console, "log").mockImplementation();

add this to jest config:

setupFilesAfterEnv: ['./src/test/config.js']

you can also use that file for global cleanup, before/after each etc

like image 37
tslalamam Avatar answered Oct 09 '22 17:10

tslalamam