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

Cannot create styled-component for component: [object Object]

Open craigcoles opened this issue 6 years ago • 14 comments

Error

Output from Terminal

$ npm test

> [email protected] test /Users/craigcoles/Projects/Wallet
> jest

 FAIL  __tests__/App-test.js
  ● Test suite failed to run

    Cannot create styled-component for component: [object Object]
      
      at constructWithOptions (node_modules/styled-components/lib/constructors/constructWithOptions.js:17:13)
      at styled (node_modules/styled-components/lib/native/index.js:45:10)
      at Object.<anonymous> (App/Components/BarcodeReader/styles.js:7:49)
      at Object.<anonymous> (App/Components/BarcodeReader/index.js:7:13)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        9.393s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

Test.js

import 'react-native';
import React from 'react';
import Wallet from '../App/Wallet';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
import 'jest-styled-components'

test('it works', () => {
  const tree = renderer.create(<Wallet />).toJSON()
  expect(tree).toMatchSnapshot()
})

Further Investigation

Investigating App/Components/BarcodeReader/styles.js:7, line 7 is actually creating a component based on an existing component react-native-camera.

import Camera from 'react-native-camera';
export const Scanner = styled(Camera)`

craigcoles avatar Dec 01 '17 15:12 craigcoles

I'm seeing the same issues when running my App component through jest. Is there anything I can provide (e.g. config or component) that can help solve this problem?

james2406 avatar Jun 22 '18 14:06 james2406

Greetings, I can't believe this is opened from 2017, I am running into the same issue or same error message on MacOS console because my app crashes natively.

In regards to styled components, these are the only locations where it exists:

"styled-components": {
      "version": "2.4.1",
      "resolved": "https://registry.npmjs.org/styled-components/-/styled-components-2.4.1.tgz",
      "integrity": "sha1-ZjvQSF1LarRvlGIQ3APSOY0a3nQ=",
      "requires": {
        "buffer": "^5.0.3",
        "css-to-react-native": "^2.0.3",
        "fbjs": "^0.8.9",
        "hoist-non-react-statics": "^1.2.0",
        "is-plain-object": "^2.0.1",
        "prop-types": "^15.5.4",
        "stylis": "^3.4.0",
        "supports-color": "^3.2.3"
      },
"react-native-material-tabs": {
      "version": "3.5.0",
      "resolved": "https://registry.npmjs.org/react-native-material-tabs/-/react-native-material-tabs-3.5.0.tgz",
      "integrity": "sha512-OSni2m2rcxiIYd082fjjroRrU8o/8pZlP3Ok/m244Gl9vUmhyj5WVeTgSYODjmHksQ9IIF2/sZurZcy3DawF7A==",
      "requires": {
        "prop-types": "^15.5.10",
        "styled-components": "^2.3.0"
      }
    },

So I am unclear if the problem could be in this code here:

render() {
    return (
      <View style={styles.container}>
        {Platform.OS === 'android' && (
          <MaterialTabs
            uppercase={false}
            items={this.props.tabNames}
            selectedIndex={this.state.selectedIndex}
            onChange={this._selectTab}
            barColor={v2Colors.charcoalDark}
            indicatorColor={v2Colors.green}
            activeTextColor={v2Colors.white}
            inactiveTextColor={v2Colors.gray}
            textStyle={{
              fontSize: moderateScale(14, 0.2),
              ...v2Fonts.GothamRegular,
            }}
          />
        )}

Its the only place where something related to styled-components exists in my application. MaterialTabs being a module of import MaterialTabs from 'react-native-material-tabs';

ldco2016 avatar Jun 20 '19 19:06 ldco2016

I am facing a similar issue. Has anyone found a solution for this?

Ajamuar avatar Aug 02 '21 07:08 Ajamuar

Any updates for that issue?

Szefczuk avatar Sep 24 '21 07:09 Szefczuk

Facing the Same issue in react native. ` FAIL tests/components/divider.test.js ● Test suite failed to run

Cannot create styled-component for component: undefined.

  1 | import styled from 'styled-components/native';
  2 |
> 3 | export const Divider = styled.View`
    |                               ^
  4 |   background-color: ${({ theme }) => theme.color.lightGray};
  5 |   height: 1px;
  6 |   margin: 0 -${({ theme }) => theme.spacing.default}px;

  at new StyledComponentsError (node_modules/styled-components/native/dist/styled-components.native.cjs.js:213:58)
  at constructWithOptions (node_modules/styled-components/native/dist/styled-components.native.cjs.js:6442:11)
  at styled (node_modules/styled-components/native/dist/styled-components.native.cjs.js:6506:10)
  at Function.View (node_modules/styled-components/native/dist/styled-components.native.cjs.js:6520:14)
  at Object.<anonymous> (src/components/divider/divider.js:3:31)
  at Object.<anonymous> (src/components/divider/index.js:1:1)
  at Object.<anonymous> (__tests__/components/divider.test.js:3:1)

`

Test file:

import React from 'react';

import { Divider } from '@src/components/divider';
import { render } from '../utils/theme-wrapper';


describe('Divider Component', () => {
  it('should match the Divider snapshot', () => {
    const compTree = render(<Divider />);
    expect(compTree.toJSON()).toMatchSnapshot();
  });
});

iamhaiderkhan avatar Sep 24 '21 11:09 iamhaiderkhan

same here

AilsonFreire avatar Sep 24 '21 11:09 AilsonFreire

guys, this bug has been hanging here for 4 years, is there someone on that project? 😭

Szefczuk avatar Sep 26 '21 19:09 Szefczuk

I guess it's time to change the stack.

AilsonFreire avatar Sep 27 '21 11:09 AilsonFreire

