jest: console.log does not output when running tests

Do you want to request a feature or report a bug?

Report a bug.

What is the current behavior?

Calling console.log using the default testEnvironment of jsdom doesn’t print to stdout.

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.

  1. Clone https://github.com/udbhav/jest-test
  2. Run yarn test
  3. Confirm that you’re not seeing anything from console.log
  4. Change the testEnvironment Jest configuration setting to node
  5. Re-run yarn test
  6. Confirm that you’re seeing output from console.log

What is the expected behavior?

I would expect to have console.log always output while my tests are running.

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

See package.json and yarn.lock in the repo for package versions. I’m running node 7.3.0 and yarn 0.18.1

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 230
  • Comments: 243 (40 by maintainers)

Commits related to this issue

Most upvoted comments

It seems like you updated to node 7.3. We have some fixes up for that. Please note this issue tracker is not a help forum; use stackoverflow for questions 😃

If it was working earlier today for you and isn’t any more, you must have made an update or broken something yourself. We didn’t publish a Jest release in two weeks.

I am using node v4.4.7, and as far as I’m concerned - not having anything show up to stdout when using console.log is an issue. I’m not trying to get help with coding, I’m reporting what appears to be a bug to me. The only other thing that’s changed is that I had multiple test files running before, and now only one. let me see if re-enabling the other tests makes console.log outputs appear again.

Have you tried using the jest flag --runInBand to see if that solves it by running tests serially? Somebody mentioned this to me, but haven’t had opportunity to test it.

@thisissami it seems like your test or code isn’t running then. Jest’s test suite passes on node 4 and node 6 which makes sure console printing works fine and we are working on a fix for 7.3.

--verbose=false fixed this for me as well 🎉

In my environment, I had verbose: true set in the jest options in package.json. Changing this to false (or removing it) fixed the issue for me. All my console logs show now.

This is in 18.1.

This is why I don’t like Jest. No matter what you do, they will clear your console and refuse to show any console statements, and then somehow randomly they will show up, until you have an error that you need to fix, in which case they will do their best to hide every log statement so you cannot fix it.

Why don’t you just STOP trying to hide console output from developers? If I want training wheels I’ll use Angular 1!

Adding --verbose false to package.json “test” script solved the problem for me. I would have never found that without this thread.

eg

"scripts": {
    "test": "jest --watch --verbose false"
}

After using jest for months, this happened to me as well out of the blue with node 8.9. One minute console.log was outputting just fine, the next it just stopped working. I ended up on this thread and tried a few things. Not using --watch fixed the problem, but then I had to re-run my test command each time. Using --watch --verbose false fixed the problem and would automatically run my tests.

This issue really sucks, wasting a lot of time on this issue and nothing seems to work. I picked jest because I thought Facebook engineers had a decent test suite and now this…

Still no output with --verbose=true or --verbose=false when using jest@24.8.0 - not sure why it is still an issue 3 years after it was originally logged.

The test suite of Jest tests this behavior on node 4, node 6 and node 7.3. It works for 4 and 6 but was broken in 7.3. I’m fixing this for node 7.3 and will publish a new release of Jest shortly: https://github.com/facebook/jest/pull/2464

If Jest’s own test suite using node 4 fails for you, then something is likely wrong with your setup.

Adding --verbose false fixed the problem. That seeems a bit unintuitive 😃

I’m sorry, I was having a really bad day on Friday and was frustrated. No reason to take it out on you, you’re just trying to help.

I did find the --verbose flag on Friday, which gave me enough output to fix my issues.

Again, sorry for being such a dick about it.

These just indicate you don’t have mercurial (hg) installed, unrelated to your issue. It seems like the test suite passes for you and as said; we explicitly test for the logging behavior in the test suite so it must be something going wrong with your code or setup.

–verbose=false

This worked for me.

--verbose=false fixed the issue for me when testing enzyme shallow. The console.logs were, though, working without the fix for enzyme mount.

Console output in --watch being overwritten by jest moving the cursor is consistent with what I’m seeing. Presence/absence of --verbose, --maxWorkers 1, --runInBand doesn’t produce success.

My current workaround is jest --watch | cat. I lose out on all the color and staying at the top of the window, but I get the console output.

Or, TERM=dumb jest --watch. I lose out on the staying at the top of the window, but I get color and the console output.

how is this not a major concern and not getting resolved asap? how is there is this issue open since 2016??

That’s quite aggressive @halis. We are doing this because Jest parallelizes tests and many tests may log to the terminal at the same time, meaning that Jest’s output becomes useless. We actually used to do that. If you are using --verbose, we don’t actually buffer anything and write straight to the console.

If that doesn’t work for you, maybe you can help us by sending a PR to Jest and improving this behavior.

I’m now having seeing some funky behaviour, which I cannot isolate to a simple test case yet, otherwise I’d file a new issue.

  1. Jest runs a test
  2. Jest outputs the console.log statements (don’t blink here)
  3. Jest scrolls back up an arbitrary number of lines, which sometimes covers all the console.log lines, sometimes some and sometimes all.
  4. Jest runs the next test (console.log lines from previous test disappear).

jest v18.1.0

Since I cannot isolate this in a simple test, I’m guessing it has something to do with running an more complex asynchronous test.

$ jest --verbose

this command will show all console logs

That’s great. Don’t let JavaScript tools ruin your Fridays 😀

I have not updated either (Jest 23.6.0), and running with “jest --watch --verbose=false” fixes it for me too.

Upgrade to the latest version of nodejs, please. It’s a known issue in node ~7.3.

I’m reopening this, as the issue is partially back and we need to fix it.

In v23 the problem appears in watch mode, since we’ve changed how it works under the hood to almost always run tests in parallel, so the TTY is not blocked and one can cancel long-running tests easily: https://github.com/facebook/jest/pull/6647. The only case we’re not spawning workers in watch mode is when we have exactly 1 test to run and it’s relatively fast (runs under 1s) – in this case we should still see console.logs appearing as always.

