styled-components / polished

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

Is the faction that lighten fails to work in testing-library a polished problem or an rtl/jest problem? #602

Closed crevulus closed 2 years ago

crevulus commented 2 years ago

Question

I'm using lighten on a component and works fine in the browser with no errors thrown. The value I'm passing in is from props.theme, but it is just a string of a hex value.

When I try running any tests in a component that uses lighten, I get the following error:

Passed an incorrect argument to a color function, please pass a string representation of a color.

      41 |     }
      42 |
    > 43 |     background: ${(props) => lighten(0.1, props.theme.primary)};

Is this a problem with polished or should I be bringing it up with testing-library? I understand this is a relatively common issue when people try to pass in rgba/hls values, but I'm passing in a hex and, again, fine the browser. Works as intended.

Relevant Information

All relevant info is above.

bhough commented 2 years ago

@crevulus This is almost always due to not properly mocking props.theme. I'd suggest logging out the value of props.theme.primary in your tests to see what it contains. That error likely means you aren't getting the hex value you think you are when you run in your test environment.

crevulus commented 2 years ago

@bhough Thanks for your feedback. I haven't mocked theme at all. Didn't realise that was a requirement when using polished -- it works fine for other places where I'm using theme so just assumed.

To "properly" mock theme, should I follow this snippet?

const renderComponent = ({ theme, name }) =>
  render(
    <ThemeProvider theme={theme}>
      <HelloMessageStyled name={name} />
    </ThemeProvider>
  );

it('renders greeting', async () => {
  const { getByText } = renderComponent({ theme: mockThemeObject, name: 'Maggie' });

  await waitForElement(() => getByText(/hello Maggie/i));
}); 
bhough commented 2 years ago

@crevulus This isn't specific to polished. It applies to anything that requires access to the theme object for your tests to pass. This is an older put relevant thread: https://github.com/styled-components/styled-components/issues/1319

crevulus commented 2 years ago

@bhough Thanks for your help.

For anyone with the same issue: the answer is to wrap with a ThemeProvider, similar to how they've done it in the Setup section of testing-library's docs: https://testing-library.com/docs/react-testing-library/setup/#custom-render