шутка с реакцией: невозможно использовать оператор импорта вне модуля

#reactjs #jestjs

#reactjs #jestjs

Вопрос:

Я впервые пытался реализовать тесты с помощью Jest и столкнулся со следующей ошибкой. Я также попробовал рекомендуемые исправления, найденные в других потоках, и не устранил свою проблему.

Кажется, что мой «импорт» не работает на определенных уровнях моего приложения.

setupTests.js

 import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({
    adapter: new Adapter()
});
 

babel.config.js

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


 

jest.config.json

 {
    "setupFiles": [
        "raf/polyfill",
        "<rootDir>/src/setupTests.js"
    ]
}

 

package.json

 {
  "name": "front",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-free": "^5.15.1",
    "@fortawesome/fontawesome-svg-core": "^1.2.32",
    "@fortawesome/free-solid-svg-icons": "^5.15.1",
    "@fortawesome/react-fontawesome": "^0.1.12",
    "@material-ui/core": "^4.11.1",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.57",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/user-event": "^12.2.2",
    "axios": "^0.21.0",
    "babel": "^6.23.0",
    "chart.js": "^2.9.4",
    "html-react-parser": "^0.14.1",
    "moment": "^2.29.1",
    "raf": "^3.4.1",
    "react": "^17.0.1",
    "react-chartjs-2": "^2.11.1",
    "react-dom": "^17.0.1",
    "react-redux": "^7.2.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.0",
    "react-test-renderer": "^17.0.1",
    "reactour": "^1.18.0",
    "recharts": "^1.8.5",
    "redux": "^4.0.5",
    "redux-devtools-extension": "^2.13.8",
    "redux-thunk": "^2.3.0",
    "styled-components": "^4.4.1",
    "universal-cookie": "^4.0.4",
    "victory": "^35.3.5",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "testJ": "jest --config=jest.config.json"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@testing-library/react": "^11.2.2",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.5",
    "jest": "^26.6.3"
  }
}
 

Всякий раз, когда я пытаюсь запустить свой набор тестов, я получаю следующую ошибку:

  FAIL  src/tests/add.test.jsTest suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.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/en/configuration.html

    Details:

    /Users/jk/EpitechProjects/T-WEB-700/CountOfMoney_18/front/src/setupTests.js:6
    import Enzyme from 'enzyme';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
 

Ответ №1:

Попробуйте добавить ниже в свой файл jest.config.json:

  transform: {
    "^. \.(js?)$": "babel-jest"
  },
 

Комментарии:

1. Пожалуйста, отметьте это как принятое, если это помогло вам, чтобы другие тоже могли извлечь из этого пользу 🙂