Home  >  Q&A  >  body text

Jest error: SyntaxError: cannot use import statement outside module

I'm using React and Typescript.

In my test file I try to render a component

test("Render Header", () => {
  render(<Header />);
});

The header component is using the action creator from actions.tsx

import { loadRepo } from "../../redux/actions";
dispatch(loadRepo());

loadRepo is an asynchronous operation creator using axios. My test throws an error because I imported axios in actions.tsx. The error is as follows: The import statement cannot be used outside the module.

I tried setting up babel and jest configurations. This is what I have.

babel.config.js

module.exports = {
  presets: [["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-react", "@babel/preset-typescript"],
  plugins: [],
};

jest.config.js

module.exports = {
  setupFilesAfterEnv: ["@testing-library/jest-dom/extend-expect"],
  moduleNameMapper: {
    "\.(css|less|scss|sass)$": "identity-obj-proxy",
  },
  transform: {
    "^.+\.(js|jsx|ts|tsx)$": "babel-jest",
  },
};

package.json

"dependencies": {
    "@testing-library/user-event": "^13.5.0",
    "@types/node": "^16.18.23",
    "@types/react": "^18.0.35",
    "@types/react-dom": "^18.0.11",
    "axios": "^1.3.5",
    "bootstrap": "^5.2.3",
    "react": "^18.2.0",
    "react-bootstrap": "^2.7.3",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.5",
    "react-scripts": "5.0.1",
    "redux": "^4.2.1",
    "redux-thunk": "^2.4.2",
    "typescript": "^4.9.5",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "@babel/core": "^7.21.4",
    "@babel/preset-env": "^7.21.4",
    "@babel/preset-react": "^7.18.6",
    "@babel/preset-typescript": "^7.21.4",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^14.0.0",
    "babel-jest": "^29.5.0",
    "jest": "^27.5.1"
  }

P粉879517403P粉879517403228 days ago506

reply all(1)I'll reply

  • P粉681400307

    P粉6814003072024-03-28 09:00:47

    I was able to fix this error by adding the following code to package.json to force jest to import the commonjs axios build

    "jest": {
        "moduleNameMapper": {
          "axios": "axios/dist/node/axios.cjs"
        }
      },

    reply
    0
  • Cancelreply