enzymejs / enzyme

JavaScript Testing utilities for React
https://enzymejs.github.io/enzyme/
MIT License
19.95k stars 2.01k forks source link

importing the wrong file gives `type is invalid` error from React #2538

Closed eshanCV closed 3 years ago

eshanCV commented 3 years ago

All common issues

I have created a styled-components in a sperate file with the same name and .css.jsx for example Abc.jsx have Abc.css.jsx and it's imported to the Abc.jsx to use. But when I try to test Abc.jsx I get the below error from the mount,

Current behavior

gives error when trying to mount,

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Expected behavior

Should be able to mount it without any issue

Your environment

React 17, Next.js 11.1, Jest 26.4.2, enzyme 3.11.0, styled-components 5.3.0, @wojtekmaj/enzyme-adapter-react-17 0.6.2

API

Version

library version
enzyme 3.11.0
react 17.0.2
react-dom 17.0.2
react-test-renderer
adapter (below) 0.6.2

Adapter

ljharb commented 3 years ago

This isn't an enzyme problem. It means the "Foo" in <Foo /> is undefined, which means you have an importing problem. Perhaps it's a default export and you're using named imports, or the reverse?

Please provide the full test and component code.

eshanCV commented 3 years ago

@ljharb below is the code,

Is this something to do with the enzyme-adapter-react-17

Abc.jsx

import * as Styled from './Abc.css';

function Abc() {
  return (<Styled.Title>ABC</ Styled.Title>);
}

export default Abc

Abc.css.jsx

import styled from 'styled-components';

export const Title = styled.div`
`;

Abc.test.js

import Abc from '../../../components/Abc';
import { mount } from 'enzyme';

describe("My Abc tests", () => {

    let wrapper;

    beforeAll(() => {
        wrapper = mount(<Abc />);
    })

    test("check api call", async () => {

    })

});
ljharb commented 3 years ago

There is no react 17 adapter; you must be using an unofficial one. enzyme is not currently supported with react 17.

I believe the issue is that you’re importing a file named “a.css.jsx” and omitting the extension. My guess is Babel or typescript is assuming you mean a file named literally “a.css” and thus, Title is undefined.

eshanCV commented 3 years ago

Yes, importing as a.css.jsx fixed the issue. Thanks