0

I am using React and Typescript.

In my test file I am trying to render a component

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

Header component is using action creator from actions.tsx

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

loadRepo is asyncronous action creator that uses axios. My test throws an error, because I import axios in actions.tsx. The error is following: Cannot use import statement outside a module.

Image of Error

I tried to set up babel and jest config. Here 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"
  }
Vitaly
  • 89
  • 1
  • 5
  • 1
    Does [this](https://stackoverflow.com/questions/73958968/cannot-use-import-statement-outside-a-module-with-axios) answer your question? – ivanatias Apr 18 '23 at 17:52

1 Answers1

0

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

  "jest": {
    "moduleNameMapper": {
      "axios": "axios/dist/node/axios.cjs"
    }
  },
Vitaly
  • 89
  • 1
  • 5