我有一个React应用程序(不使用创建React应用程序),使用TypeScript, Jest, Webpack和Babel构建。当试图运行纱线笑话时,我得到以下错误:

我已经尝试删除所有包并重新添加它们。它不能解决这个问题。我看过类似的问题和文档,但我仍然误解了一些东西。我甚至按照另一个指南从头开始设置这个环境,但我的代码仍然遇到了这个问题。

依赖关系包括……

"dependencies": {
  "@babel/plugin-transform-runtime": "^7.6.2",
  "@babel/polyfill": "^7.6.0",
  "babel-jest": "^24.9.0",
  "react": "^16.8.6",
  "react-dom": "^16.8.6",
  "react-test-renderer": "^16.11.0",
  "source-map-loader": "^0.2.4"
},
"devDependencies": {
  "@babel/core": "^7.6.0",
  "@babel/preset-env": "^7.6.0",
  "@babel/preset-react": "^7.0.0",
  "@types/enzyme": "^3.9.2",
  "@types/enzyme-adapter-react-16": "^1.0.5",
  "@types/jest": "^24.0.13",

组件的导入行…

import * as React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/pages";
import {
  Footer,
  Header,
  Navigation,
} from "./components/shared";

测试文件....

import * as React from "react";
import * as renderer from "react-test-renderer";
import App from "../App";

it("Renders the Footer correctly", () => {
  const tree = renderer
    .create(<App />)
    .toJSON();
  expect(tree).toMatchSnapshot();
});

我希望能够在组件中使用命名导入,而不会导致测试失败。如果我在解决方案中只使用默认导入,似乎可以解决这个问题,但我宁愿不走那条路。


当前回答

匹配的文件扩展名:

我导入一个名为Todo的文件。./src/Todo/。当我把它改成Todo.js时,问题就消失了。

免责声明:我不确定组件的文件扩展名是jsx还是js的要求是什么。它完全没有影响到我,但我可以想象它可能会扰乱智能感知或片段。

其他回答

我通过改变tsconfig来解决这个问题。Json到兼容的本机输出

"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */

这并非在所有情况下都是理想的,但你可能会接受。

如果你在使用TypeScript,你有一个tsconfig。Json文件,尝试删除"module": "esnext",如果你正在使用它

对我来说,重命名文件为babel.config.js是有效的。 下面是我的NX项目配置文件,使用Typescript和twin -宏next


// .babelrc.js >> babel.config.js
module.exports = {
  presets: [
    [
      "@nrwl/react/babel",
      {
        "runtime": "automatic",
        "targets": {
          "browsers": [">0.25%", "not dead"]
        },
        "preset-react": {
          runtime: "automatic",
          importSource: "@emotion/react",
        },
      }
    ],
    '@babel/preset-env',
    '@emotion/babel-preset-css-prop',
    '@babel/preset-typescript'
  ],
  plugins: ['@emotion', 'macros', '@babel/plugin-transform-runtime', 'react-docgen'],
}

另外,请注意甚至更新包。json的作品, https://kulshekhar.github.io/ts-jest/docs/getting-started/presets/#basic-usage

// package.json
"jest": {
    // Replace `ts-jest` with the preset you want to use
    // from the above list
    "preset": "ts-jest"
  }

匹配的文件扩展名:

我导入一个名为Todo的文件。./src/Todo/。当我把它改成Todo.js时,问题就消失了。

免责声明:我不确定组件的文件扩展名是jsx还是js的要求是什么。它完全没有影响到我,但我可以想象它可能会扰乱智能感知或片段。

没有一个答案对我有帮助,帮助我的是确保我的NODE_ENV被设置为测试,因为babel配置是每个NODE_ENV使用错误的NODE_ENV,在babel配置中没有配置将意味着你不会使用babel, typescript文件不会被转换。

我花了几个小时来解决这个问题,所以我希望它能帮别人节省我花的时间。