eremzeit
eremzeit

Reputation: 4566

How do you setup multiple jest configs within a single project?

In the create-react-app boilerplate it has both server and client code using the same package.json file. I'd like to have three separate jest configs: client unit tests, server unit tests, and server integration tests. Unfortunately, I haven't been able to get this to work. My plan was to have yarn run commands for each option and then specify the config to jest using the --config CLI option. But then I ran into this roadblock which happens on both v20 and v21 and is showing no progress. Basically, people are reporting issues with reading config files using --config and the fallback is to use the config package.json. Unfortunately, you can only specify a single config file.

Has anyone managed to get this to work and if so can you describe your setup (the version of jest, etc). I'm wondering if I need to downgrade to v19. Alternatively, am I just taking the wrong approach?

Upvotes: 32

Views: 37228

Answers (2)

David Redmond
David Redmond

Reputation: 31

I had a very similar issue. I wanted to run a lightweight jest locally when developing but a heavier, with test coverage, in the pipeline.

The solution I found was to pass a flag into the config.

in the package.json

{
  "name": "project",
  "version": "1.0.0",
  "scripts": {
    "test": "cross-env DEV=false jest --maxWorkers=30% ",
    "test:coverage": "cross-env DEV=true jest --collectCoverage"
  }
}

Then in the jest.config.js file

module.exports = () => {
  // only collect cover if true
  const isDev = process.env.DEV === 'true';
  
  return {
    "collectCoverage": isDev ? false : true,
    "collectCoverageFrom": [
      "src/**/*.{js,ts, tsx}"
    ],
    "coverageDirectory": "coverage",
    "roots": [
      "<rootDir>/src"
      ]
  };
};

Now you will have the ability to change the config, but use the same file for all setups.

Upvotes: 2

eremzeit
eremzeit

Reputation: 4566

Apparently the up and coming feature of jest is the --projects option. You can do something like this in your package.json file:

"jest": {
  "projects": [
    "src/client/jest.config.js",
    "src/server/unit.jest.config.js",
    "src/server/int.jest.config.js",
   ]
}

And then in src/client/jest.config.js you can define a specific configuration:

module.exports = {
  name: 'client',
  displayName: 'client',

  // NOTE: if you don't set this correctly then when you reference
  // it later in a path string you'll get a confusing error message.
  // It says something like' Module <rootDir>/config/polyfills.js in
  // the setupFiles option was not found.'
  rootDir: './../../',

  testMatch: [
    "<rootDir>/src/server/**/__tests__/*.unit.{js,jsx}",
    "<rootDir>/src/server/**/__tests__/unit/*.{js,jsx}"
  ],

  // etc...
};

Here's the post describing the feature: https://facebook.github.io/jest/blog/2017/05/06/jest-20-delightful-testing-multi-project-runner.html

Upvotes: 49

Related Questions