jest-styled-components icon indicating copy to clipboard operation
jest-styled-components copied to clipboard

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

Open Kepro opened this issue 5 years ago • 1 comments

"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;

Kepro avatar Jul 01 '20 15:07 Kepro

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).

ricardo-kagawa avatar Sep 09 '20 17:09 ricardo-kagawa