无论如何都要扩展一个jest配置文件?

时间:2016-11-21 18:11:18

标签: jestjs

在我正在使用Jest来测试客户端代码(testEnvironment:'jsdom')和服务器端代码(testEnvironment:'node')以及收集客户端和服务器端的代码覆盖率的节点应用程序中。

目前我正在使用4个具有大量冗余配置的Jest配置文件来完成此任务。

客户端

{
  "bail": true,
  "verbose": true,
  "notify": true,
  "scriptPreprocessor": "./node_modules/babel-jest",
  "testPathIgnorePatterns": [
    "./node_modules",
    "./coverage",
    "./dist",
    "./build"
  ],
  "testRegex": "\\.test\\.js"
}

客户报道

{
  "bail": true,
  "verbose": true,
  "notify": true,
  "scriptPreprocessor": "./node_modules/babel-jest",
  "testPathIgnorePatterns": [
    "./node_modules",
    "./coverage",
    "./dist",
    "./build"
  ],
  "testRegex": "\\.test\\.js",
  "collectCoverageFrom": ["**/*.js", "!**/node_modules/**"],
  "collectCoverage": true,
  "coverageDirectory": "./coverage",
  "coveragePathIgnorePatterns": [
    "./node_modules",
    "./coverage",
    "./dist",
    "./build",
    "./test"
  ],
  "coverageThreshold": {
    "global": {
      "branches": 100,
      "functions": 100,
      "lines": 100,
      "statements": 100
    }
  }
}

服务器

{
  "bail": true,
  "verbose": true,
  "notify": true,
  "scriptPreprocessor": "./node_modules/babel-jest",
  "testPathIgnorePatterns": [
    "./node_modules",
    "./coverage",
    "./dist",
    "./build"
  ],
  "testRegex": "\\.test\\.js",
  "testEnvironment": "node"
}

服务器覆盖率

{
  "bail": true,
  "verbose": true,
  "notify": true,
  "scriptPreprocessor": "./node_modules/babel-jest",
  "testPathIgnorePatterns": [
    "./node_modules",
    "./coverage",
    "./dist",
    "./build"
  ],
  "testRegex": "\\.test\\.js",
  "testEnvironment": "node",
  "collectCoverageFrom": ["**/*.js", "!**/node_modules/**"],
  "collectCoverage": true,
  "coverageDirectory": "./coverage",
  "coveragePathIgnorePatterns": [
    "./node_modules",
    "./coverage",
    "./dist",
    "./build",
    "./test"
  ],
  "coverageThreshold": {
    "global": {
      "branches": 100,
      "functions": 100,
      "lines": 100,
      "statements": 100
    }
  }
}

如何在不重复配置4次的情况下实现此目的?我查看了preset配置选项。使用它我必须为每个配置创建一个单独的包。这是推荐的方式吗?

2 个答案:

答案 0 :(得分:2)

是的,自Jest v20起,您可以将config定义为JS文件,并使用它来共享类似配置的常见部分。 Docs on configuring Jest

默认情况下,Jest会查找:

  • jest.config.js
  • "jest" package.json
  • 条目

...并将父目录视为rootDir

另外请务必查看projects选项,这样可以更轻松地在monorepos中运行Jest(例如,在一个代码库中运行客户端+服务器代码)。请参阅此答案以供参考:Testing two environments with jest

答案 1 :(得分:0)

是的,您可以定义共享的jest.config.js 并在您的特定配置中重复使用它:

  • 在共享配置的所有路径中都使用<rootDir>很不错,因此这些路径也可以重用。

client/jest.config.js

const sharedConfig = require('../jest.config.js');
module.exports = {
  ...sharedConfig,
  'rootDir': './',
}

server/jest.config.js

const sharedConfig = require('../jest.config.js');
module.exports = {
  ...sharedConfig,
  'rootDir': './',
  "testEnvironment": "node"
}

如果需要,您还可以重用Jest默认值:Jest Documentation - Configuring Jest