Saturday, 13 May 2017

Difficulty using babel and jest together

I am trying to use jest and babel together.

Overview

How can I compile a folder of ES6 files with babel, ignore particular folders (/__tests__/) in the build step, and write my tests in ES6 using jest?

More details

My directory structure looks like this:

src
│   a.js
│   b.js
│   c.js
│
└───__tests__
    │   d.js

I wish to compile src (excluding the test folders) and put the output in lib.

Here are the scripts in package.json:

"scripts": {
  "build": "babel src -d lib",
  "test": "jest --coverage"
}

And .babelrc:

{
  "presets": [
    "env"
  ]
}

I have also installed babel-jest, so jest will correctly run my tests written in ES6.

With the configuration above, running yarn build correctly builds into lib, but it also includes the __tests__ folder. yarn test works as expected, correctly running ES6.

I tried:


1.

ignoring the __tests__ folder in .babelrc.

Compilation works as expected, no __tests folder:

yarn build yarn build v0.24.4 $ babel src -d lib src\a.js -> lib\a.js src\b.js -> lib\b.js src\c.js -> lib\c.js Done in 0.82s.

But, yarn test no longer works:

>yarn test
yarn test v0.24.4
$ jest --coverage
 FAIL  src\__tests__\toccer.js
  ● Test suite failed to run

    D:\Dev\toccer\src\__tests__\toccer.js:6
    import toccer from '../'
    ^^^^^^
    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:290:17)
      at process._tickCallback (internal/process/next_tick.js:103:7)

Apparently the ignore option I used above also skips even tranforming the file when jest does its thing.


2.

So, I reverted the change above and tried setting the ignore in the CLI for the build script instead.

"build": "babel src -d lib --ignore '/__tests__/'"

However, the tests folder still gets processed.

>yarn build
yarn build v0.24.4
$ babel src -d lib --ignore '/__tests__/'
src\cli.js -> lib\cli.js
src\index.js -> lib\index.js
src\utils.js -> lib\utils.js
src\__tests__\toccer.js -> lib\__tests__\toccer.js
Done in 0.95s.

This flag seems to do something different from the ignore option in the configuration file. Actually, it doesn't seem to do anything. I tried --ignore '/src/a.js', and it still processed that file. I saw somewhere that there was a bug with babel in an older version, but should be fixed in the version I am currently using.

versions

node: 6.10.0

babel-cli: 6.24.1

babel-jest: 20.0.1

jest-cli: 20.0.1



via Hoten

No comments:

Post a Comment