Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read console.log from a mounted component with Enzyme and Jest in Create React App

I have a component I'm mounting with Enzyme. There is an object that is defined inside the constructor of the component. I need to read values inside that object. How do I do this? If I was using the browser, I would use console.log(this.object.property) in the constructor or other function. In Jest, this doesn't seem to work. I tried running console.log in my test() function by:

console.log(wrapper.instance().object)

but it only showed me the default props from the object.
My prefered way would be to see console.log anywhere in the component. Is there a way to enable that? Otherwise, what is the best way to get access to properties of rendered components in Enzyme so I can do a console.log in one of my test() functions?

like image 515
Brandon Keith Biggs Avatar asked Feb 08 '19 15:02

Brandon Keith Biggs


People also ask

How would you test the React components using Jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

Does console log work in Jest?

Jest by default prints all console. log (warnings, errors, etc) messages to the console. That's great - it helps you understand what's going on in your code when tests run.


2 Answers

You can use console.log(wrapper.debug());

like image 91
Mwibutsa Floribert Avatar answered Oct 24 '22 12:10

Mwibutsa Floribert


Adding --verbose false will fix the issue.
The test line in package.json should look something like:
"test": "react-scripts test --env=jsdom --verbose=false",

Just like Console.log statements output nothing at all in Jest suggested.

like image 34
Subhendu Kundu Avatar answered Oct 24 '22 13:10

Subhendu Kundu