我在一个具有相同名称和.css.jsx
的单独文件中创建了一个样式组件,例如Abc.jsx
有Abc.css.jsx
并将其导入到 Abc.jsx
中使用。但是当我尝试测试 Abc.jsx
时,我从 enzyme 安装中收到以下错误,
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.
React 似乎无法找到我的 Abc.css.jsx
中编写的样式。有谁知道这个问题的原因以及如何解决这个问题?
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 () => {
})
});
jest.config
module.exports = {
testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
setupFilesAfterEnv: ["<rootDir>/setupTests.js"],
moduleNameMapper: {
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
transform: {
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
}
};
最佳答案
我终于能得到和你一样的错误了!在这个codesandbox
所以问题出在样式组件文件的命名上。您将它们命名为 [something].css.jsx
。
在你的 jest.config 文件中尝试将它们映射为类或类似的东西,我认为这是因为导入,因为它以“.css”结尾
...
moduleNameMapper: {
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
...
您可以在此处执行几项操作。
- 更改样式组件的命名约定。从
[something].css.jsx
到[something].styled.jsx
。 - 删除
moduleNameMapper
- 从
moduleNameMapper
中删除css
我个人最喜欢的是选项 1。
关于reactjs - Jest、Enzyme 和 Styled Component 无法使用警告 : React. createElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68883532/