【问题标题】:Jest, Enzyme and Styled Component not working with Warning: React.createElementJest、Enzyme 和 Styled Component 不适用于警告:React.createElement
【发布时间】:2021-10-23 06:27:01
【问题描述】:

我在一个具有相同名称和.css.jsx 的单独文件中创建了一个样式化的组件,例如Abc.jsxAbc.css.jsx,它被导入到Abc.jsx 中使用。但是当我尝试测试 Abc.jsx 时,我从 Enzyme 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.

似乎 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"
    }
};

【问题讨论】:

  • 请提供minimal reproducible example,而不仅仅是描述它。
  • @jonrsharpe 抱歉,我添加了一个可重复的样本
  • “您可能混淆了默认导入和命名导入”
  • @jonrsharpe 很抱歉没有得到您的答复。你能否详细说明一下。我是 React 和所有这些技术的新手。现在我的代码工作正常,只有测试因上述错误而失败
  • 我刚刚在codesendbox 中创建了一个示例,它正在运行。你能分享一下你的文件夹结构吗

标签: reactjs jestjs next.js enzyme styled-components


【解决方案1】:

我终于能得到和你一样的错误了!在这个codesandbox

所以问题在于样式化组件文件的命名。你将它们命名为[something].css.jsx

在你的 jest.config 文件中尝试将它们映射为类或类似的东西,我认为这是因为导入,因为它以 '.css' 结尾

...
  moduleNameMapper: {
    "\\.(css|less|scss|sass)$": "identity-obj-proxy"
  },
...

您可以在这里做几件事。

  1. 更改样式组件的命名约定。从[something].css.jsx[something].styled.jsx
  2. 删除moduleNameMapper
  3. moduleNameMapper 中删除css

我个人最喜欢的是选项 1。

【讨论】:

  • 谢谢,是的,这就是问题所在,否则如果我像 [something].css.jsx 一样导入,那么它也可以工作
  • 但我认为正如你所说,选项 1 很好。
猜你喜欢
  • 2020-03-19
  • 2020-12-17
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
相关资源
最近更新 更多