styled-components / jest-styled-components

🔧 💅 Jest utilities for Styled Components
MIT License
1.58k stars 145 forks source link

Styled components complaining about dynamic creation in tests, but that's not true #329

Open Kepro opened 4 years ago

Kepro commented 4 years ago

"jest": "^25.5.4", "jest-styled-components": "^7.0.2", "styled-components": "^5.1.1",

console.warn
      The component styled.div with the id of "sc-fzomME" has been created dynamically.
      You may see this warning because you've called styled inside another component.
      To resolve this only create new StyledComponents outside of any render method and function component.

      2 | import styled, { keyframes } from 'styled-components';
      3 | 
    > 4 | const LoaderWrapper = styled.div`
        |                                  ^
      5 |       display: flex;
      6 |       align-items: center;
      7 |       justify-content: center;
ricardo-kagawa commented 4 years ago

Hello, just a random guy here.

I just stumbled across this myself, and maybe this is also your case, maybe not.

In my case, I have found that the issue was me mocking React's useRef to manipulate the current value for tests with shallow rendering. It seems styled-components will attempt to call this hook to determine if it is inside a render method or not, that is, if it does not throw, it considers itself in a render method and issues the warning. The mocked hook was not configured to throw errors during component definition, so SC got confused.

Just make sure React.useRef throws as it should before SC styled is used (before importing your component under test in test modules).