entwicklerstube/babel-plugin-root-import

Not working with jest

witalobenicio opened this issue · 6 comments

"@babel/core": "7.2.2",
"babel-plugin-root-import": "6.1.0",
"babel-jest": "24.9.0",
"enzyme": "^3.10.0",
@jest/core: "24.9.0"

As requested by @brigand I'm opening a new issue.

I'm using CRA with Craco to override default Webpack configs (use eslint, babelrc, etc).
If I try to run a simple test to see if App.js render without erros, but jest is not able to files imported like this:
import File from '~/components/File';

If I add this to my package.json:

"jest": {
    "moduleNameMapper": {
      "~": "<rootDir>/src"
    }
  },

it stops showing error for not found files, but I'm still not able to get my test successful, because I get an error saying that what I'm trying to render is not a DOM element.
But if I remove all imports and return just a single div in my App component, the tests are ok.

So I presume that the problem is with the imports.

This is my babelrc config:

{
  "presets": [
    "@babel/preset-flow",
    "react-app",
    ["@babel/preset-env", {"targets": {"node": "current"}}]
  ],
  "plugins": [
    ["symlink-import"],
    "babel-plugin-add-module-exports",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-syntax-export-default-from",
    "@babel/plugin-transform-runtime",
    ["babel-plugin-root-import", {
      "rootPathPrefix": "~",
      "rootPathSuffix": "src"
    }]
  ]
}

Someone?

@witalobenicio hey, sorry for the delay on this. I've created a repo using the provide config, minus the jest alias which you shouldn't have, and the tests pass

brigand/babel-plugin-root-import-131

Note that babel config is in .babelrc, as there are a few ways to define it, but craco config isn't one of them (unclear if you defined it in both).

Please modify it to be more like your project until it breaks, and share a forked repo, or diffs of changed files and any new files you added.

@brigand you created using CRA? I'm using craco just to say to CRA to use babelrc file (and others things).

@brigand from what I saw you didn't import example anywhere, so your tests are not reaching it, so it won't break.

Sorry, I didn't saw that you've created a test just to example.js.
But anyway, I tried on gitpod.io (yarn test) and I got:
Cannot find module '~/example' from 'example.test.js'

And this is probably because you won't telling CRA to use your babelrc as configurations (which is exactly what craco does).

Also...I tried to use example.js in App.js importing with '~' suffix and this doesn't work neither.

Finally fixed.
With craco, you can't use a babelrc file (if you want jest to work).
You have to put your presets and plugins directly on craco.config.js.