Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Ask HN: How do you test React components for CSS?
1 point by akudha on May 14, 2023 | hide | past | favorite | 7 comments
What is the best way to test React components, specifically CSS? Are there any test frameworks, tricks etc to do it? Is there a way to compare CSS properties of components with Figma designs?


Are you using vanilla css and class names? Or styling the elements with the style attribute?

Usually if I need to debug css I'll check computed styles in chrome debugger. It will show you what styles are being applied to an element and where they came from [1].

[1] https://support.google.com/webdesigner/answer/9008244?hl=en


Yes, I am using Chrome debugger too. But there are tons of components that my team inherited, it is not possible to test them all manually. I was wondering if there is any automatic way to test it. I looked at Jest, but it seems to be for JS testing, not CSS


If you just want to catch regressions while refactoring, it's probably easiest to add visual snapshot tests. Checkout Chromatic for a SaaS that integrates with Storybook and can detect diffs of components on each PR.


I did check Chromatic, my employer rejected it. I'll have to find some other way.


Are there refs the compliments are holding on to? If so use that and then window.getComputedStyle(refeElement) to test the style.

Jest is a testing framework. You'll need to plug in other libraries to test specific things. For example, use react-testing-library to test react components in various ways.


Thank you, I wasn't aware of getComputedStyle, will experiment with it. I haven't yet tried react-testing-library yet, will try it too.

It looks like testing JS is straightforward, but not CSS?


Once you have the element it should be fairly straightforward to test computed styles. You may have to add some hooks for react-testing-library to grab elements like attributes, unique text, refs, etc. Read up on the tools you should be able to find something in there for your use case.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: