Jest: console.log does not output when running tests

Created on 25 Dec 2016  ·  236Comments  ·  Source: facebook/jest

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

Most helpful comment

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.

All 236 comments

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.

Thanks for reporting this, but that's a duplicate of #2166 and happens on Node 6 too.

@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.

@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.

@cpojer - My tests pass/fail properly - just console.log messages do not show up. I discovered this when trying to figure out what the properties of a particular object are by console.loging it, and seeing no output. I've added many console.log statements and none are showing up in my terminal now. =/ I'm currently reverting to Jest v17 to see if that changes anything.

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.

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.

@cpojer I don't know what to say, I don't see anything wrong in my test code but nothing is being outputted to stdout:

import React from 'react';
import {shallow} from 'enzyme';
import FundPercentage from '../../src/reactClasses/fund_percentage';

console.log('cmon');
describe('Normal Percentage', () => {
  console.log('do this');
  const percentage1 = shallow(
    <FundPercentage percentage={0.5}/>
  );
  const percentage2 = shallow(
    <FundPercentage percentage={0.26}/>
  );
  it('should work', () => {
    console.log(percentage1.childAt(0));
    expect(0).toBe(1);
  });
});

The test fails, as expected, so I know it's working. My config in package.json is really simple, solely:

  "jest": {
    "collectCoverageFrom": [
      "src/*.jsx"
    ]
  }

Jest ran totally normally, no extra flags attached. Same issue with Jest v17 & 18.

I haven't changed any files other than this one in the entire afternoon. I've just been getting to understand how enzyme works by outputting various things to stdout, and after beginning to add in some expects, the console.logs stopped working when I needed them again, and now they don't work at all - no matter what I have in the test. I haven't changed anything in my environment either (beyond downgrading just now to v17), which is certainly confusing.

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 :)

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.

@cpojer Fairly certain you guys have a bug here.

Having 3 tests run (as in 3 different files with .test.js, with 2 of those files being examples from your tutorials) works without issue. My test (copied above) renders all the console.logs.

Having just 1 test run (AKA me renaming .test.js to .teast.js on 2 of the files) results in no console.log outputs being rendered.

I'm gonna keep running a second arbitrary test so that I see the output I need, so I'm good for my own personal needs - but this should be addressed imo, assuming it's reproducable elsewhere.

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.

Cloning the repository and giving it a try now.

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

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.

Ok cool - thanks for your feedback. Do you have any inkling as to what could be causing it to work when there are multiple files but not when there is only 1? If there's no obvious "oh this sometimes causes an issue like that" that comes to your mind - no worries, I'll just ensure that there's always at least 2 files running. :)

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.

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 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.

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.

@davidgilbertson does it happen on v18.1?

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.

Not working for me either (jest 19.0.1, node 5.12). Interestingly it does work on another project with same setup. Not sure how to debug Jest tests so being able to see some console messages would be quite important I think.

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.

The bail flag prevent the console logs from printing.

I will try. The slightly unnerving thing is that in the same project some console log statements are being output on the console, some aren't. Unfortunately the ones I tried to add where a test case is failing doesn't get output (I tried to add everywhere in the test case, in the unit tested, etc to no avail). So I don't actually think this can be down to a flag, as the behaviour is not concise. It's a react native project, following standard layout btw.

None of this seems to help. The --bail flag just stops other tests from being run (the offending one is last one anyway in my case), and --runInBands doesn't seem to have any observable difference. Jest does run the updated files btw, so if I insert a console.log statement, the error stack trace shows the error coming from the updated line number. It's just the console log doesn't happen. Since it's hard/impossible to debug these tests in a browser (pls correct me if this is not the case) console.log is absolutely vital to fix some issues in the tests.

It seems that this test case wasn't being run actually. There was a TypeError (accessing a property on an undefined). What mislead me is that I actually saw the stack trace on the console, which sort of suggests that it's being executed. So seeing the trace but not seeing the log message didn't quite add up :) Does anyone know why it's done this way, so if a test fails with a runtime error, logs aren't output as it seems? (Just to be clear I mean logs that have happened until the point of error, I obviously don't mean logs after the error :))

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.

For anyone else running into this issue, check any recently added dependencies. I started running into issues after adding mock-browser in an attempt to mock browser objects. Apparently it replaces global with its own object.

package.json (jest config)

