Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest in a Monorepo doesn't work if running from a specific package

I have monorepo and I'm trying to use jest to run tests. This is what I have

/
   packages/
       package1/
           jest.config.js
   jest.config.base.js
   jest.config.js

any my config files are

// jest.config.base.js
module.exports = {
  collectCoverage: true,
  setupFiles: ['<rootDir>/jest.setup.js'],
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  collectCoverageFrom: [
    '<rootDir>/packages/**/*.ts'
  ],
  testMatch: [
    '<rootDir>/packages/**/__tests__/**/*.test.ts'
  ],
  transform: {
    '^.+\\.js?$': '<rootDir>/node_modules/babel-jest'
  },
  testPathIgnorePatterns: [
    '/node_modules/',
  ],
  coveragePathIgnorePatterns: [
    '/node_modules/',
  ]
};

// jest.config.js (root dir)
const base = require('./jest.config.base');

module.exports = {
  ...base,
  projects: [
    '<rootDir>/packages/*/jest.config.js'
  ]
};

// jest.config.js (of a package)
const base = require('./../../jest.config.base');

module.exports = {
  ...base,
  rootDir: '../..',
};

Running npm run test from root directory works, but if I run npm run test from one of the packages, I get

 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import '@babel/polyfill';
                                                                                                ^^^^^^^^^^^^^^^^^

  SyntaxError: Unexpected string

  at ScriptTransformer._transformAndBuildScript (packages/package1/node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
  at ScriptTransformer.transform (packages/package1/node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
like image 339
Kousha Avatar asked Sep 01 '25 01:09

Kousha


1 Answers

This seems to be related to how babel is configured in your project.

The way I did it is add a root babel config:

const presets = [
  [
    '@babel/preset-env',
    {
      targets: {
        node: 'current',
      },
    },
  ],
];

module.exports = function babelConfig(api) {
  api.cache(false);

  return {
    presets,
  };
};

And then in each package extend this base config:

module.exports = function babelConfig(api) {
  api.cache(false);

  return {
    extends: '../../babel.config.js',
  };
};

In my root package.json I also have these:

"@babel/cli": "~7.8.4",
"@babel/core": "~7.8.4",
"@babel/preset-env": "~7.8.4",
"babel-jest": "~25.1.0",
"jest": "~25.1.0",

In my package package.json I have a prepare npm script that transpiles the ES6 to ES5:

{
  ...
  "main": "lib/index.js",
  "files": [
    "lib"
  ],
  "scripts": {
    "prepare": "rm -rf lib && babel src --out-dir lib"
  }
}
like image 186
void Avatar answered Sep 02 '25 14:09

void