Jest - `Cannot create styled-component for component: undefined`
Asked Answered
N

4

11

I'm running into the following error when testing my application using jest:

 FAIL  
  ● Test suite failed to run

    Cannot create styled-component for component: undefined.

      30 |
      31 | 
    > 32 | export const BackgroundVector = styled(Background)`
         |                                 ^
      33 |   position: fixed;
      34 |   left: 0;
      35 |   bottom: 0;

Background is an svg that I imported at the top of this file as follows:

import { ReactComponent as Background } from '../images/Background.svg';

I'm not quite sure how to get around this error. In my package.json, I have mapped SVG files to a fileMock.js which is just module.exports = 'test-file-stub';. Is there anything else I should do to resolve this?

Nomenclator answered 14/4, 2022 at 18:38 Comment(0)
A
16

You could try the following:

export const BackgroundVector = styled(props => <Background {...props}/>)`
  //Your styles here
`

This solved my problem.

Autochthon answered 26/5, 2022 at 3:37 Comment(2)
Is there no other way?Diastema
I cant understand why this works? Wouldn't passing the function re-render this component unnecessarilyParegmenon
P
1

my problem too and with jest i thought it was a circular dependency but it shouldn't even render.

Postscript answered 29/8, 2023 at 14:36 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Painter
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewLesbos
D
0

I encountered the same issue. To debug it, I added a console log just above the line where I was getting the error. Sure enough, the component was undefined. The issue turned out to be an incorrectly defined alias in babel.config.js. After correcting the alias setup in babel.config.js, everything worked as expected. What confuses me, however, is why the project ran successfully with the incorrect alias; the error only appeared when using Jest.

Doty answered 28/8, 2023 at 5:16 Comment(0)
M
0

Do this :

export const BackgroundVector = styled(props => <Background {...props}/>)`
  //Your styles here
`
Molasses answered 9/1, 2024 at 14:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.