--verbose=false appears to have worked for me. Thanks!

As @bkempner said, using --watch --verbose false fixes the issue.

Shouldn’t this issue be reopened?

Does not look solved yet, even though the long discussion. The mentioned duplicate is not really one; that relates specifically to the use of --watch flag.

IMHO this issue is the main one that keeps popping out every time and that limits productivity, working with Jest.

There are so many suggested solutions but not a consistent/confirmed one. Also I can’t grasp exactly how the combinations of CLI params do influence the logging.


Why not to add a FAQ and provide a streamlined solution recommended by the authors? (possibly: a simple & compatible one)

I’m still struggling to get console.log working here. I am occasionally getting logs but there seems to be no discernable pattern for success.

I am using Jest 24.7.1 and have also tried 24.7.1 and 24.2.0-alpha.0.

Setting verbose=false and verbose=true have both failed to provide a fix.

I have also tried using node v10.8.0 and v6.17.1, also with no fix.

Is there anything missing here?

disabling verbose in the jest config worked for me 0_o\

Just confirmed with a video that the console.log is in fact being drawn to the screen for ~0.2s before being drawn over.

Running --watch without --verbose seems to fix this.

I spent 10 minutes trying to get an isolated repro case, but I can’t seem to do it. It probably only manifests with large (well, >1) test suites.

You can see the behavior here:

  • Before console.log screen shot 2017-03-29 at 3 38 51 pm

  • console.log - shown for a split second (<0.2s) screen shot 2017-03-29 at 3 39 34 pm

  • After console.log is painted over screen shot 2017-03-29 at 3 39 47 pm

What worked for me on Node 8: Instead of using console.log, use built-in debug log:

const util = require('util')
const myLogger = util.debuglog('myloggername')
myLogger('foobar')

And start jest with the debugger flag:

NODE_DEBUG=myloggername npm test -t "My Test Name"

I can’t log with any of the solutions above, but as a workaround I just get expect to fail with the value and check the diff:

expect(thingIWantToLog).toBe({})

Seems like this is still an issue, even on node 8.11.1. Maybe we should file a new bug and refer back to here?

I confirm this issue is with verbose. The issue is the line count calculation is messed up when verbose is on.

If anyone can point me to the place where it prints the message I can take a stab at it.

You can mitigate the issuing using jest-watch-toggle-config for the time being.

Set it up like this:

module.exports = {
  "watchPlugins": [
    ["jest-watch-toggle-config", { "setting": "verbose" }]
  ]
}

When you run your test, press v to enable verbose and then v again to disable it.

After that, as long as you keep verbose off, you can see all logs.

My guess is, they’re capturing the console logs because they’re trying to get asynchronous output to print in a sane order when running tests. The problem is that if this logging code doesn’t work for a user, in their environment, they’re pretty much hosed.

I stopped using jest years ago, because I couldn’t reliably get console output when debugging tests, i matter what suggestions I followed in this thread.

The moral of the story is, don’t mess with the global console. EVER. If you want to provide a logger that can be turned on or off great do that. I’ll use it if I want. But the global console should not be interfered with.

Get Outlook for iOShttps://aka.ms/o0ukef


