2

I am trying to make a test using jest and react-testing-library but when I try to render the app inside a test block I am getting this error:

...{import axios from './lib/axios.js';
                                                                                 

SyntaxError: Cannot use import statement outside a module

After a little research I see that jest ignores everything in node_modules when it transforms modules using babel-jest. Is there a way to allow the axios module to be transformed?

Here is my package.json file

{
  "name": "weather_app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest",
    "start": "webpack serve --config webpack.config.js",
    "react-dev": "webpack --mode development --watch",
    "server-dev": "npx nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.19.3",
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/preset-env": "^7.19.4",
    "@babel/preset-react": "^7.18.6",
    "@testing-library/react": "^13.4.0",
    "babel-jest": "^29.2.0",
    "babel-loader": "^8.2.5",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^6.7.1",
    "html-webpack-plugin": "^5.5.0",
    "jest": "^29.2.0",
    "jest-environment-jsdom": "^29.2.0",
    "react-test-renderer": "^18.2.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.1"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^6.2.0",
    "@fortawesome/free-solid-svg-icons": "^6.2.0",
    "@fortawesome/react-fontawesome": "^0.2.0",
    "axios": "^1.1.2",
    "dotenv": "^16.0.3",
    "mysql2": "^2.3.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "url": "^0.11.0"
  }
}

And my .babelrc file

    {
  "presets": [
    "@babel/preset-env",
    ["@babel/preset-react", {"runtime": "automatic"}],
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties"
  ]
}

I do not have any other config files for jest or babel

2 Answers 2

2

I found a solution. You can add a property to your jest.config.js file and specify modules from node modules to transform specifically but still ignore the rest of node modules. To tell babel-jest to transform axios it looked like this:

transformIgnorePatterns: ['<rootDir>/node_modules/(?!(axios)/)']
1

This axios issue (#5106) helped me (just downgrade axios to v0.27.2 and it works).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.