bakhansen
bakhansen

Reputation: 41

How to transform module after ordinary transform has run in jest

Testing React components with jest. Some of these components make use of OpenLayers (ol package v5.2.0). In ol package v4 I applied transformIgnorePatterns to have the ol package transformed:

"jest": {
    "transformIgnorePatterns": [
         "node_modules/(?!(ol)/)"
    ],
    (...)
}

Now I get the following error when running NODE_ENV=test jest:

(...)
(...)/node_modules/ol/index.js:5
export {default as AssertionError} from './AssertionError.js';
^^^^^^

SyntaxError: Unexpected token export

  14 |     let map = new Map({
  15 |       layers: options.layers,
> 16 |       target: 'map',
     |           ^
  17 |       view: options.view,
  18 |       controls: options.controls
  19 |     });

I have applied the following presets and plugins in .babelrc:

"presets": [
   ["@babel/preset-env", {
     "modules": false
    }
   ],
   "@babel/preset-react"
],
"plugins": [
    "lodash",
    ["@babel/plugin-transform-runtime", {
      "corejs": 2,
      "helpers": true,
      "regenerator": true,
      "useESModules": false
    }
  ],
  "@babel/plugin-transform-modules-commonjs",
  "@babel/transform-arrow-functions",
  "@babel/plugin-syntax-dynamic-import",
  "@babel/plugin-syntax-import-meta",
  ["@babel/plugin-proposal-class-properties", {"loose": false}],
  "@babel/plugin-proposal-json-strings"],
"env": {
    "production": {},
    "development": {},
    "test": {
      "presets": [
        ["@babel/preset-env"],
        "@babel/preset-react"
      ]
    }
  }

A similar problem is solved when building the application by applying the global-transform option (https://github.com/browserify/browserify#usage) cf. this issue thread: https://github.com/openlayers/openlayers/issues/8497.

$ browserify -g [ babelify --presets [ \"@babel/preset-env\" ] --ignore [ \"//node_modules/(?!ol/)/\" ] ] ./src/index.js -o ./public/js/bundle.js

I want to apply a similar transformation to the ol module but unsure on how to approach it. The transformIgnorePatterns used to solve this problem cf. https://github.com/facebook/jest/issues/2550

Upvotes: 2

Views: 858

Answers (1)

bakhansen
bakhansen

Reputation: 41

The error no longer occurs if I put the contents of .babelrc into babel.config.js in the root of the project.

module.exports = {
    (...)
};

cf.

side effect - TypeError: $export is not a function when loading the bundle built via browserify/babelify, but I guess it is a configuration problem.

Edit: Side effect was solved for me by changing the options for the plugin "@babel/plugin-transform-runtime" to:

{
  "corejs": false,
  "helpers": false,
  "regenerator": true,
  "useESModules": false
}

cf. https://stackoverflow.com/a/39502362/3798151 and installing @babel/runtime cf. https://babeljs.io/docs/en/babel-plugin-transform-runtime

Upvotes: 1

Related Questions