Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

console.log does not output when running tests #2441

Closed
udbhav opened this issue Dec 25, 2016 · 243 comments · Fixed by #6871
Closed

console.log does not output when running tests #2441

udbhav opened this issue Dec 25, 2016 · 243 comments · Fixed by #6871

Comments

@udbhav
Copy link

udbhav commented Dec 25, 2016

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

@udbhav
Copy link
Author

udbhav commented Dec 25, 2016

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.

@thymikee
Copy link
Collaborator

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

@thisissami
Copy link

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

@cpojer
Copy link
Member

cpojer commented Dec 29, 2016

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

@thisissami
Copy link

thisissami commented Dec 29, 2016

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

@cpojer
Copy link
Member

cpojer commented Dec 29, 2016

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.

@thisissami
Copy link

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.

@thisissami
Copy link

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

@thisissami
Copy link

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.

@cpojer
Copy link
Member

cpojer commented Dec 29, 2016

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

@thisissami
Copy link

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.

@thisissami
Copy link

thisissami commented Dec 29, 2016

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

@cpojer
Copy link
Member

cpojer commented Dec 29, 2016

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: #2464

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

@thisissami
Copy link

Cloning the repository and giving it a try now.

@thisissami
Copy link

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

@cpojer
Copy link
Member

cpojer commented Dec 29, 2016

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.

@thisissami
Copy link

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

@Alex-Mann
Copy link

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.

@philwhln
Copy link

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.

@philwhln
Copy link

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.

jeffbski added a commit to jeffbski/react-boilerplate-logic that referenced this issue Jan 30, 2017
Upgrade jest-cli since it was not logging stdout under node 7.4

Apparently there was a bug that was recently fixed to be compatible with Node v7.

jestjs/jest#2441
@davidgilbertson
Copy link

davidgilbertson commented Feb 8, 2017

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.

@thymikee
Copy link
Collaborator

thymikee commented Feb 8, 2017

@davidgilbertson does it happen on v18.1?

@davidgilbertson
Copy link

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.

@jarecsni
Copy link

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.

@philwhln
Copy link

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.

@PaulTomchik
Copy link

The bail flag prevent the console logs from printing.

@jarecsni
Copy link

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.

@jarecsni
Copy link

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.

@u84six
Copy link

u84six commented Feb 13, 2020

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

@ivandosreisandrade
Copy link

@u84six have you tried my solution?
Here's the link to my answer on the post.
#2441 (comment)

Cheers

@u84six
Copy link

u84six commented Feb 14, 2020

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

@u84six
Copy link

u84six commented Feb 19, 2020

@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
Copy link

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

@ljharb
Copy link
Contributor

ljharb commented Feb 20, 2020

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

@ivandosreisandrade
Copy link

It's not relevant to the cause 🤷‍♂️
That is just which file to locate and run tests against them.

@vijayakumar-psg587
Copy link

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.

@ljharb
Copy link
Contributor

ljharb commented Apr 2, 2020

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.

@jackobear
Copy link

jackobear commented Apr 8, 2020

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

@renatomariscal
Copy link

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"

@OliverJAsh
Copy link

OliverJAsh commented Jun 25, 2020

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

@earonesty
Copy link

earonesty commented Aug 12, 2020

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.

@halis
Copy link

halis commented Aug 12, 2020 via email

@jbreckmckye
Copy link

jbreckmckye commented Aug 26, 2020

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

@alexweej
Copy link

alexweej commented Oct 6, 2020

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

WHAT

@dfusic
Copy link

dfusic commented Oct 21, 2020

Try using console.debug or console.error

@diomalta
Copy link

diomalta commented Nov 9, 2020

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

@bvaughn
Copy link
Contributor

bvaughn commented Nov 9, 2020

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

@KitsonBroadhurst
Copy link

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

@Doogiemuc
Copy link

Doogiemuc commented Dec 6, 2020

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.

@badiozam
Copy link

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.

@jbreckmckye
Copy link

jbreckmckye commented Dec 15, 2020

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

@badiozam
Copy link

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

@Pictor13
Copy link

Pictor13 commented Feb 7, 2021

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)

GerHobbelt added a commit to GerHobbelt/prettier that referenced this issue Mar 6, 2021
@iba-ragi
Copy link

iba-ragi commented Apr 5, 2021

I could it by using console.error

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 10, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.