From: earonesty notifications@github.com Sent: Wednesday, August 12, 2020 12:33:23 PM To: facebook/jest jest@noreply.github.com Cc: Chris Grimes cjg1981@live.com; Mention mention@noreply.github.com Subject: Re: [facebook/jest] console.log does not output when running tests (#2441)

jest doesn’t handle logging well on multiple levels. it should capture logs and show them on failure by default, have an option to show none at all, and have an option to show all. that’s it.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://github.com/facebook/jest/issues/2441#issuecomment-673011577, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AAFCNBK5MQEA6AJHEC52ZWDSALG6HANCNFSM4C2VWUXQ.

I had the same problem.

What worked for me was to use console.debug

I’m getting the same issue, I wonder if it’s output overwriting other output. Occasionally I’ll see something like this:

image

It’s like one process outputted an error (failed prop types) but it just gets written right over by the test output logs.

More:

image

And sometimes if I Ctrl + c while the tests are running I’ll see console logs that I wouldn’t see if I let the tests finish.

Versions Jest: 17.0.1 Node: 6.6.0 NPM: 3.10.3 macOS: 10.12.2 Terminal: 2.7.1 (and also in iTerm2 3.0.13) Script (in package.json): jest /src/main/js --watch or jest /src/main/js --coverage or jest --watch --onlyChanged all have the same behaviour.

I was seeing console logs appear sporadically when watching a single test. Sometimes I would see all logs, other times none, and other times I would see some of them but not all of them. Each time the test ran I would see something different. 😒

--verbose=false fixed it for me. I was surprised by this, because I’m not setting verbose to true anywhere. It turns out that Jest will set it to true automatically if you’re running a single test. 🙃

if there is only one test file being run it will default to true.

https://jestjs.io/docs/en/configuration#verbose-boolean

Related StackOverflow thread: https://stackoverflow.com/questions/48695717/console-log-statements-output-nothing-at-all-in-jest

I got around this issue for debugging purposes by simply putting whatever I wanted to log into a temporary expect statement. So, instead of console.log(sketchyVariable), use expect(sketchyVariable).toEqual(42).

Getting this on node v8.4.0 and Jest 21.0.0-beta.1.

When running only a single test case with test.only, console.log output doesn’t show up.

But if I remove --testPathPattern file and run all tests, output shows up.

Also, if I add await Promise.delay(100) as last step in the test, output shows up.

I’m pretty sure 90% of Jest users have no idea their code is AST-transformed to hoist mock calls, for example.

WHAT

FYI this PR fixes the problem for me - https://github.com/facebook/jest/pull/6871

Its not ready yet, it might need a change in the approach - but it does display all logged data in verbose mode.

I am also having the same issue.

Before spreading hate, @yanshuf0, consider the free and open tools you are clearly benefiting from. You chose to use Jest. If you don’t like it, you can choose to leave (or fix it yourself, the team is friendly and open to PRs).

jest ^21.2.1 and node 8.9.4

Jest still doesn’t throw console logs sometimes, --verbose option doesn’t solve problem for me. I don’t get why this issue is closed.

I have the same problem with console.log. It was working fine in v19, and I was able to see the output in the console. After upgrading to v20.0.3, the output is gone. I tried to add --runInBand or --verbose, but didn’t help.

Yeah. Im on the edge as well. It seems like its more popular here to close issue, and recommend hacks instead of fixing obvious painpoint for over 3 years.

@odykyi does not work for me. jest 22.1.0 and v8.9.4

weird behaviour. If I set verbose to false my console.log statements were printed.

For those who use ts-jest, I had to turn diagnostics off in order to see the console.logs jest.config.js

  globals: {
    'ts-jest': {
      diagnostics: false,
    },
  },

@thymikee done (though I’ve already switched to mocha – so no worries about triage)

Working on a React project I tried Jest because with Jasmine is a total quest to test HTTP calls with whatwg-fetch, Node.js execution and Babel transpilation. But when I saw that at the moment with Jest you cannot print to the console, that was a no-no to use this framework. Having the issue with Node.js 7.10 and Jest 20.0.4.

Finally I was able to set all the testing environment with Jasmine and Node.js execution by declaring xmlhttprequest on the global scope and using nock as the fake server.

Bugs can be very hard to catch and fix. But this one is a P0 reported 6 months ago that will prevent anyone to consider Jest seriously as the testing framework for any React project.

It’s worse than not showing logs:

If I have any form of error in an async test, then not only do I not see log messages, but the expect errors are also hidden, and exceptions are swallowed.

test('async', (done) => {
  setTimeout((() => {
    expect(1).toEqual(2);
    throw new Error();
    done();
  }), 1000);
});

Nowhere is my expect test displayed.

    Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
      
      at Timeout.callback [as _onTimeout] (../../../../../../../../usr/local/lib/node_modules/jest/node_modules/jsdom/lib/jsdom/browser/Window.js:523:19)
      at ontimeout (timers.js:386:14)
      at tryOnTimeout (timers.js:250:5)
      at Timer.listOnTimeout (timers.js:214:5)

Neither runInBand nor verbose:false help.

I have a trivially simple (babel-jest) config.

Ran into this as well: it seems that the “PASS: …” output is overwriting the stdout, so your “last” console.log will be eaten.

If --verbose=false doesn’t work, you can add a bunch of sacrificial newlines (\n) to your last console.log.

Thanks @jamespolanco Using the --clearCache option fixed the issue for me (for the time being). I’m going to run my tests using the --no-cache option and see if that prevents the issue from recurring in the future.

EDIT: I should have mentioned that my problem was that only some of my console.log messages were printed out. I used 5 console.log lines in one test and only the first 3 lines were printed. Using --clearCache fixed this issue for me. Maybe there is a different issue where no console.logs show up?

@mvolkmann thanks for the hint about verbose mode. If non-verbose mode is the default in jest, it might be worth it to consider a change. It doesn’t seem intuitive to me that console.logs you place in your code just don’t show up. It’s the very first and basic thing one tries when a test fails.

(node v9.3.0 and jest v20.0.4 here)

@nharrisanalyst use --verbose flag

That comment says it works on 8.1.2 but I tried that and I didn’t get it working. I already switched to mocha because this was a pretty bad bug.

@cpojer I’m not seeing any console.log output with this setup (macOS):

$ node --version
v7.4.0

Files

package.json:

{
  "dependencies": {
    "@types/jest": "19.2.4",
    "jest": "20.0.4",
    "ts-jest": "20.0.6",
    "typescript": "2.3.4"
  }
}

__tests__/jestconfig.json:

{
  "rootDir": "../",
  "globals": {
    "__TS_CONFIG__": {}
      
  },
  "moduleFileExtensions": [
    "ts",
    "tsx",
    "js",
    "jsx",
    "json"
  ],
  "transform": {
    "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
  },
  "testRegex": "__tests__/.*test_.*\\.(ts|tsx|js)$"

__tests__/test_foo.ts:

import {} from 'jest';

console.log('CONSOLE before test');
test('fail', () => {
  console.log('CONSOLE inside test');
  expect(true).toEqual(false);
  console.log('CONSOLE end of test');
})

__tests__/test_bar.js:

console.log('BAR CONSOLE before test');
test('fail', () => {
  console.log('BAR CONSOLE inside test');
  expect(true).toEqual(false);
  console.log('BAR CONSOLE end of test');
})

Output

$ jest -c __tests__/jestconfig.json 
 FAIL  __tests__/test_foo.ts
  ● fail

    expect(received).toEqual(expected)
    
    Expected value to equal:
      false
    Received:
      true
      
      at Object.<anonymous> (__tests__/test_foo.ts:6:16)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)

 FAIL  __tests__/test_bar.js
  ● fail

    expect(received).toEqual(expected)
    
    Expected value to equal:
      false
    Received:
      true
      
      at Object.<anonymous>.test (__tests__/test_bar.js:4:16)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)

Test Suites: 2 failed, 2 total
Tests:       2 failed, 2 total
Snapshots:   0 total
Time:        1.379s
Ran all test suites.

Single JS test:

$ jest -c __tests__/jestconfig.json __tests__/test_bar.js 
 FAIL  __tests__/test_bar.js
  ● fail

    expect(received).toEqual(expected)
    
    Expected value to equal:
      false
    Received:
      true
      
      at Object.<anonymous>.test (__tests__/test_bar.js:4:16)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)

  ✕ fail (7ms)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.596s, estimated 1s
Ran all test suites matching "__tests__/test_bar.js".

Single TS test:

$ jest -c __tests__/jestconfig.json __tests__/test_foo.ts 
 FAIL  __tests__/test_foo.ts
  ● fail

    expect(received).toEqual(expected)
    
    Expected value to equal:
      false
    Received:
      true
      
      at Object.<anonymous> (__tests__/test_foo.ts:6:16)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)

  ✕ fail (116ms)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        1.27s