"jest": {
    "testEnvironment": "node",
    "moduleFileExtensions": [
        "js",
        "json"
    ],
    "moduleDirectories": [
        "node_modules",
        "src"
    ],
    "transform": {
        "^.+\\.js$": "babel-jest"
    },
    "roots": [
        "<rootDir>/__test__"
    ],
    "setupFiles": [
        "<rootDir>/__test__/test-setup.js"
    ],
    "moduleNameMapper": {
        "client": "<rootDir>/src/client",
        "common": "<rootDir>/src/common",
        "server": "<rootDir>/src/server",
        "!CONFIG": "<rootDir>/config/env/test.js",
        "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/file.js",
        "\\.(css|less)$": "identity-obj-proxy"
    }
}

test-setup.js

const mockBrowser = require('mock-browser').mocks.MockBrowser;

const MockBrowser = new mockBrowser();
global.APP_CONFIG = require('!CONFIG').default;

global.__DEVELOPMENT__ = false;
global.__TESTING__ = true;
global.__PRODUCTION__ = false;
global.document = MockBrowser.createDocument();
global.window = MockBrowser.createWindow();
global.localStorage = MockBrowser.getLocalStorage();

test-setup.js
Commenting out the mock-browser bits...

// const mockBrowser = require('mock-browser').mocks.MockBrowser;

// const MockBrowser = new mockBrowser();
global.APP_CONFIG = require('!CONFIG').default;

global.__DEVELOPMENT__ = false;
global.__TESTING__ = true;
global.__PRODUCTION__ = false;
// global.document = MockBrowser.createDocument();
// global.window = MockBrowser.createWindow();
// global.localStorage = MockBrowser.getLocalStorage();

console.log works fine.

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

I'll add my $0.02 because I just ran into this.

Issue:

  • I am running jest --watch --verbose (v19.0.2)
  • Some (but not all!) console.log statements do not appear, neither during test run, or in the summary
  • In my case, I can isolate it to a _.reduce call: all console.log statements inside this block are not shown, console.log statements outside the reduce block are shown. I've verified by other means (coverage, test results) that the reducer body is in fact being called. This is weird since I'm not doing anything async/promise based in this part of the code, I can't fathom why the reduce call would affect anything.
  • If I invoke jest with --runInBand, I see all the console.log statements.
  • Unlike most previous reports I am running with "testEnvironment": "node", not jsdom

The following comments seem to be related to my issue:

https://github.com/facebook/jest/issues/2441#issuecomment-273643521
https://github.com/facebook/jest/issues/2441#issuecomment-278202180

It's pretty fast, but it does seem like the console.logs are actually being drawn to the screen and then overwritten.

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

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...

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!

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 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.

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

any news on this? how to show console.log?

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

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.

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.

@richburdon for async tests using done callback you need to cover failing case with done.fail()

@thymikee thanks for the quick response. i don't know what you mean though. can you modify my test and/or point me at docs. Thanks very much.

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

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

I get that this is not ideal, but this is how it currently works. It's worth to note, that it's not a problem, when tested function returns a Promise. There are couple of issues affected by this behavior, such as https://github.com/facebook/jest/issues/2136 or https://github.com/facebook/jest/issues/2059. If you have an idea on how to improve it, we'd love to review a PR and make it happen.

But this is not a relevant issue to discuss it, you can post your ideas elsewhere.

@thymikee, my example wasn't a good one since setTimeout has issues relating to promises that have nothing to do with jest...

It's worth to note, that it's not a problem, when tested function returns a Promise.

I don't see that:

````
test('async', (done) => {
function foo() {
return Promise.resolve(1);
}

foo().then(value => {
expect(value).toEqual(2); // Never reported; just times out.
done();
});
});
````

It's not obvious that testing code should catch exceptions for expect calls (i.e., part of the test framework itself). This seems pretty convoluted?

So, just to be clear, I should wrap ALL tests that involve any tested functions that return promises with a catch block -- to catch expect calls, which otherwise will: a) timeout; b) not report the error.

Unless I'm making a different mistake:

a). Perhaps document this (https://facebook.github.io/jest/docs/asynchronous.html#content)?

b). Why not log the error? and/or have an option to exit?

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.

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

@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?

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

@marcusjwhelan
Works for me on v7.10.0

I'm still seeing console output get swallowed when using jest --bail.

@cpojer Does not work on v8.0.0

Not working on node 8.0.0

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

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.

@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".

Having this same issue with node v8.1.2. I have also tried node v7.10.0 and that didn't work either

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.

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).

@cpojer @thymikee will you please reopen this issue so that it gets attention?

@iffy, can you please create a separate issue with your repro? I'll try to triage it and see what's wrong.
BTW nothing below failing expect will ever get called, because expect throws.

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

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!');

Winston works because it uses process.stdout.write which gets around this bug in Jest. I ended up making my own console.log by using node's util module.

@eranimo @Daymannovaes look at bug #3853

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.

