javascript 错误“语法错误:当我尝试在react应用程序中运行npm测试时,出现”无法在模块外使用import语句

vxbzzdmp  于 2023-01-11  发布在  Java
关注(0)|答案(3)|浏览(97)

我已经花了2天多的时间来研究解决我的react应用程序中关于测试库和jest的问题,但它不起作用。
每次运行npm测试时,终端中出现的错误如下所示:

FAIL  src/App.test.jsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/thanhnhan/Desktop/capstone-frontend/node_modules/axios/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      3 | import LoginPage from "./pages/LoginPage/LoginPage";
      4 | import { useEffect, useState } from "react";
    > 5 | import axios from "axios";
        | ^
      6 | import HomePage from "./pages/HomePage/HomePage";
      7 | import HeaderComponent from "./components/HeaderPage/HeaderComponent";
      8 | import SideMenu from "./components/SideMenu/SideMenu";

      at Runtime.createScriptFromCode (node_modules/react-scripts/node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/App.jsx:5:1)
      at Object.<anonymous> (src/App.test.jsx:2:1)
      at TestScheduler.scheduleTests (node_modules/react-scripts/node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/react-scripts/node_modules/@jest/core/build/runJest.js:404:19)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.243 s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.

我的测试文件是App.test.jsx:

import { render } from "@testing-library/react";
import App from "./App";

describe("<App />", () => {
  it("should match snapshot", () => {
    const snapshot = render(<App />);
    expect(snapshot).toMatchSnapshot();
  });
});

我的package.json看起来像这样:

{
  "name": "capstone-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/material": "^5.11.4",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.2.0",
    "chart.js": "^4.0.1",
    "faker": "^5.5.3",
    "fitness-calculator": "^1.1.0",
    "framer-motion": "^7.6.19",
    "js-sha256": "^0.9.0",
    "react": "^18.2.0",
    "react-chartjs-2": "^5.0.1",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.4",
    "react-scripts": "5.0.1",
    "react-slick": "^0.29.0",
    "sass": "^1.56.1",
    "slick-carousel": "^1.8.1",
    "uuid": "^9.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.20.12",
    "@babel/plugin-transform-modules-commonjs": "^7.20.11",
    "@babel/preset-env": "^7.20.2",
    "babel-jest": "^29.3.1",
    "jest": "^29.3.1"
  }
}

经过研究,我知道JestJS无法读取App.jsx中的一些语法,所以我需要使用babel。下面是我的babel.config.js文件:

module.exports = {
  presets: ["@babel/preset-env", "@babel/preset-react"],
  env: {
    test: {
      plugins: ["@babel/plugin-transform-runtime"],
    },
  },
};

我也尝试过使用。babelrc文件,但它不工作。我现在压力很大,我希望有人能帮我弄清楚这一点。谢谢你这么这么多的帮助。

ljsrvy3e

ljsrvy3e1#

我现在还没有答案,但我不想听到你对自己的问题感到压力。
过去我在混合importexportmodules.exportsrequire语句时遇到过问题。使用babel我可以“做所有的事情”。但是最近我一直在尝试标准化,只使用importexport语句。这是我的babel.config.js。我也在使用webpack

module.exports = {
    presets: [
        ["@babel/preset-env", {
        useBuiltIns: "entry",
        corejs: {
            version: 3,
        }
        }],
        "@babel/react"
    ],
    plugins: [
        ["@babel/plugin-transform-regenerator"],
        ["@babel/plugin-transform-runtime", {
        corejs: {
            version: 3
        },
        helpers: true
        }],
        // ["@babel/plugin-transform-runtime", {
        //   corejs: {
        //     version: 3
        //   },
        // }],
        // Stage 0
        "@babel/plugin-proposal-function-bind",

        // Stage 1
        "@babel/plugin-proposal-export-default-from",
        "@babel/plugin-proposal-logical-assignment-operators",
        ["@babel/plugin-proposal-optional-chaining", { "loose": false }],
        ["@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" }],
        ["@babel/plugin-proposal-nullish-coalescing-operator", { "loose": false }],
        "@babel/plugin-proposal-do-expressions",

        // Stage 2
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        "@babel/plugin-proposal-function-sent",
        "@babel/plugin-proposal-export-namespace-from",
        "@babel/plugin-proposal-numeric-separator",
        "@babel/plugin-proposal-throw-expressions",

        // Stage 3
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-syntax-import-meta",
        ["@babel/plugin-proposal-class-properties", { "loose": false }],
        "@babel/plugin-proposal-json-strings"
    ]
}
pw136qt2

pw136qt22#

看来你错过了 babel-jest 模块:https://jestjs.io/docs/28.x/getting-started#using-babel

[更新]

好的,看起来您使用的是CRA,所以不需要单独安装该模块。
我已经检查了错误日志,似乎 import 语句只在node_module中不能正常工作(错误发生在axios模块中)。默认情况下,Jest不会从node_modules转换文件。
请检查jest配置的transformIgnorePatterns属性,例如

"jest": {
    "transformIgnorePatterns": ["node_modules/(?!axios)/"]
},

参见https://github.com/axios/axios/issues/5101
或事件更好=)-https://github.com/axios/axios/issues/5101#issuecomment-1307878899

eivnm1vs

eivnm1vs3#

"type":"module",
将其添加到您的package.json以使用ES6模块。

相关问题