styled-components / polished

A lightweight toolset for writing styles in JavaScript ✨
https://polished.js.org/
MIT License
7.6k stars 209 forks source link

Test suite fails to run with cssVar() #590

Closed dlavieri closed 2 years ago

dlavieri commented 2 years ago

Mixin/Helper/Shorthand Usage

What You Are Seeing

Our application sets brand colors for our clients in a .haml file, which we access and set to global style variables in out global.scss file. We are trying to access these brand variables in our styled-components using the cssVar() method from polished, and in terms of rendering it is working as expected. However it is causing all of our related React Testing Library tests to fail with the error:

Test suite failed to run

    CSS variable not found and no default was provided.

      53 |   color: ${theme.$givelivelyWhite};
    > 54 |   border-color: ${cssVar(theme.$brandColorBase)};

Is there a way to stub or mock this variable, or any recommendations for bypassing this so that we can still test our components' functionality in Jest tests?

What You Expected To See

I would expect a way to give access to these variables, or have them ignored for the purposes of testing, rather than cause the test suite to fail.

Reproduction

bhough commented 2 years ago

@dlavieri Thank you for submitting this issue.

There is indeed a way to give access to these variables for the purposes of testing. If you look at our test for cssVar you will see an example of how we do this using Jest: https://github.com/styled-components/polished/blob/main/src/helpers/test/cssVar.test.js

In this case, we do it in the test itself, but if you have a lot of tests that rely on CSS variables in your themes, I'd suggest mocking it higher up the test chain so they are available for all your tests.

Here is smaller example:

beforeAll(() => {
  document.documentElement.style.setProperty('--background', '#FFF')
})
dlavieri commented 2 years ago

Hi @bhough thanks for your response but that does not solve my problem. I get the same error as before, saying that there is no such variable.

theme.js

Screen Shot 2021-08-16 at 8 34 59 AM

Button.spec.js w/ error

Screen Shot 2021-08-16 at 8 34 25 AM
bhough commented 2 years ago

@dlavieri I'd have to see more, but my immediate guess is that your theme file isn't getting access to them. You're mocking them in the button test but since the button test is reading them from a theme file vs directly from the DOM, they are undefined when the theme file tries to access them.