How do I get Jest to run tests against a rollup+babel build?

Viewed 3690

I'm trying to set up a React module with tests. I'm using rollup to compile everything, which works fine. But I'm trying to introduce testing as well.

My directory structure:

dist/
  |- index.js
src/
  |- .babelrc
  |- util.js
test/
  |- .babelrc
  |- util.test.js
rollup.config.js

So far, so good. I have a .babelrc in src that applies to my source files:

{
  "presets": [
    ["es2015", { "modules": false }],
    ["env", { "modules": false }],
    "react"
  ],
  "plugins": ["external-helpers"]
}

and a separate one for the Jest tests, which doesn't have the exceptions Rollup requires:

{
  "presets": ["es2015", "env", "react"]
}

Unfortunately, I get an error when I run the tests, complaining about the very first es6 feature they run in to in the source file (SyntaxError: Unexpected token export). If I remove the module exception, then the test passes, but Rollup fails.

How do I get babel to apply the module exceptions for Rollup, but not for Jest? Or is there an entirely different way I should be configuring these?

2 Answers

I had a similar problem recently (although I wasn't using React), and having my .babelrc file in src/ produced the same error.

I use this configuration for my projects now. The README includes an explanation.

The key feature is that I've specified the babel config in the rollup.config.js, and I include the option babelrc: false.

I no longer get the error when I run my tests, and everything works perfectly. Does this sound reasonable to you?

import resolve from "rollup-plugin-node-resolve";
import babel from "rollup-plugin-babel";

export default {
  input: "src/index.js",
  output: [
    {
      file: "build/index.cjs.js",
      format: "cjs"
    },
    {
      file: "build/index.es.js",
      format: "es"
    }
  ],
  plugins: [
    resolve(),
    babel({
      presets: [
        [
          "env",
          {
            modules: false
          }
        ]
      ],
      plugins: ["external-helpers"],
      babelrc: false
    })
  ]
};
Related