Ran all test suites matching "__tests__/test_foo.ts".

The bail flag prevent the console logs from printing.

I’ve been struggling with this again today and the --useStderr flag fixed it for me. Thanks @diomalta!

Try using console.debug or console.error

Jest hide the logs and warnings when you pass --silent option Try yarn jest it should work

Still no output with --verbose=true or --verbose=false when using jest@24.8.0 - not sure why it is still an issue 3 years after it was originally logged.

This is my jest.config.js and it worked for me. jest -v 23.6.0 & node -v 8.11.2

module.exports = {
  clearMocks: true,
  moduleDirectories: [
    'node_modules',
  ],
  testEnvironment: 'node',
  testMatch: [
    '**/__tests__/**/*.js?(x)',
    '**/?(*.)+(spec|test).js?(x)',
  ],
  verbose: false,
};

Then in package.json I have:

"scripts": {
  "test": "jest --config ./jest.config.js",
}

Then run your specific test suite with this command:

yarn test -- -t 'test-suite-name-here'

This is my workround:

npm install --save-dev sprintf-js

In your jest setupTest.js, or where ever:

import {sprintf} from 'sprintf-js';

console.log = (msg, args) => {
    const str = sprintf(msg, args);
    process.stderr.write(str + '\n');
  };

I also see this bug, can we rep-open this issue?

I’m also experiencing this when using verbose or when in watch mode

What’s so ironic is that it’s more verbose when console.log works!

This is SO frustrating! I have the latest versions of everything and still Jest chops off console.log output at seemingly random places. This makes it very hard to debug failing tests.

I just found the answer to this! If you turn off verbose mode, all the console.log output will appear! I think when Jest outputs is verbose stuff, it writes it over the top of your output from the last few console.logs.

@cpojer Does not work on v8.0.0

As @cpojer mentioned, using the latest version of node fixes the issue.

I was having the same issue, but found that it was due to running jest via jest-cli (jest.runCLI) within gulpfile.js and it was swallowing the output of console.log. If I run jest directly I see the console output.

I’m 2 weeks into learning react and ran into this issue. I wanted to share my solution as none of the suggestions above worked for me (neither --verbose=false nor --verbose=true nor --silent=false nor any of the other combinations, even double checked that they were being set using --showConfig and --debug).

// Bypass console capture
//
const console = require('console');

test("set loading complete", async () => {
        console.log("########## Yo LOG!");
        console.debug("########## Yo DEBUG!\n\n");
        console.info("########## Yo INFO!");
        console.warn("########## Yo WARN!");
        console.error("########## Yo ERROR!");
});

It’s crude and ugly, but it works for debugging test code I’ve written. Here’s the output I get:

yarn run v1.22.5
$ node_modules/.bin/jest src/store/models/__tests__/user-test.ts
########## Yo WARN!
########## Yo ERROR!
 PASS  src/store/models/__tests__/user-test.ts
########## Yo LOG!
########## Yo DEBUG!


########## Yo INFO!

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.926 s, estimated 1 s
Ran all test suites matching /src\/store\/models\/__tests__\/user-test.ts/i.
Done in 3.50s.

jest doesn’t handle logging well on multiple levels. it should

  • capture and show all captured logs for one test on failure by default
  • have an option to show none at all, and
  • have an option to disable capture.

that’s it. not complicated really.

FYI: If I use fit to run a single test, my console.logs did not output anything. When I ran the whole suite of tests, the console.logs worked just fine.

I noticed that some console.log() where working while others didn’t in my tests (node v8, jest@23.6.0)

const something = () => new Promise(resolve => {
  console.log('NOT logged for some reason!')
  setTimeout(resolve, 100);
});

describe('Something', () => {
  it('logging works in non-async test', function () {
    console.log('logged 1')
    console.log('logged 2')
    expect(true).toBe(true);
  });

  it('console log does not work well in async test', async () => {
    console.log('logged 3')
    await something();
    console.log('NOT logged!')
    expect(true).toBe(true);
  });
});

/* Output:
> logged 1
> logged 2
> logged 3
*/

There’s something very weird going on, with async tests where the first console.log in the async test is not being logged, also the one after the await is not logged.

Add some more console.log in that async test and you’ll start notice even weirder behavior like some of the logs after the await suddenly working 🤷‍♀️ 🤷‍♂️

So, what @philwhln wrote above two years ago

Since I cannot isolate this in a simple test, I’m guessing it has something to do with running an more complex asynchronous test.

Seems to have some truth to it.

–verbose=false

Also worked for me in this case.

I think there is some code in Jest that plays a jest on us and “hijacks” console.log(), making it into a no-op, something like…

console.log = function(){ /* do nothing */}

The remedy for resetting console.log is, ironically enough – see https://stackoverflow.com/questions/7089443/restoring-console-log – to delete console.log

delete console.log
console.log("Can you hear me now, Jesters...?");

…and all of a sudden – Voila! – like a Phoenix from the flames – console.log() works again in Jest…! Jest even prints out “console.log (location info)” before logging your message…

console.log tests\lib\array-helpers.test.js:35 Can you hear me now, Jesters…?

Also, I’ve been using isomorphic “logatim” lately https://www.npmjs.com/package/logatim in lieu of console.log(), and it seems immune to Jest’s hijack attempts…(maybe it resets console.log…)

You can even pre-emptively “hijack” console.log yourself for logatim to log an “info” level message in green…

// const logatim = require('logatim') // ES5
import logatim from 'logatim' // ES6
/* ... */
console.log = function(...args){ logatim.green.info("[INFO]",...args) } // ES6

(Please don’t interpret my jocosity as bellicosity…where’s the joy in naming a fine product Jest if you can’t jest about it jest a little bit…)

Better yet, go for it! Here is my repo. https://github.com/RALifeCoach/handandfootserver.git

Run jest from npm or run from the command line. You will see that there are many, many console.logs, but most are covered up.

