Home > front end >  The error "SyntaxError: Cannot use import statement outside a module" appears when I try t
The error "SyntaxError: Cannot use import statement outside a module" appears when I try t

Time:01-11

I have spent more than 2 days to research to solve the problem regarding testing library and jest in my react application but it does not work.

The error appearing in my terminal each time I run npm test looks like below:

     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.

My test file is the 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();
  });
});

My package.json looks like this:

{
  "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"
  }
}

After researching, I know that JestJS can not read some syntaxes in my App.jsx, so I need to use babel. Here is what my babel.config.js file looks like:

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

I have also tried using .babelrc file but it does not work. I am very stressed now and I hope that someone can help me figure this out. Thank you so so much for your help.

CodePudding user response:

I don't have an answer for you for now, but hate to hear you're stressed about your issue.

I have had issues in the past with mixing import, export, with modules.exports and require statements. Using babel I was able to "do it all" though. But as of late have been trying to standardize using only import and export statements. Here is my babel.config.js. I am also using 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"
    ]
}

CodePudding user response:

it seems that you missed babel-jest module: https://jestjs.io/docs/28.x/getting-started#using-babel

[UPDATES]

Ok, it seems you use CRA so there is not need to install separately that module.

I have checked the error log and it seems that import statement does not work properly only in your node_module (error happens in axios module). By default Jest does not transform files from node_modules.

Please check transformIgnorePatterns property of jest config and e.g

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

see https://github.com/axios/axios/issues/5101

or event better=) - https://github.com/axios/axios/issues/5101#issuecomment-1307878899

CodePudding user response:

"type":"module",

Add this to your package.json to use ES6 modules .

  • Related