7

TLDR: How can I configure jest so that it uses babel to compile the test files and the files required in globalSetup and globalTeardown?


I've been struggling a lot to configure jest and babel. It seems that when I run my tests babel fails to load the configuration file, or perhaps it doesn't run at all.

in package.json:

{
  "scripts": {
    "start": "babel-node src/index.js",
    "test": "jest src/tests/*.test.js",
  },
  "devDependencies": {
    "@babel/cli": "^7.0.0-rc.1",
    "@babel/core": "^7.0.0-rc.1",
    "@babel/node": "^7.0.0-rc.1",
    "@babel/preset-env": "^7.0.0-rc.1",
    "babel-jest": "^23.4.2",
    "jest": "^23.5.0",
  }
}

in babel.config.js:

module.exports = (api) => {
    if (api) api.cache(true);
    const presets = ['@babel/preset-env'];
    const plugins = [];
    return {
        presets,
        plugins,
    };
};

in jest.config.js:

module.exports = {
    globalSetup: './src/config/jest/setup',
    globalTeardown: './src/config/jest/teardown',
};

When I run npm run test I get the following error:

import app from '../../index';
^^^^^^ SyntaxError: Unexpected token import

...which I assume means that babel failed to configure properly. I tried logging on both config files and babel.config.js is only run when I do npm start.

When I used an identical configuration with .babelrc instead, the tests could run. However the globalSetup and globalTeardown could not.

nomadoda
  • 4,561
  • 3
  • 30
  • 45
  • So when I run `npm start` I use `babel-node` and it does some magic compilation it seems. I would like to use `babel-node` when I do my jest testing too I guess? – nomadoda Aug 14 '18 at 10:58
  • Possible duplicate of [How to use babel-preset-env with Jest](https://stackoverflow.com/questions/45259679/how-to-use-babel-preset-env-with-jest) – Andrea Carraro Aug 14 '18 at 12:55

1 Answers1

8

Jest currently doesn't transform modules defined in globalSetup and globalTeardown. There's an open GitHub discussion here.

That being said, there are some workarounds on the same thread. You'll have to require babel-register and babel-polyfill on top of your jest.config.js. Here is the full implementation: https://github.com/facebook/jest/issues/5164#issuecomment-366139663

If someone is using TypeScript requiring ts-node/register should make it work. https://github.com/facebook/jest/issues/5164#issuecomment-376006851

Saugat
  • 1,309
  • 14
  • 22