true @AilsonFreire .

Szefczuk avatar Sep 27 '21 12:09 Szefczuk

Hi guys @Szefczuk, @iamhaiderkhan, @Ajamuar, @ldco2016 and @james2406 I finally got everything working in my project but, my gosh!, it was almost a month of trying and failing. Here is my setup. I'm using react native, typescript, styled-components and icons. I really hope it helps you. My dependencies:

 "react-native-svg": "^12.1.1"
 "styled-components": "^5.3.1", 
 "react-native-svg": "^12.1.1",   
 "@types/styled-components": "^5.1.14",
 "@types/styled-components-react-native": "^5.1.1",
 __DEV__
 "jest": "^26.6.3",
 "jest-svg-transformer": "^1.0.0",
 "@testing-library/react-native": "^7.2.0",
 "@types/jest": "^26.0.23",
 "react-native-svg-transformer": "^0.14.3",

My theme folder has three files: Captura de Tela 2021-09-29 às 18 24 44

//styled-components


const {
  default: styled,
  css,
  ThemeProvider,
} = styledComponents as styledComponents.ReactNativeThemedStyledComponentsModule<styledComponents.DefaultTheme>;

export { css, ThemeProvider };
export default styled;

//styles.d.ts

import "styled-components/native";

declare module "styled-components/native" {
  export interface DefaultTheme {
    COLORS: {
      PRIMARY: string;
      SECONDARY: string;
      TERTIARY: string;
      BLACK: string;
      WHITE: string;
      ALERT: string;
    };
    FONTS: {
      PRIMARY: string;
      SECONDARY: {
        REGULAR: string;
        BOLD: string;
        ITALIC: string;
        ITALIC_BOLD: string;
      };
    };
  }
}

//theme.ts

import { DefaultTheme } from "styled-components/native";

export const Theme: DefaultTheme = {
  COLORS: {
    PRIMARY: "#9966CC",
    SECONDARY: "#F9F9F9",
    TERTIARY: "#CCFFFF",
    BLACK: "#333333",
    WHITE: "#FFFFFF",
    ALERT: "#DF4B38",
  },
  FONTS: {
    PRIMARY: "Jua-Regular",
    SECONDARY: {
      BOLD: "SegoeUI-Bold",
      REGULAR: "SegoeUI-Regular",
      ITALIC: "SegoeUI-LightItalic",
      ITALIC_BOLD: "SegoeUI-BoldItalic",
    },
  },
};

//test-utils.tsx

jest.useFakeTimers();
import { ApolloProvider } from "@apollo/client";
import OrganizeMoneyGameProvider from "@contexts/OrganizeMoneyGame/provider";
import { graphqlClient } from "@graphql/client";
import { render, RenderOptions } from "@testing-library/react-native";
import { ThemeProvider } from "@theme/styled-components";
import { Theme } from "@theme/theme";
import React from "react";
import "react-native";

const AllTheProviders = ({ children }: { children: React.ReactNode }) => {
  return (
    <ApolloProvider client={graphqlClient}>
      <ThemeProvider theme={Theme}>
        <OrganizeMoneyGameProvider>{children}</OrganizeMoneyGameProvider>
      </ThemeProvider>
    </ApolloProvider>
  );
};

const customRender = (
  component: React.ReactElement<any>,
  options?: RenderOptions,
) => render(component, { wrapper: AllTheProviders, ...options });

export * from "@testing-library/react-native";
export { customRender as render };

//package.json

"jest": {
    "preset": "react-native",
    "setupFiles": [
      "react-native-gesture-handler/jestSetup",
      "<rootDir>/jest.setup.js"
    ],
    "transform": {
      "^.+\\.js?$": "babel-jest",
      "^.+\\.svg$": "jest-svg-transformer"
    },
    "transformIgnorePatterns": [
      "!node_modules/react-runtime"
    ],
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }

//jest.setup.js

import "react-native-indicators";

jest.mock("react-native-indicators", () => ({
	MaterialIndicator: jest.fn()
}))

jest.mock("@react-native-firebase/auth", () => ({
	auth: jest.fn()
}))

AilsonFreire avatar Sep 30 '21 11:09 AilsonFreire

@AilsonFreire What exactly fixed the issue? The dependencies update?

sayurimizuguchi avatar Nov 24 '21 21:11 sayurimizuguchi

also getting this error in react-native when in testing. im getting this error with .svg files im using styled() on. im not getting errors for .svg files im using as component directly, only when using styled() on the .svg file.

i dont even have to render the component, its enough to fail even if i just define the component.

the error i get looks like this:

  ● Test suite failed to run

    Cannot create styled-component for component: [object Object].

      141 | })``;
      142 |
    > 143 | const IconName = styled(Icon).attrs({
          |                  ^
      144 |   width: 38,
      145 |   height: 38,
      146 | })`

      at throwStyledError (node_modules/styled-components/src/utils/error.js:39:11)
      at constructWithOptions (node_modules/styled-components/src/constructors/constructWithOptions.js:15:12)
      at styled (node_modules/styled-components/src/native/index.js:20:33)
      at Object.<anonymous> (src/screens/Home/components/PaymentCard.tsx:143:25)
      at Object.<anonymous> (src/screens/Home/components/index.ts:87:1)

styled-components version: 5.3.5

edit: i should mention im not using jest-styled-components, i just found this issue.

Adnan-Bacic avatar Jan 06 '23 12:01 Adnan-Bacic

this solved my jest test failing: https://github.com/styled-components/styled-components/issues/1449#issuecomment-420087359

Adnan-Bacic avatar Jan 11 '23 09:01 Adnan-Bacic

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.

adybuciuman avatar Aug 28 '23 05:08 adybuciuman