Will this bug be fixed in the next release? Also, where do I find when that is?

I cannot upgrade to the latest version of node (not an option) so that's not a solution. I could make my own logger util which I can mess with. I am considering converting to mocha but it depends on how my logger util experiment goes.

Please fix ASAP, console logs are extremely helpful for writing my tests.

I have temporarily downgraded to 19.0.2 and that is working.

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

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

fixed for me when updating node from 7.4.0 -> 8.2.1

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.

sorry for this comment but is their a way to get Jest to console.log in real time instead of after a test has passed or failed. my test uses a while loop I was trying to get values logged while the loop is running?

@nharrisanalyst use --verbose flag

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.

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

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".

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.

Running Jest v19.0.2 with node v8.1.4.

Running --verbose --testPathPattern=<path/to/file> led to logs being printed. Otherwise, it gets swallowed.

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)?

There's no need to configure verbose or additional jest configs and the problem just gone when I upgrade my node version from 7.4.0 to 8.0.0. That's my observations.

Using [email protected]

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.

Do you have some piece of code consistently reproducing this? Might help us eliminate the underlying inconsistency causing the issue.

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.

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

@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)

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.

@fega since nobody has provided a reproduction case we can pull and test on.

$ jest --verbose

this command will show all console logs

@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.

on [email protected], [email protected], 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).

on [email protected], [email protected], 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. [email protected], [email protected].

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?

We have a test case for it: https://github.com/facebook/jest/blob/497be7627ef851c947da830d4a8e21046f847a78/integration-tests/__tests__/console_log_output_when_run_in_band.test.js#L24 Is it faulty somehow?

Can somebody set up a reproduction repo we can take a look at?

Quick addition: jest --no-cache also seems to mean console.logs don't show.

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.

This issue has also been nagging us for quite some time now, first with output being truncated randomly, now output totally ignored. To reproduce, clone the branch dev/dexie-search-index of this repo:
[email protected]:WorldBrain/Memex.git

Add this line somewhere in the insertTestData() in src/search/index.test.ts:
console.log('!?!?!?!!?!?!!?'); expect(1).toBe(2)

Tested with Node.js versions 6.11 and 8.10. Please resolve this as soon as possible, since it makes coding sooo much slower :(

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

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.

Just added a solution that worked for me in this related issue: https://github.com/facebook/jest/issues/3853#issuecomment-375183943

@ledbit That did not work for me. Wow an issue that has spanned one and a half years and still no solution.

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.

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 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.

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 <[email protected] 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.

@RALifeCoach looking at your repo now, there's quite a bit of logging there. Mind pointing out which logging in particular you're missing?

Run it. You will see some output, but much is overwritten.

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

@RALifeCoach https://github.com/RALifeCoach looking at your repo now,
there's quite a bit of logging there. Mind pointing out which logging in
particular you're missing?


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-381318608, or mute
the thread
https://github.com/notifications/unsubscribe-auth/ADrayHQCc8C0NmMmrtE7mEo2jN999CChks5tocsKgaJpZM4LVbUv
.

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

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
.

I am also experiencing what @RALifeCoach is describing. I will see my log output flash on the screen as the tests fire off, then when I scroll up that output is no longer there.

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?

Still have the same problem in node v8.9.0.

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]

Setting up "verbose": true in package.json helps. Logs show up in the bottom of the output.

Man for a closed issue I still watch people complain about this since it was created 2 years ago.

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__\libarray-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...)

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).

I was having this "overwriting" problem (Windows 10, VS Code terminal, node.js project) and then as I was fiddling with it, the bug stopped happening. I thought it stopped happening because I stopped using --watch or because I added a "verbose": false option, but reverting those changes did not make the bug come back.

I have to ask though, does Jest intentionally not associate log output with the test that produced it? For awhile all console output was below all test results, but now it's shown above all test results. So random.

--watchAll flag blocked it. now it works for me

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.

Finding the same problem here, thanks for the temporary fix @bkempner

Can confirm that this is an issue in both 22.4.4 and 23.4.1 (current as of this comment). The flags I'm using are:

$ jest --forceExit --runInBand --bail --ci --json --outputFile=/tmp/jest_results.json

Another issue on the same topic suggested adding the --json option, which did work for a while... Maybe some dependency has changed since then, but STDOUT and STDERR output is always suppressed. The closest I got to anything that worked was using --watch; sometimes some output would get tacked onto the end without being overwritten.

I found --silent is true by default, set it to false will output the console.log: jest --silent=false

Seems like a ton of reports of this still, something is clearly still broken. This was closed as a dupe of #2166 which is now closed, but yet this persists.

@thymikee Could we reopen this issue?

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.

