【问题标题】:Where to configure jest in a monorepo?在 monorepo 中哪里可以配置 jest?
【发布时间】:2022-02-07 12:33:30
【问题描述】:

我正在设置一个 monorepo,在其中我正在构建一个反应应用程序,我将在其中使用 typescript。我们想使用 jest 来测试后端功能和 React-Testing-Library 来测试前端功能。我应该安装 jest 并将配置文件添加到 root 中还是直接添加到 ''backend'' 包中?

做一个比另一个有什么优点/缺点?

感谢您的帮助。

【问题讨论】:

    标签: typescript jestjs react-testing-library monorepo


    【解决方案1】:

    只需在根目录下安装 jest 包。然后,在jest.config.js文件中添加projects [array<string | ProjectConfig>] 配置:

    Jest 将同时在所有指定项目中运行测试。这对于 monorepos 或同时处理多个项目时非常有用。

    我的项目使用lerna 来管理单声道存储库。

    文件夹结构:

    ⚡  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
    

    有两个包:redux-saga-examplesredux-toolkit-example。这些包中有很多测试文件。

    根中的package.json

    {
      "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)'],
        },
      ],
    };
    

    现在,您可以在项目根目录下运行npm t npm 脚本来运行所有测试。

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2011-03-14
      • 1970-01-01
      • 2016-09-19
      • 2011-02-10
      • 1970-01-01
      相关资源
      最近更新 更多