Search code examples
reactjsunit-testingjestjsreact-testing-libraryparceljs

How do I configure .babelrc for react and jest testing framework?


I created a react app from scratch(createapp.dev) and am using parcel bundler to bundle it.

I tried do unit testing on it using https://testing-library.com/ and jest but I keep getting this error.

src/components/App.test.js
  ● Test 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:
     • 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

How can I fix it? These are my files .babelrc

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

package.json

{

  "main": "src/index.js",

  "scripts": {
    "test": "jest",
    "start": "parcel public/index.html --host 127.0.0.1 --port 8080",
  },
  "dependencies": {
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  },
  "devDependencies": {
    "@babel/core": "^7.8.7",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/preset-env": "^7.8.7",
    "@babel/preset-react": "^7.8.3",
    "@testing-library/react": "^10.0.1",
    "babel-jest": "^25.1.0",
    "jest": "^25.1.0",
    "parcel": "^1.12.4",
    "parcel-bundler": "^1.12.4",
    "prettier": "^1.19.1"
  }
}

Solution

  • I realized installing @testing-library/react and jest is not enough I added the followings

    @testing-library/dom
    @testing-library/jest-dom
    @testing-library/user-event
    babel-jest 
    

    I also changed my .babelrc to look like this

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