skip to Main Content

I am getting the error "SyntaxError: Cannot use import statement outside a module" when I run my tests in a react project. So, the testing suite has a problem with all of my import statements. The project is not using TypeScript. Based on other Stack Overflow posts, it seems like the issue may be with the version numbers of my React and @testing-library/react. My react version number is "react": "^18.2.0", and my @testing-library/react version number is "@testing-library/react": "^13.4.0". Given these version numbers, how should I resolve the problem?

Other Stack Overflow posts seem to fix the issue if the React and @testing-library/react versions are lower, but I don’t want to downgrade versions to fix the problem.

2

Answers


  1. Chosen as BEST ANSWER

    The issue is apparently a known problem with axios. This fixes the issue:

    in package.json, add:

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

    I found this in the comment to a Youtube video, "React Testing Library Tutorial #12 - Finding Async Elements with FindBy". Here is the comment:

    "There is a problem with the recent axios v1.2. It will give import error. Add the below line at the end of package.json

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

    restart the test and it will work. This is a temporary solution until axios fixes it."


  2. Add below jest config to package.json:

    "jest": {
      "transformIgnorePatterns": [
        "node_modules/(?!axios/)"
      ],
      "moduleNameMapper": {
        "\.(css|less|scss|sass)$": "<rootDir>/src/test/styleMock.js"
      }
    },
    

    And create the styleMock.js file:

    module.exports = {};
    

    I created a PR

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search