There - the dev team has everything they need. Please fix this issue.

On Mar 22, 2018, at 8:36 AM, Christopher Oliphant oliphant.christopher@gmail.com wrote:

It is certainly happening for me. What do you need from me so that you can fix it?

On Mar 22, 2018, at 8:32 AM, Dennis Brown <notifications@github.com mailto:notifications@github.com> wrote:

That’s true, but there still isn’t much for the devs to go on.

I found this issue most commonly within a nested asynchronous call within an async example. I’m not quite sure the case with anyone else, but showing its use of console.log would surely be helpful to resolving this.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/facebook/jest/issues/2441#issuecomment-375349444, or mute the thread https://github.com/notifications/unsubscribe-auth/ADrayIO4NBB2dZM1XL8ZQO32W9SUnu2Yks5tg8QCgaJpZM4LVbUv.

running v 22.0.4 no console.log… add this to one of many other reasons I don’t recommend jest

OK So this is still an issue for some people including myself today. I imagine it’s going to continue to be a thing.

From my testing, Jest exits the process before outputting logs meaning that it looks like the logs are being swallowed.

For me, I set verbose: true and bail: false in my jest config. Jest will continue till all tests are run and will output all errors and logs. This is favourable. I also ran --runInBand, which does the same as setting --maxWorkers=1.

The biggest help was bail: false because that allowed all tests to run till finished. It still exited with code 1 but I can see all logs again.

This problem is indeed pretty annoying as it makes it difficult/impossible to debug tests using console.log (I know… old school but still convenient). For me to use the --runInBand options made my log statements appear.

EDIT: I am pretty sure it is related to the way the result are displayed on the screen… one option would be to have a ‘dummy’ reporter which just doesn’t try fancy rendering. Another option would be to let the developer choose a reporter like mocha does.

I am experiencing the same issue, console.log is not outputting for me now (and it previously was about an hour ago). I’m using node 6.9.1 and also enabling the --forceExit flag. When I do not have this flag enabled, the console.log output appears.

However, I have another test script that utilizes the --forceExit flag and console.log appears, so I cannot say that the --forceExit flag is causing this behaviour.

As @thisissami is doing, I experience the logging issue only when I try to test a single file.

Everything passed except for these 3 tests. Not sure what implications that might have. You have all the info of what the errors related to console.log that I’m having are, as well as the image below. If that isn’t a bug in jest, then so be it. Seems weird to me though that doing nothing but following the guides would result in a scenario where I can’t see my logs when only running one test file.

screen shot 2016-12-28 at 5 55 29 pm

@jbreckmckye yeah I agree, and I’m surprised that it’s not easily available in such a widely used package and platform.

We spent quite a bit of time trying to get it to work with --useStdErr as well as many of the other suggestions here and elsewhere to no avail. But being under a time crunch, the solution above saved us.

We did indeed end up with the scenario you pointed out above and the code under test wouldn’t output anything, even though the test code would.

Our solution was to just explicitly include the import statement in that code as well. Desperate times indeed, but since our app ships with all log output stripped out anyway, it was a relatively easy choice to make. Here’s a sample of that which worked for us:

import React, { useEffect } from "react";
...

// Yuck!
var console = require('console');

const App = () => {
    // Enable native screens
    //
    enableScreens();

    console.log("What up y'all from within the App component");

    useEffect(() => {
    }, []);

    return (
        <StoreProvider store={store}>
            <StatusBar translucent backgroundColor="transparent" />
            <SafeAreaProvider>
                <AppStateListener />
                <AppContainer />
            </SafeAreaProvider>
        </StoreProvider>
    );
};

export default App;

@halis I’ve used Jest on and off for about four years and this has always been a problem. The result is that Jest tests are quite difficult to debug.

My sense is that Jest’s main play is to be happy to break expected behaviour & semantics now and then if it drastically improves the testing experience. Things like the autohoisting of jest.mock(...) mean that Jest tests aren’t strictly JavaScript (or even ECMAScript) in their semantics; likewise parallelism means that any void-returning builtin methods like console.log can and should be treated as asynchronous, if it can improve performance.

Is that a bad thing? Clearly not necessarily, as Jest is enormously successful. But I do think Jest has the capacity to surprise you once in a while. I’m pretty sure 90% of Jest users have no idea their code is AST-transformed to hoist mock calls, for example.

I was excited to finally start using jest on the backend for uniformity. Instead, I’m running into this issue and as of now am switching back to mocha/proxyquire. No console.log output visible (in modules or test cases) and after spending several hours on it, none of the workarounds seem to help. Not interested in any workarounds which involve logging to files…

Tested against node 8/10 LTS with "jest": "^24.9.0",

Have you tried using the jest flag --runInBand to see if that solves it by running tests serially? Somebody mentioned this to me, but haven’t had opportunity to test it.

Adding this flag helped sorting the problem. From time to time it was also not showing the console.log outputs. Using this command: npm test -- --verbose --runInBand -t "My Test Name"

Node and NPM versions: node v8.16.0 npm 6.4.1

i can confirm that it has not been resolved. sometimes console.log works and sometimes not, how confused me. my environment as follows: jest 23.6.0 node v8.13.0 and my jest.config.js

const path = require('path');

module.exports = {
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
    "\\.(less|css|scss)$": "<rootDir>/__mocks__/cssMock.js",
    "^@\/(.*)$": "<rootDir>/src/client/$1",
  },
  bail: true,
  setupTestFrameworkScriptFile: "<rootDir>/setupTests.js",
  collectCoverageFrom: [
    "src/client/**/*.{js,jsx}",
  ],
  verbose: true,
  coverageReporters: ["text", "text-summary", "lcov", "json"],
  coveragePathIgnorePatterns: ["src/client/index.js"],
}

@philraj we’ve switched to the beta version "24.0.0-alpha.9" at @leaplabs and it works flawlessly. In the sense that I didn’t see any logs disappear since we upgraded.

