Search code examples
javascriptbabeljsjestjslerna

Jest fails to transpile import from npm linked module


I have a project with multiple modules (using Lerna) and I want to use Jest to run tests. However, when I test code that uses a shared module (npm linked module via Lerna) it seems that Babel is not correctly applied and I get the following error:

SyntaxError: Unexpected token import

The structure of my project is like this:

- my-project
|- shared
|- native
|- web

web and native require the shared module. When I go into the shared directory and run the local tests in Jest everything works fine. If I run Jest tests in the web directory the above error occurs as soon as I include something from shared.

Here is a super simple test that causes the error:

import { util } from 'shared';

it('returns false if not prod', () => {
    expect(util.isProd()).toBe(false);
});

My .babelrc looks like this:

{
    "presets": [
        "env",
        "flow",
        "react"
        ],
    "plugins": [
        "flow-react-proptypes",
        "transform-object-rest-spread",
        "transform-class-properties"
    ]
}

I tried everything I could find, including:

  • Different Babel configs, including one with the es2015 preset and enabling modules for the test environment
  • Manually setting the transform option for babel-jest
  • As mentioned, Jest can be executed in the shared module, thus, Jest and babel-jest are installed there as well.

Solution

  • I had to change the transformIgnorePatterns configuration option of Jest in the package.json of the web module.

    {
        "jest": {
            "transformIgnorePatterns": [
                "<rootDir>/node_modules/(?!shared|another)"
            ]
        },
    }