In my case, running all tests in watch mode does log correctly. If I use pattern mode to filter to just one test class, then logging is truncated

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.

I have verbose: true in my package.json and I'm finding that console.log statements are sometimes there and sometimes not (if I have like 10 in all clumped together they seem to show up, but not for just one) - I'm thinking this is maybe an async issue

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

@ndelangen that's curious - I wonder if it maybe is an async issue then. I thought Jest collected all console.logs and then printed them at the end, no?

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've done some analysis, added some comments and managed to create a partial patch here:

https://github.com/facebook/jest/issues/3853#issuecomment-413622844

edit:

repo containing code to reproduce easily available here: https://github.com/spion/jest-logging-repro

analysis of ouput here: https://gist.github.com/spion/bbb34c5abc1230a37ad5f4f01336b8df

The patch is partial because

  • lots of integration tests are failing now due to necessary changes in output
  • sometimes (unfortunately) the log output appears after the last status update - the reason is probably the fact that the child process streams gets flushed after the child process sends the success message to the parent.

@philraj same issue for me.. i have to log multiple times to reliably see the intended log message

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

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.

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

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.

I had the same problem.

What worked for me was to use console.debug

TERM=dumb fixes it for me as well

FWIW, TERM=dumb fixes it for me as well

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

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"
}

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.

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

I have started noticing this issue with verbose in Jest 23.6, I rolled back to 23.5 and I am seeing it still. If I run --clearCache this fixes verbose for a while until it fails again. I'm unclear what the trigger is, such as a lot of log failures or something along that line. Once that happens it appears to cause Jest to corrupt the cache. I am trying the --verbose false and see if that prevents it going forward.

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?

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.

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 also having the same issue.

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

Believe it or not I sometimes log throwing an Error. Also doing node --inspect node_modules/.bin/jest --runInBand mypath/to/my.test.js shows the real console.log outputs in my case.

Node v9.11.1
Jest: v23.6.0

Jest config in package.json:

  "jest": {
    "preset": "react-native",
    "verbose": true,
    "testEnvironment": "node",
    "haste": {
      "defaultPlatform": "android",
      "platforms": [
        "android",
        "ios",
        "native"
      ],
      "providesModuleNodeModules": [
        "react-native"
      ]
    },
    "setupFiles": ["<rootDir>/__tests__/setup"]
  },

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.

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

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)

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.

Haven't updated yet (running jest 22.4.2) but using the watch mode my logs wouldn't show. Running with --runInBand fixed it in watch mode.

    "test": "jest --watch --runInBand",
    "test:once": "jest",

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

Would love for people having issues to test the PR mentioned above. It's available in jest@beta (24.0.0-alpha.9 right now)

So yarn add jest@beta?

ons. 19. des. 2018 kl. 16:46 skrev Simen Bekkhus notifications@github.com:

Would love for people having issues to test the PR mentioned above. It's
available in jest@beta (24.0.0-alpha.9 right now)


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

>


Tarjei Huse
Mobil: 920 63 413

@tarjei, yes:

yarn add --dev jest@beta

It is working for me. 🎉

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 🤦‍♂️

Notice when verbose is enabled (I toggle it using jest-watch-toggle-config), some of the console log is being blocked in beta.

--verbose=false

This worked for me.

I noticed that some console.log() where working while others didn't in my tests (node v8, [email protected])

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.

@DanweDE can you check if the latest alpha yarn add jest@beta --dev fixes the issue for you, even with verbose set to true?

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

Is this fixed? I'm still seeing no console.logs on "jest": "23.6.0"

@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.

console logs in the classes i am testing do show up

@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.

Can confirm too, works on 24.0.0-alpha.9 without any command line args.

I'm relatively new to React and Jest. I couldn't get consistent logs using the defaults from create-react-app. I ejected and now the logs are working fine. I don't think ejecting changed the version of Jest. Maybe that just changed one of the settings for how Jest was running. This is with 23.6.0.

When using 24.0.0-alpha.16 I do not see any console logs unless I add verbose=false.

I get pretty inconsistent results with this as well on [email protected]. If I run in watch mode all (a) then I can see console output, but not if I run in related changes watch mode (o)?

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

I'm using 24.1.0 and it works even without verbose option. However, it doesn't output any console.log statements in test file when test file contains eg. reference to class, that is not imported. For example

image

That's an error from ts-jest and not really relevant here

Yes but when that error occurs, console log output is not displayed. Is that still relevant for ts-jest? I'm not very familiar with what each library around jest is responsible for.

IDK how ts-jest works, but if it doesn't run any tests on type errors, that would explain why they're missing - the code never runs

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?

