Jest

Jest 是一个拥有庞大生态系统的通用测试运行器。与 Turborepo 集成将带来巨大的速度提升。

¥Jest is a common test runner with a vast ecosystem. Integrating with Turborepo will lead to enormous speed-ups.

Good to know: 

This guide assumes you're using create-turbo or a repository with a similar structure.

设置

¥Setting up

假设我们有一个如下所示的 monorepo:

¥Let's say we have a monorepo that looks like this:

package.json
package.json

jest 安装到你计划包含测试套件的包中。在本例中,我们将在 web@repo/ui 中进行测试:

¥Install jest into the packages where you plan on having test suites. For this example, we will have tests in web and @repo/ui:

Terminal
pnpm add jest --save-dev --filter=@repo/ui --filter=web

apps/webpackages/ui 都有各自的测试套件,所以我们会在它们的 package.json 中添加一个 test 脚本:

¥Both the apps/web and packages/ui have their own test suites, so we'll add a test script to their package.json:

./apps/web/package.json
{
  "name": "web",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest": "latest"
  }
}

在根 turbo.json 文件中,创建一个 test 任务:

¥Inside the root turbo.json, create a test task:

Turborepo logo
./turbo.json
{
  "tasks": {
    "test": {}
  }
}

现在,turbo test 可以并行化和缓存每个包中的所有测试套件,只测试已更改的代码。

¥Now, turbo test can parallelize and cache all of the test suites from each package, only testing code that has changed.

在监视模式下运行测试

¥Running tests in watch mode

当你正常运行测试套件时,它会完成并输出到 stdout。这意味着你可以使用 Turborepo 进行 缓存

¥When you run your test suite normally, it completes and outputs to stdout. This means you can cache it with Turborepo.

但是,当你在监视模式下运行测试时,该进程永远不会退出。这使得监视任务更像 开发任务

¥But when you run your tests in a watched mode, the process never exits. This makes a watch task more like a development task.

由于这种差异,我们建议指定两个单独的 Turborepo 任务:一个用于运行测试,另一个用于在 Jest 的监视模式下运行测试。在每个工作区的每个 package.json 文件中:

¥Because of this difference, we recommend specifying two separate Turborepo tasks: one for running your tests, and one for running them in Jest's watch mode. Inside your each package.json file for each workspace:

./apps/web/package.json
{
  "name": "web",
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch"
  },
  "devDependencies": {
    "jest": "latest"
  }
}

turbo.json 内部:

¥Inside the root turbo.json:

Turborepo logo
./turbo.json
{
  "tasks": {
    "test": {},
    "test:watch": {
      "cache": false,
      "persistent": true
    }
  }
}

你现在可以使用 全局 turbo 作为 turbo test:watch 运行此任务,也可以从根目录 package.json 中的脚本运行:

¥You can now either run this task using global turbo as turbo test:watch or from a script in your root package.json:

Terminal
turbo test
Terminal
turbo test:watch