Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest encountered an unexpected token

I have just started learning react testing library with jest and created a sample application to mock the server.my node version is v16.13.0. However, I am getting following error "SyntaxError: Cannot use import statement outside a module". I even write import axios from './lib/axios' but I got the same error.

     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:

D:\test-projects\icecream\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

> 1 | import axios from "axios";
    | ^
  2 | import { useEffect, useState } from "react";
  3 | import { Row } from "react-bootstrap";
  4 | import ScoopOption from "./ScoopOptions";

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (src/pages/entry/Options.jsx:1:1)

my test

      import Options from "../Options";
      import { render, screen } from "@testing-library/jest-dom";
       test("displays image for each scoop option from the server",async   () => {
      render(<Options optionType="scoop" />);
     const scoopImages = await screen.findAllByRole("img", { name: /scoop$/i });
     expect(scoopImages).toHaveLength(2);
    });

this is some of my code (Options.jsx):

     import axios from "axios";
     const [items, setItems] = useState([]);
  useEffect(() => {
  axios
  .get(`http://localhost:3030/${optionType}`)
  .then((response) => setItems(response.data))
  .catch((err) => {});
 }, [optionType]);

my package.json is:

             {
         "name": "icecream",
        "version": "0.1.0",
        "private": true,
        "type": "module",
        "dependencies": {
       "@babel/plugin-transform-modules-commonjs": "^7.20.11",
       "@testing-library/jest-dom": "^5.16.5",
      "@testing-library/react": "^13.4.0",
      "axios": "^1.2.1",
      "bootstrap": "^5.2.3",
    "eslint-plugin-jest-dom": "^4.0.3",
    "eslint-plugin-testing-library": "^5.9.1",
   "msw": "^0.49.2",
    "react": "^18.2.0",
  "react-bootstrap": "^2.7.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
     },
      "scripts": {
      "start": "react-scripts start",
      "build": "react-scripts build",
     "test": "react-scripts test",
    "eject": "react-scripts eject"
     },
     "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.7",
   "@babel/preset-env": "^7.20.2",
   "@testing-library/user-event": "^14.4.3",
    "babel-jest": "^29.3.1"
   }
  }

 
like image 587
Elham Bagheri Avatar asked Oct 24 '25 14:10

Elham Bagheri


2 Answers

this error occurs in axios in 1.x.x version and it is because of the change of transpilers from babel to Common js.

I solved this problem by changing "test" in my package.json to:

"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",
like image 86
Elham Bagheri Avatar answered Oct 26 '25 04:10

Elham Bagheri


Why does this error occur?

The 1.x.x version of axios changed the module type from CommonJS to ECMAScript.

The 0.x.x version of axios index.js file

module.exports = require('./lib/axios');

The 1.x.x version of axiox index.js file

import axios from './lib/axios.js';
export default axios;

Basically, jest runs on Node.js environment, so it uses modules following the CommonJS. If you want to use axios up to 1.x.x, you have to transpile the JavaScript module from ECMAScript type to CommonJS type. Jest ignores /node_modules/ directory to transform basically.

So you have to override transformIgnorePatterns option. There are two ways to override transformIgnorePatterns option.

jest.config.js

So how do you use config.js ,you can replace the parameter

transformIgnorePatterns: ['<rootDir>/node_modules/'],

on

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

package.json

you can add a setting for just in your package.json file

    {
  ...other options
  "jest": {
    "preset": "your project",
    "transformIgnorePatterns": ["node_modules\/(?!axios)"]
  }
}

Or you can use the solution from @Elham Bagheri and add a parameter to your script "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\""

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",
    "eject": "react-scripts eject"
  },
like image 23
BuGaGa Avatar answered Oct 26 '25 04:10

BuGaGa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!