Enzyme with Jest and Styled-Component mount gives an error: Warning: React.createElement: type is invalid
eshanCV opened this issue · comments
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,
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.
I'm using,
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
Can you check your exports/imports first, and if that doesn't help, give some code example? I'm testing multiple styled-components projects using @wojtekmaj/enzyme-adapter-react-17 and no such error has ever come up.
Hi @wojtekmaj Thanks for the reply. Below is my code,
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 () => {
})
});
import * as Styled from './Abc.css';
This line is confusing Babel or Jest probably because you use css as a "mid-extension". If you write
import * as Styled from './Abc.css.jsx';
instead, then it'll work.
To avoid confusion I'd refrain from naming your styled components files like that and stick to Abc.styles.js
.
@wojtekmaj Thanks that worked.