typescriptjestjsreact-testing-librarymonorepo

Where to configure jest in a monorepo?


I am setting up a monorepo in which I am building a react app where I will be using typescript. We want to use jest to test backend features and React-Testing-Library to test frontend features. Should I install jest and add the config file in root or directly in the ''backend'' package?

What would be the advantage / disadvantages of doing one over the other?

Thank you for your help.


Solution

  • Just install the jest package in the root. Then, add projects [array<string | ProjectConfig>] configuration in jest.config.js file:

    Jest will run tests in all of the specified projects at the same time. This is great for monorepos or when working on multiple projects at the same time.

    My project uses lerna to manage mono repos.

    Folder structure:

    ⚡  tree -L 2 -I 'node_modules|examples' 
    .
    ├── LICENSE
    ├── coverage
    │   ├── clover.xml
    │   ├── coverage-final.json
    │   ├── lcov-report
    │   └── lcov.info
    ├── jest.config.js
    ├── jest.setup.js
    ├── lerna.json
    ├── package-lock.json
    ├── package.json
    ├── packages
    │   ├── redux-saga-examples
    │   └── redux-toolkit-example
    └── tsconfig.json
    
    5 directories, 10 files
    

    There are two packages: redux-saga-examples and redux-toolkit-example. There are many test files in these packages.

    The package.json in the root:

    {
      "name": "root",
      "private": true,
      "scripts": {
        "bootstrap": "lerna bootstrap",
        "clean": "lerna clean",
        "test": "jest"
      },
      "devDependencies": {
        "@types/jest": "^26.0.24",
        "lerna": "^4.0.0",
        "jest": "^27.0.6",
        "ts-jest": "^27.0.4",
        "ts-node": "^9.1.1",
        "typescript": "^4.3.5",
        "prettier": "^2.3.1"
      },
      "dependencies": {
        "axios": "^0.21.4"
      }
    }
    

    jest.config.js:

    const reduxSagaExamplesPkg = require('./packages/redux-saga-examples/package.json');
    const RTKExamplesPkg = require('./packages/redux-toolkit-example/package.json');
    
    module.exports = {
      verbose: true,
      projects: [
        {
          preset: 'ts-jest/presets/js-with-ts',
          testEnvironment: 'jsdom',
          setupFilesAfterEnv: ['./jest.setup.js'],
          displayName: reduxSagaExamplesPkg.name,
          testMatch: ['<rootDir>/packages/redux-saga-examples/**/?(*.)+(spec|test).[jt]s?(x)'],
        },
        {
          preset: 'ts-jest/presets/js-with-ts',
          testEnvironment: 'jsdom',
          setupFilesAfterEnv: ['./jest.setup.js'],
          displayName: RTKExamplesPkg.name,
          testMatch: ['<rootDir>/packages/redux-toolkit-example/**/?(*.)+(spec|test).[jt]s?(x)'],
        },
      ],
    };
    

    Now, you can run npm t npm script in the root of the project to run all tests.