@mulholio are you 100% sure you're running localy installed jest? I reported issues in the past that only happened because I had a old global version of a package which was running instead of the locally installed one.

Yep, no global versions of Jest installed

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"],
}

yeah, after remove verbose:true, it seems fine

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

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.

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)

+1000

sounds really silly but make sure you yarn build before the tests!

Still no output with --verbose=true or --verbose=false when using [email protected] - not sure why it is still an issue 3 years after it was originally logged.

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..

This is still an issue for me, [email protected]

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 [email protected]', () => {
  console.log("[email protected] bug|last 2 lines get override. remove this once 24.8.0 gets fixed");
  console.log("[email protected] bug|last 2 lines get override. remove this once 24.8.0 gets fixed");
});

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,
    },
  },

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

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 ([email protected]). On my system the terminal output line with [PASS] appears to flash some content before its cleared.

Experiencing this issue also.

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({})

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.

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

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');
  };

Still no output with --verbose=true or --verbose=false when using [email protected] - 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'

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

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

This bug is so annoying... 3 years...

turn off --silent
and for ts tests using ts-jest @mr-madamin solution working for me!

Not using verbose or silent, have tried --runInBand, TERM=dumb, running all tests vs. single test file, and console.log appears when placed in setup blocks but not within it() blocks.

When all else fails, you should still be able to do:

require('fs').writeFileSync('./output', data);

But I feel like a caveman using a rock to crack a peanut.

edit: "jest": "^24.9.0"

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().

Not using verbose or silent, have tried --runInBand, TERM=dumb, running all tests vs. single test file, and console.log appears when placed in setup blocks but not within it() blocks.

When all else fails, you should still be able to do:

require('fs').writeFileSync('./output', data);

But I feel like a caveman using a rock to crack a peanut.

edit: "jest": "^24.9.0"

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",

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.

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",

Ive tested every single solution in this thread.

Just to check if nothing changed in this regard:
image

bash-5.0$ npm -v ; node -v; cat node_modules/jest/package.json |grep version
6.12.0
v12.11.0
  "version": "24.9.0",

Edit

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.

I wasnt even checking bottom of the report, but thats exactly where my log landed. So i guess it works, just not consistently/the same way for everyone.

image

Thank you for your help.

Question is how much does it hurt performance, but thats for another day, logging is more important.

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

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

It's incredible this has not yet been fixed.

@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

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

@u84six have you tried my solution?
Here's the link to my answer on the post.
https://github.com/facebook/jest/issues/2441#issuecomment-552368939

Cheers

@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.

@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 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!

@u84six this is my packadge.json

"scripts": {
    "test": "jest test --coverage",
    ... 
},
...
"jest": {
    "verbose": true,
    "testMatch": [
      "**/tests/**/*.js?(x)"
    ],
    "moduleFileExtensions": [
      "js"
    ],
    "moduleDirectories": [
      "node_modules"
    ]
  }

Your testMatch allows either .js or .jx or .jsx files, and your moduleFileExtensions only allows .js. Something seems wrong there.

It's not relevant to the cause :man_shrugging:
That is just which file to locate and run tests against them.

I am unsure as to why the issue is closed. So here is my node version - 13.12.10, npm -6.14.4
jest -24.9.0

Here is a basic test with mock-fs
import mock from 'mock-fs';
import * as fs from 'fs';
import pump from 'pump';
import * as util from 'util';

describe('Test suite for bucket functionality', () => {
    beforeEach(() => {
        mock({
            'sample-file.txt': 'Content of the sample file',
            'sample-upload.txt': ''
        });
    });
    test('test upload', async () => {
        const filePromisy = util.promisify(fs.readFile);
        pump(fs.createReadStream('sample-file.txt'), fs.createWriteStream('sample-upload.txt'));
        filePromisy('sample-upload.txt').then(data => {
                       // when I do a console.log() here I get a warning stating that before I do an expect of data , I get a warning (no longer an error) stating that -_Cannot log after tests are done._

        }).catch(err => {

        });



    });
    test('test download', () => {

    });
});

I am unsure as to why this happens. Is this because of the event-loop where the console.log is made to considered to be processed in the nextTick() only after the execution of test specs. Apologies to bringing this up, but it rather seems tedious to debug every single test case, rather than just do a console o/p and check the req data.

Because you have to return your filePromisy promise to jest so it knows when your test is done - your issue has nothing to do with this one.

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).

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 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

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.

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.

@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'm pretty sure 90% of Jest users have no idea their code is AST-transformed to hoist mock calls, for example.

WHAT

Try using console.debug or console.error

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

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

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

Was this page helpful?
0 / 5 - 0 ratings