reactjswebpackjestjsenzyme

Import react components with absolute path


Here is my test file

// /imports/components/main.test.js
import React from 'react'
import { shallow, mount } from 'enzyme'
import Main from './main'
import TextInput from "/imports/ui/textInput"
...

and the main.js has

// /imports/components/main.js
import { action1 } from "/imports/actions/myAction"

but it throws an error when I run the test, saying

Cannot find module '/imports/actions/myAction' from 'main.js'

If I comment the import './main', same thing happen with importing TextInput. I have no issue with importing modules in node_modules.

How can I tell Jest or webpack to import the component using absolute path from project directory (i.e import Foo from /imports/...)?


Solution

  • My file structure follows exactly the same pattern as yours. To teach Jest into using imports beginning with a /, I use babel-plugin-module-resolver and its handy root option. My .babelrc for Jest looks like this:

    {
      "presets": ["es2015", "meteor"],
      "plugins": [
        "transform-class-properties",
        "transform-react-constant-elements",
        "transform-react-inline-elements",
        "transform-react-remove-prop-types",
          ["module-resolver", {
          "root": ["../"],
          "alias": {
            "react-router-dom": "react-router-dom/umd/react-router-dom.min.js",
            "redux": "redux/dist/redux.min.js",
            "react-redux": "react-redux/dist/react-redux.min.js"
          }
        }]
      ]
    }
    

    As I'm using Meteor which customized its root imports, I hide my Jest usage and configuration into a .jest directory at the root of my repository allowing me to have a specific .babelrc without risking conflicts with Meteor's one.