Weird how some of the last console disappears but not all of them, fixed it with --verbose false in my watch command.

Works fine when you run without --watch so it is something about the watch flag that does it.

Update: With this patch, I’m down to only 8 failing tests:

diff --git a/packages/jest-runner/src/index.js b/packages/jest-runner/src/index.js
index 2f4dd724..618a8cbf 100644
--- a/packages/jest-runner/src/index.js
+++ b/packages/jest-runner/src/index.js
@@ -97,11 +97,14 @@ class TestRunner {
     // $FlowFixMe: class object is augmented with worker when instantiating.
     const worker: WorkerInterface = new Worker(TEST_WORKER_PATH, {
       exposedMethods: ['worker'],
-      forkOptions: {stdio: 'inherit'},
+      forkOptions: {stdio: 'pipe'},
       maxRetries: 3,
       numWorkers: this._globalConfig.maxWorkers,
     });
 
+    worker.getStdout().pipe(process.stdout);
+    worker.getStderr().pipe(process.stderr);
+
     const mutex = throat(this._globalConfig.maxWorkers);
 
     // Send test suites to workers continuously instead of all at once to track
diff --git a/packages/jest-worker/src/worker.js b/packages/jest-worker/src/worker.js
index 5eee64af..17d76d36 100644
--- a/packages/jest-worker/src/worker.js
+++ b/packages/jest-worker/src/worker.js
@@ -87,6 +87,13 @@ export default class {
   }
 
   _initialize() {
+    const forceColor =
+      'FORCE_COLOR' in process.env
+        ? process.env['FORCE_COLOR']
+        : // $FlowFixMe: Does not know about isTTY
+          process.stdout.isTTY
+          ? '1'
+          : '0';
     const child = childProcess.fork(
       require.resolve('./child'),
       // $FlowFixMe: Flow does not work well with Object.assign.
@@ -94,6 +101,7 @@ export default class {
         {
           cwd: process.cwd(),
           env: Object.assign({}, process.env, {
+            FORCE_COLOR: forceColor,
             JEST_WORKER_ID: this._options.workerId,
           }),
           // Suppress --debug / --inspect flags while preserving others (like --harmony).

They are mainly about not expecting FORCE_COLORS in process.env, hg scm and packages/jest-runner/src/__tests__/test_runner.test.js not fully mocking the streams (so there are no pipe methods on them.

At this rate I’ll be able to submit a PR that fixes this next week… provided I find a fix for the log output appearing after the entire report is finished.

It’s also working from me after moving from Node.js v7.10 to v8.1.

I had this issue too, and even after reading all this thread and trying everything, I can’t get the issue fixed. My test is very simple, because I just implemented jest at my app, and even so console.log doesn’t show.

Then I tried to use winston to log at a output file and it worked. Then I tried to use winston to log at the console and, guess what, it worked!

So I suggest you guys to do the same. Check my logger.js file:

'use strict';

const winston = require('winston');

const customColors = {
  trace: 'white',
  debug: 'blue',
  info: 'green',
  warn: 'yellow',
  crit: 'red',
  error: 'red'
};

let config = {
  colors: customColors,

  levels: {
    trace: 0,
    debug: 1,
    info: 2,
    warn: 3,
    crit: 4,
    error: 5
  },
  transports: [
  ]
};

config.transports.push(
  new(winston.transports.Console)({
    name: 'consoleLogger',
    level: 'error',
    colorize: true,
    timestamp: true
  })
);

const logger = new (winston.Logger)(config);
winston.addColors(customColors);

module.exports = logger;

The in the tests files just use:

let log = require('./logger.js');
log.debug('some log here!');

I want to add myupvote to this and support what @halis has written above: Never ever mess with the global console.

I know that what jest is doing may seem “logical” if you are a real expert in coding of parallel runing asynchrounous TDD test code. But most jest users will be confused, where their log outputs are. See [1] [2] [3]

Catching console.log() in asynchrounous test is a nice idea for parallel running tests as a configuration option. But it shouldn’t be the default.

You can use --useStderr in my case solved the problem because it passes messages directly

https://nodejs.org/api/process.html#process_a_note_on_process_i_o

@ivandosreisandrade I was able to verify the runInBand flag workaround but at this time I’d rather not waste time adding the extra step for other devs, and have reverted back to something which behaves as expected out of the box. will remain subscribed to see if anything changes in this regard

TERM=dumb fixes it for me as well

I can confirm @RALifeCoach’s comment about log output being “overwritten” – I finally got the logs to show up by tagging each one with a particular string of characters (e.g. @@@) and running:

yarn test --verbose | grep '@@@'

It’s a terrible hack (you lose all console coloring, but you do still see test failures and a final test summary) but it’s the only thing that’s worked so far. I tried everything else in the comments above. Note that the --verbose arg is necessary for this solution (and it’s being implicitly combined with --watch via react-scripts).

[Using react-scripts forked to use latest Jest v23.0.0, node v8.11.2]

If six lines are written using console.log the 6 appear briefly and then the test summary overlaps some of the 6 lines.

On Sat, Apr 14, 2018, 8:58 AM Simen Bekkhus notifications@github.com wrote:

I’m not sure what you mean by overwritten. Is something output to the console then cleared?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/facebook/jest/issues/2441#issuecomment-381339074, or mute the thread https://github.com/notifications/unsubscribe-auth/ADrayF0P5SqpHjaAAYcPaIAF7ubSMVRTks5tohyIgaJpZM4LVbUv .

With Node 9.7.1, and jest 22.4.2 with babel 7 using verbose seems to work just fine for displaying console logs from within tests:

package.json

"dependencies": {
  ...
},
"jest": {
  "verbose": true
}

It’s been some time since this didn’t require user intervention, but it seems the remedy has been consistent.

I used expect(<value>).toEqual("someImpossibleValue") with bail: false to work around this when just trying to fix something broken. Definitely not ideal, but quick and dirty…

Maybe you could introduce an assume() function that’s similar to expect(), but doesn’t bail.

This is a bug in node 7.3 only. They merged a bad change and revert it for 7.4 or 7.5.

People are telling me it doesn’t work on node 8 but we have a test for this behavior and it is passing. If people would like to create a proper repro with Jest 20 and node 8, then please create an issue for that.

I feel like this is a bad bug If you have to be on a certain version for it to work. What if your system is running at 6.0 and it doesn’t work in 7.0 because of some nodejs change. Shouldn’t jest work on at least modern versions of Node? at least 5 year support? @cpojer @taion

I’ve tried 18.1.0 and it seems even buggier. And I still see things like this:

image

I can’t pick any particular pattern, but some things that have happened (I have a console.warn('----------------') in one of my components.)

  • If I’m scrolled up a bit from the bottom when I run the tests, I see the log. If I scroll down the terminal window while the tests are rolling (so that it begins auto scrolling) then when the test are finished, I scroll back up and the console.warn line is gone (presumably overwritten).
  • If I run the tests and straight away hit ctrl + c, I see some console logs. But if I do the same and don’t interrupt, those console logs aren’t visible.
  • When I run jest /src/main/js --watch once, then hit a to run again, it picks up a whole lot of legacy tests in a directory src/main/assets/legacy - not matching the glob.
  • Same as the above if I just run jest --watch (all my tests end in .test.js or .test.jsx). So hitting ‘a’ in watch mode seems to go looking everywhere, including an old jasmine test called src/test/js/spec/categoryselector/spec.js. Hitting Enter seems to do what I expect.

Could it be that all the errors thrown by missing props causes this issue? I have to keep ctrl+cing the output to try and catch these errors before they’re overwritten.

@thymikee How is this a duplicate of #2166? In this scenario, console.log outputs nothing at all. I’m having this issue with Node v4. The frustrating thing is that it was working fine earlier today, and with 0 changes to my environment, I don’t get any more console.log outputs to my terminal.

const component = shallow(…) console.log(component.debug())

You’re right @pavelloz, when you run the tests with the --runInBand option it will take more time finish the tests because it does this:

--runInBand, -i                 Run all tests serially in the current process
                                  (rather than creating a worker pool of child
                                  processes that run tests). This is sometimes
                                  useful for debugging, but such use cases are
                                  pretty rare.

So what I do is to only use that option when I need to debug an issue on a test. All other time, just run the test normally.

Cheers

It looks like the buffer for the [PASS] statement is writing over the last 2 console log lines (I can see part of the console log line number at the end of the Pass statement)

This does appear to be the case for me (jest@24.8.0). On my system the terminal output line with [PASS] appears to flash some content before its cleared.

Have you tried using the jest flag --runInBand to see if that solves it by running tests serially? Somebody mentioned this to me, but haven’t had opportunity to test it.

Thanks, It works! But why not set it default to have the output of console.log…

yeah, after remove verbose:true, it seems fine

I am having this issue in the watch mode too. Version 23.6.0

I even recorded it if anyone likes to see for themselves: asciicast

like others-it only is erased when running with --watch. Tried --verbose false and that didn’t help.

I am having this issue as well. I have tried using console.log, console.debug, and console.error. I have also tried using the --no-cache flag. In all cases, my console statement is getting completely ignored.

As per the comment by @davidgilbertson (https://github.com/facebook/jest/issues/2441#issuecomment-286248619) removing verbose: true in my package.json and removing --verbose from my command line flags allows me to view console logs that were otherwise hidden. That’s pretty confusing.

@frankred thanks. I set verbose: "false" and it works.

Sharing my observations on console.log() not showing up when running tests with Jest.

Pre-requisite for this is running Jest with --verboseflag.

If you’re running tests with multiple test files, output from console.log() is not visible (most of the time). If Jest is running tests from only one test file, console.log() works as expected.

You can workaround this issue by:

  • Run Jest tests from only 1 file. Yup…not realistic at all, so see next option.
  • Use the --maxWorkers=1 flag. Somehow, this works nicely for me. My guess(*) is…Jest runs in the same process and there is no need to buffer stdout from each process to pipe them back to the main process.

If my guess(*) is an expected behavior, I suggest updating docs to indicate it clearly to avoid developers wasting time trying to figure out “why my console.log() does not show…sometimes”.

thank you for the response but I use this flag and it only console.log() after a test has either passed or failed. so if my while loop gets stuck I can’t debug it with console.log when testing becuase the test neither passes or fails it just gets stuck in a loop.

fixed for me when updating node from 7.4.0 -> 8.2.1

I had the same problem and just tested it with the latest version of node. It works now. 💯

@marcusjwhelan Works for me on v7.10.0

very interesting behaviour, after banging my head couple of times (more like several times) figured out that --verbose is indeed the culprit to not having console.log printed out. My best solution was to create another script in package.json that doesn’t have verbose flag involved when I want some msg printed out in my console. Would really appreciate if you guys fix this soon

ok so the only thing that’s changed in my test code is that i’ve added a multiline comment after the code that’s supposed to run (as a reference for myself). I’ll see if removing that makes a difference.

Just tested this using repl.it: https://repl.it/EwfT/0

Good news is it works as expected and console.log outputs. I attempted downgrading my jest version to 17.0.3, was still seeing the same issues. Installed nvm to test with node v6.9.2, and hurray console.log works with jsdom, so I’m assuming the issue is tied to node v7.

@badiozam The problem with that approach is that it only works for logs in the test functions themselves, i.e. that have the require statement in their closures. The code under test won’t have access to that scope, unless it’s written in an IOC style allowing you to manually pass the logger in.

What we really want is a reliable, synchronous, unbuffered output to stderr and stdout. It seems like --useStdErr should fit that bill, although maybe a more obvious API could be preferable.

I was struggling with the same issue, logs weren’t showing when a test failed.

I managed to get my console.log to show by setting verbose: true in my jest.config

@ivandosreisandrade what does your package.json look like? I’m trying to follow this:

npm test – --runInBand -t “My Test Name”

But I have it setup like this in my package.json

“test:unit”: “jest --verbose”

You’d think that with the --verbose flag, it would allow a console.log to get through, but I still can’t get console.log to work. So frustrating!

@ivandosreisandrade what happens is that if there’s an error in the code (like referencing an undefined value), it won’t print out, even if the console.log call is before the error. If everything in the test passes, then I’ll see the log. That kind of behavior makes it totally useless for debugging.

I’ve tried everything in this thread and still can’t see output for console.log. --runInBand does not solve the problem for me. Using node@12 and latest jest. Debugging with web dev is hard enough, it would be really useful if I could at least print to the screen to see why my unit test is failing

Hello samlevin and pavelloz, Have you tried this option?

I’m using this command and it works: npm test -- --runInBand -t "My Test Name"

You can specify your Test Name after the -t flag to run individual tests or groups of test under the same describe(). Could you please let me know if it works? As I’ve been using it for a while now.

Here’s a screen shoot with an example code and output. NOTE that: in case you don’t know, the console.lg is printed on top of all other reports, and not at the end where you see the code coverage report or the error resume. Jest test console log

My Node and NPM versions:

node v8.16.0
npm 6.4.1

I was excited to finally start using jest on the backend for uniformity. Instead, I’m running into this issue and as of now am switching back to mocha/proxyquire. No console.log output visible (in modules or test cases) and after spending several hours on it, none of the workarounds seem to help. Not interested in any workarounds which involve logging to files…

Tested against node 8/10 LTS with "jest": "^24.9.0",

For those who use ts-jest, I had to turn diagnostics off in order to see the console.logs jest.config.js

  globals: {
    'ts-jest': {
      diagnostics: false,
    },
  },

This option didn’t work for us. We also tried setting verbose = false which didn’t help either.

Our environment:

  • Node 10.16.0
  • jest 24.8.0
  • ts-jest: 24.0.2
  • typescript 3.5.2
  • @types/jest 24.0.15

This is still an issue for me, jest@24.8.0

I found a fix actually, the last 2 lines in the last testcase (cascading up) get overriden so, make this your last test case

it('bugfix for jest@24.8.0', () => {
  console.log("jest@24.8.0 bug|last 2 lines get override. remove this once 24.8.0 gets fixed");
  console.log("jest@24.8.0 bug|last 2 lines get override. remove this once 24.8.0 gets fixed");
});

Encountering the same issue, some console logs get “eaten” up. For those having this issue, can you verify but cloning multiple console logs?

console.log('ok');
console.log('ok');
console.log('eaten up');

It looks like the buffer for the [PASS] statement is writing over the last 2 console log lines (I can see part of the console log line number at the end of the Pass statement)

@iDVB If you read the thread a couple comments above you’ll see there’s a beta version which is supposed to fix the problem. Try that and report if it solves your issue to help @spion

Also everyone who comes here to say --verbose false or --verbose true or any combination of flags or Node or Jest versions fixed their issue, please try the beta version and report if it fixes your problem without your workaround.

Is this fixed? I’m still seeing no console.logs on “jest”: “23.6.0”

This is really silly but just in case it helps anyone else, I am working on a new (to me) project - jest was running with the --silent option which disables output. Removed that and I’m seeing logs now 🤦‍♂️

@tarjei, yes:

yarn add --dev jest@beta

That suggests a difference between how the errors are logged by the react-test-renderer, versus how they’re logged by react’s builtin renderer (since enzyme doesn’t mess with console functions at all)

The problem is recurring now even though I’m not using verbose.

--runInBand doesn’t fix it for me. The only reliable workaround so far is to just log something multiple times so that some of the output isn’t overwritten by jest.

I have this problem occasionally too, I enable runInBand (https://jestjs.io/docs/en/cli.html#runinband) and that fixes it.

–watchAll flag blocked it. now it works for me

Stumbled upon this issue https://github.com/evanw/node-source-map-support/issues/207 yesterday and it seemed awfully similar to this problem here.

The reason this is problematic is because writes to process.stdout in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Calling process.exit(), however, forces the process to exit before those additional writes to stdout can be performed.

https://nodejs.org/api/process.html#process_process_exit_code

I haven’t checked the code, but if process.exit() is being used with --forceExit, it would explain why log output goes missing.

on jest@v22.4.0, node@8.9.4, and using --forceExit, i don’t see the output of console.log from my tested code unless i explicitly set verbose to false or remove the --forceExit flag (which i’m using temporarily).

Seeing exactly the same behavior as stated above. jest@v22.4.0, node@9.5.0.

console.logging before before done() is called, yet the output is not shown with --forceExit. When --forceExit is removed, the console.log output is shown at the end.

Test Suites: 1 passed, 1 total
Tests:       35 skipped, 1 passed, 36 total
Snapshots:   0 total
Time:        2.512s
Ran all test suites matching /test\/api.test.js/i.
  console.log test/api.test.js:247
    bar

So isn’t the obvious solution here to before force exiting flush whatever output buffer jest has internally?

Can anyone provide a small reproduction which fails on jest 21.2.0 and current nodes (so 4.8.4, 6.11.4 or 8.7.0)?

Jest seems to eat any console-ing I do in a setupFiles, setupTestFrameworkScriptFile, or beforeAll, making it impossible to write test setup scripts that ask for user input and validate command line flags. Happens with or without "verbose": true

I was having the same problem as in @davidgilbertson 's screenshots (test results overwriting console.log) on Jest 19.0.2 and Node 7.10.0 when running jest --verbose. What helped me: when using jest --verbose --runInBand it worked correctly (first test result, then all console.log).

@thymikee So are they going to fix this issue? I have tried everything under the sun. Still no console logs. I am using typescript and jest’s provided preprocessor. I was using ts-jest and their preprocessor worked. Is it possible it has something to do with the preprocessor?

@cpojer @lsentkiewicz Should we open a new issue since its a new issue on a new version?

Why is this issue closed? Clearly not a duplicate of #2166