Tech enthusiast, working as Senior Software Developer at Mediaocean
How to get rid of the weird styled component names in test snapshots
This requires some previous knowledge with unit testing React code. If you want to understand the basic of unit testing, please check here.
Find the relevant code examples at github. Clone the repository to follow along, if you want. There are two folders with same example, one of them uses displayName for styled components, while the other doesn’t. We will start with the code which does not contain displayName to understand the issues.
Check link - code
The main component is user.jsx which uses some styled components.
The styled components file contains the below code:
While unit testing, when we shallow render user component and generate the snapshot, we will not get the exact names for the styled components, instead we get something like below:
What we expected:
What actually got generated:
When we try to traverse the component tree for any assertion, and the target component is a styled component, we cannot simply use the straightforward approach of using the name of the styled component.
Let’s assume wrapper is the shallow rendered output of user component and we are trying to test if the LoadingSpinnerStyled component is indeed present in the user component. So we simply cannot do something as below:
However, if we import the LoadingSpinnerStyled component into our test file, we can test it like below:
Notice that there is no single quotes around the component name in above statement. This means that we are traversing the component tree using the actual component, rather than just the name (which is one of the benefits of using enzyme).
Or, if we want to avoid those extra imports into the test file, we will have to test the code like below:
As the title of this article might indicate, we can solve all the issues as mentioned above by just specifying displayName for all the styled components.
You can assign display names by just adding one extra line besides each component, like below:
Now, when the component is shallow rendered, look at the snapshot generated:
It now contains the names as we want it to be and it makes the snapshot as well as unit tests more readable and maintainable.
Check code: link
The displayName provided by React is a recommended feature which helps a lot with unit testing as well as debugging the code.
It also helps when we are using React devtools to inspect a component.
Read more about displayName here.
Thanks for reading. I hope this was helpful. Please feel free to leave a response if you have any questions or suggestions.
Happy learning and have a great day!!
Previously published at https://medium.com/@anuradha15/test-styled-components-in-react-efficiently-using-displayname-53281a0c1f2d