diff --git a/api/advanced/test-case.md b/api/advanced/test-case.md index 2a47d435..009acba0 100644 --- a/api/advanced/test-case.md +++ b/api/advanced/test-case.md @@ -177,7 +177,7 @@ export interface TestResultPending { ```ts interface TestResultSkipped { /** - * 使用 `skip` 或 `todo` 标志跳过测试。 + * 使用 `skip` 或 `todo` 参数跳过测试。 * 你可以在 `options.mode` 选项中查看使用的是哪种模式。 */ readonly state: 'skipped' @@ -193,7 +193,7 @@ interface TestResultSkipped { ``` ::: tip -如果测试因为其他测试有 `only` 标志而被跳过,则 `options.mode` 将等于 `skip`。 +如果测试因为其他测试有 `only` 参数而被跳过,则 `options.mode` 将等于 `skip`。 ::: 如果测试失败,返回值将是 `TestResultFailed`: @@ -246,7 +246,7 @@ interface TestDiagnostic { readonly slow: boolean /** * 测试使用的内存量(字节)。 - * 只有使用 `logHeapUsage` 标志执行测试时,该值才可用。 + * 只有使用 `logHeapUsage` 参数执行测试时,该值才可用。 */ readonly heap: number | undefined /** diff --git a/api/advanced/test-module.md b/api/advanced/test-module.md index 6aeb0087..ee6b68a6 100644 --- a/api/advanced/test-module.md +++ b/api/advanced/test-module.md @@ -110,7 +110,7 @@ interface ModuleDiagnostic { readonly duration: number /** * 模块使用的内存量(以字节为单位)。 - * 此值仅在使用 `logHeapUsage` 标志执行测试时才可用。 + * 此值仅在使用 `logHeapUsage` 参数执行测试时才可用。 */ readonly heap: number | undefined /** diff --git a/api/advanced/test-suite.md b/api/advanced/test-suite.md index 3f664aee..4c8ccd28 100644 --- a/api/advanced/test-suite.md +++ b/api/advanced/test-suite.md @@ -81,7 +81,7 @@ const hash = generateFileHash( ## location -套件在模块中定义的位置。仅当配置中启用了 [`includeTaskLocation`](/config/includetasklocation) 时才会收集位置信息。请注意,如果使用了 `--reporter=html`、`--ui` 或 `--browser` 标志,此选项会自动启用。 +套件在模块中定义的位置。仅当配置中启用了 [`includeTaskLocation`](/config/includetasklocation) 时才会收集位置信息。请注意,如果使用了 `--reporter=html`、`--ui` 或 `--browser` 参数,此选项会自动启用。 此套件的位置将等于 `{ line: 3, column: 1 }`: diff --git a/api/advanced/vitest.md b/api/advanced/vitest.md index e7f0c298..bd0857e1 100644 --- a/api/advanced/vitest.md +++ b/api/advanced/vitest.md @@ -187,10 +187,10 @@ function getRelevantTestSpecifications( ): Promise ``` -此方法通过调用 [`project.globTestFiles`](/api/advanced/test-project#globtestfiles) 解析每个测试规范。它接受字符串过滤器以匹配测试文件 - 这些过滤器与 [CLI 支持的过滤器](/guide/filtering#cli) 相同。如果指定了 `--changed` 标志,则列表将被过滤为仅包含已更改的文件。`getRelevantTestSpecifications` 不会运行任何测试文件。 +此方法通过调用 [`project.globTestFiles`](/api/advanced/test-project#globtestfiles) 解析每个测试规范。它接受字符串过滤器以匹配测试文件 - 这些过滤器与 [CLI 支持的过滤器](/guide/filtering#cli) 相同。如果指定了 `--changed` 参数,则列表将被过滤为仅包含已更改的文件。`getRelevantTestSpecifications` 不会运行任何测试文件。 ::: warning -此方法可能很慢,因为它需要过滤 `--changed` 标志。如果我们只需要测试文件列表,请不要使用它。 +此方法可能很慢,因为它需要过滤 `--changed` 参数。如果我们只需要测试文件列表,请不要使用它。 - 如果我们需要获取已知测试文件的规范列表,请使用 [`getModuleSpecifications`](#getmodulespecifications) 代替。 - 如果我们需要获取所有可能的测试文件列表,请使用 [`globTestSpecifications`](#globtestspecifications)。 @@ -216,7 +216,7 @@ function collect(filters?: string[]): Promise 执行测试文件而不运行测试回调。`collect` 返回未处理的错误和 [测试模块](/api/advanced/test-module) 数组。它接受字符串过滤器以匹配测试文件 - 这些过滤器与 [CLI 支持的过滤器](/guide/filtering#cli) 相同。 -此方法根据配置的 `include`、`exclude` 和 `includeSource` 值解析测试规范。有关更多信息,请参阅 [`project.globTestFiles`](/api/advanced/test-project#globtestfiles)。如果指定了 `--changed` 标志,则列表将被过滤为仅包含已更改的文件。 +此方法根据配置的 `include`、`exclude` 和 `includeSource` 值解析测试规范。有关更多信息,请参阅 [`project.globTestFiles`](/api/advanced/test-project#globtestfiles)。如果指定了 `--changed` 参数,则列表将被过滤为仅包含已更改的文件。 ::: warning 请注意,Vitest 不使用静态分析来收集测试。Vitest 将像运行常规测试一样在隔离环境中运行每个测试文件。 @@ -246,9 +246,9 @@ function standalone(): Promise - **别名:** `init` -初始化报告器和覆盖率提供者。此方法不运行任何测试。如果提供了 `--watch` 标志,Vitest 仍将运行更改的测试,即使未调用此方法。 +初始化报告器和覆盖率提供者。此方法不运行任何测试。如果提供了 `--watch` 参数,Vitest 仍将运行更改的测试,即使未调用此方法。 -在内部,仅当启用了 [`--standalone`](/guide/cli#standalone) 标志时才会调用此方法。 +在内部,仅当启用了 [`--standalone`](/guide/cli#standalone) 参数时才会调用此方法。 ::: warning 如果还调用了 [`vitest.start()`](#start),则不应调用此方法。 diff --git a/api/assert-type.md b/api/assert-type.md index 973b9f6c..ef47a942 100644 --- a/api/assert-type.md +++ b/api/assert-type.md @@ -5,7 +5,7 @@ 你可以使用此函数作为 [`expectTypeOf`](/api/expect-typeof) 的替代方法,以轻松地断言参数类型等于提供的泛型。 ::: warning -在运行时,此函数不执行任何操作。要 [启用类型检查](/guide/testing-types#run-typechecking),不要忘记传递 `--typecheck` 标志。 +在运行时,此函数不执行任何操作。要 [启用类型检查](/guide/testing-types#run-typechecking),不要忘记传递 `--typecheck` 参数。 ::: ```ts diff --git a/api/browser/assertions.md b/api/browser/assertions.md index 7906fb4c..babe3e7a 100644 --- a/api/browser/assertions.md +++ b/api/browser/assertions.md @@ -1042,7 +1042,7 @@ function toMatchScreenshot( ::: ::: tip -若截图对比因**有意变更**而失败,可在监听模式下按 `u` 键,或运行测试时加上 `-u`/`--update` 标志,以更新基准图。 +若截图对比因**有意变更**而失败,可在监听模式下按 `u` 键,或运行测试时加上 `-u`/`--update` 参数,以更新基准图。 ::: ```html diff --git a/api/describe.md b/api/describe.md index 6b358cec..d2cce684 100644 --- a/api/describe.md +++ b/api/describe.md @@ -247,7 +247,7 @@ describe.concurrent('suite', () => { - **别名:** `suite.shuffle` -Vitest 通过 CLI 标志 [`--sequence.shuffle`](/guide/cli) 或配置选项 [`sequence.shuffle`](/config/sequence#sequence-shuffle),提供了一种以随机顺序运行所有测试的方法。但如果只想让测试套件的一部分以随机顺序运行,可以用这个标志来标记它。 +Vitest 通过 CLI 参数 [`--sequence.shuffle`](/guide/cli) 或配置选项 [`sequence.shuffle`](/config/sequence#sequence-shuffle),提供了一种以随机顺序运行所有测试的方法。但如果只想让测试套件的一部分以随机顺序运行,可以用这个参数来标记它。 ```ts import { describe, test } from 'vitest' diff --git a/api/expect-typeof.md b/api/expect-typeof.md index cb923736..b3270273 100644 --- a/api/expect-typeof.md +++ b/api/expect-typeof.md @@ -3,7 +3,7 @@ - **类型:** `(a: unknown) => ExpectTypeOf` ::: warning -在运行时,此函数不执行任何操作。要 [enable typechecking](/guide/testing-types#run-typechecking),不要忘记传递 `--typecheck` 标志。 +在运行时,此函数不执行任何操作。要 [enable typechecking](/guide/testing-types#run-typechecking),不要忘记传递 `--typecheck` 参数。 ::: ## not diff --git a/api/test.md b/api/test.md index 4f7e5ded..722591a2 100644 --- a/api/test.md +++ b/api/test.md @@ -411,7 +411,7 @@ vitest interesting.test.ts ``` ::: warning -Vitest 会检测当前是否在 CI 环境中运行,如果有任何测试带有 `only` 标志,将会抛出错误。你可以通过 [`allowOnly`](/config/allowonly) 选项来配置此行为。 +Vitest 会检测当前是否在 CI 环境中运行,如果有任何测试带有 `only` 参数,将会抛出错误。你可以通过 [`allowOnly`](/config/allowonly) 选项来配置此行为。 ::: ## test.concurrent diff --git a/blog/vitest-3-2.md b/blog/vitest-3-2.md index cd9019da..a8de2683 100644 --- a/blog/vitest-3-2.md +++ b/blog/vitest-3-2.md @@ -192,7 +192,7 @@ it('calls console.log', () => { Vitest 现在向测试主体提供一个 [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) 对象。你可以使用它来停止任何支持此 Web API 的资源。 -当测试超时、其他测试失败且 [`--bail` 标志](/config/bail) 设置为非零值,或者用户在终端中按下 Ctrl+C 时,信号会被中止。 +当测试超时、其他测试失败且 [`--bail` 参数](/config/bail) 设置为非零值,或者用户在终端中按下 Ctrl+C 时,信号会被中止。 例如,你可以在测试中断时停止 `fetch` 请求: diff --git a/config/browser/expect.md b/config/browser/expect.md index cd3e2c05..5ee6edab 100644 --- a/config/browser/expect.md +++ b/config/browser/expect.md @@ -225,7 +225,7 @@ type Comparator = ( ::: tip 性能注意事项 `createDiff` 选项表示是否需要生成差异图像。在 [稳定截图检测](/guide/browser/visual-regression-testing#how-visual-tests-work) 过程中,Vitest 会以 `createDiff: false` 调用比较器以避免不必要的计算。 -**请遵守此标志以保持测试速度**。 +**请遵守此参数以保持测试速度**。 ::: warning 处理缺失参数 `toMatchScreenshot()` 中的 `options` 参数是可选的,因此用户可能不会提供所有比较器选项。务必使用默认值使它们成为可选的: diff --git a/config/browser/playwright.md b/config/browser/playwright.md index 8de45262..7595f22a 100644 --- a/config/browser/playwright.md +++ b/config/browser/playwright.md @@ -64,7 +64,7 @@ export default defineConfig({ ::: warning Vitest 将忽略 `launch.headless` 选项。请改用 [`test.browser.headless`](/config/browser/headless)。 -请注意,如果启用了 [`--inspect`](/guide/cli#inspect),Vitest 会将调试标志推送到 `launch.args`。 +请注意,如果启用了 [`--inspect`](/guide/cli#inspect),Vitest 会将调试参数推送到 `launch.args`。 ::: ::: tip 启用新版 Chromium 无头模式 diff --git a/config/chaiconfig.md b/config/chaiconfig.md index ded255a2..3d4c71f2 100644 --- a/config/chaiconfig.md +++ b/config/chaiconfig.md @@ -22,7 +22,7 @@ outline: deep - **类型:** `boolean` - **默认值:** `true` -控制是否在抛出的 AssertionError 中包含 `showDiff` 标志。设为 `false` 将始终禁用差异显示;设为 `true` 则当断言请求显示差异时才会启用。 +控制是否在抛出的 AssertionError 中包含 `showDiff` 参数。设为 `false` 将始终禁用差异显示;设为 `true` 则当断言请求显示差异时才会启用。 ## chaiConfig.truncateThreshold diff --git a/config/exclude.md b/config/exclude.md index e60fb82a..9c4cc40f 100644 --- a/config/exclude.md +++ b/config/exclude.md @@ -15,7 +15,7 @@ Vitest 使用 [`tinyglobby`](https://npmx.dev/package/tinyglobby) 包来解析 g ::: warning 该配置项不影响代码覆盖率。如需从覆盖率报告中排除特定文件,请使用 [`coverage.exclude`](/config/coverage#exclude)。 -如果使用命令行参数,这是唯一一个不会被覆盖配置项。通过 `--exclude` 标志添加的所有 glob 规则都将追加到 `exclude` 中。 +如果使用命令行参数,这是唯一一个不会被覆盖配置项。通过 `--exclude` 参数添加的所有 glob 规则都将追加到 `exclude` 中。 ::: ## 示例 {#example} diff --git a/config/experimental.md b/config/experimental.md index 4b3f6e66..f44067d9 100644 --- a/config/experimental.md +++ b/config/experimental.md @@ -293,7 +293,7 @@ vitest --experimental.importDurations.failOnDanger - 测试文件及源码不会经过 Vite 处理 - 全局初始化文件不会被处理 - 自定义运行器 / 池 / 环境文件不会被处理 -- 配置文件仍由 Vite 处理(该过程发生在 Vitest 获知 `viteModuleRunner` 标志之前执行) +- 配置文件仍由 Vite 处理(该过程发生在 Vitest 获知 `viteModuleRunner` 参数之前执行) ::: warning 当前 Vitest 仍需依赖 Vite 实现某些功能,如模块图或监视模式。 @@ -427,7 +427,7 @@ interface VCSProviderOptions { - **默认值:** `'git'` -用于检测更改文件的自定义驱动。与 [`--changed`](/guide/cli#changed) 标志配合使用,用于确定哪些文件已被修改。 +用于检测更改文件的自定义驱动。与 [`--changed`](/guide/cli#changed) 参数配合使用,用于确定哪些文件已被修改。 默认情况下,Vitest 使用 Git 检测更改的文件。你可以提供 `VCSProvider` 接口的自定义实现以使用不同的版本控制系统: @@ -488,7 +488,7 @@ export default { 在运行测试前预解析测试规范。这会在所有文件中应用 [`.only`](/api/test#test-only) 修饰符、[`-t`](/config/testnamepattern) 测试名称模式、[`--tags-filter`](/guide/test-tags#syntax)、[测试行号](/api/advanced/test-specification#testlines) 和 [测试ID](/api/advanced/test-specification#testids) 而无需执行它们。例如,如果只有一个测试标记了 `.only`,Vitest 将跳过所有其他文件中的测试。 ::: tip -使用 [`.only`](/api/test#test-only)、[`-t`](/config/testnamepattern) 标志或 [`--tags-filter`](/guide/test-tags#syntax) 时推荐启用此选项。 +使用 [`.only`](/api/test#test-only)、[`-t`](/config/testnamepattern) 参数或 [`--tags-filter`](/guide/test-tags#syntax) 时推荐启用此选项。 无条件启用可能会因额外的解析步骤而降低测试运行速度。 ::: diff --git a/config/stricttags.md b/config/stricttags.md index c6b6ac69..a54e8a40 100644 --- a/config/stricttags.md +++ b/config/stricttags.md @@ -10,9 +10,9 @@ outline: deep - **命令行终端:** `--strict-tags`, `--no-strict-tags` 如果测试使用了未在配置中定义的 [`tag`](/config/tags),Vitest 是否应抛出错误,以避免因拼写错误导致意外的行为(应用错误的配置或因 -`--tags-filter` 标志而跳过测试)。 +`--tags-filter` 参数而跳过测试)。 -注意,如果 `--tags-filter` 标志定义了配置中不存在的标签,Vitest 将会抛出错误。 +注意,如果 `--tags-filter` 参数定义了配置中不存在的标签,Vitest 将会抛出错误。 例如,以下测试将因标签 `fortnend` 存在拼写错误(正确应为 `frontend`)而抛出错误: diff --git a/config/watch.md b/config/watch.md index 3822895c..f65c3246 100644 --- a/config/watch.md +++ b/config/watch.md @@ -13,4 +13,4 @@ outline: deep 交互式环境中,默认启用监听模式,除非显式传入 `--run`。 -在 CI 或非交互式 shell 中,监听模式默认关闭,但可通过该标志显式启用。 +在 CI 或非交互式 shell 中,监听模式默认关闭,但可通过该参数显式启用。 diff --git a/eslint.config.js b/eslint.config.js index fd94fb39..2ee0d214 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -75,6 +75,7 @@ export default antfu( 'no-self-compare': 'off', 'import/no-mutable-exports': 'off', 'no-throw-literal': 'off', + 'markdown/no-missing-link-fragments': 'off', }, }, createSimplePlugin({ diff --git a/guide/advanced/reporters.md b/guide/advanced/reporters.md index 7a5e7e4c..721d849e 100644 --- a/guide/advanced/reporters.md +++ b/guide/advanced/reporters.md @@ -71,22 +71,22 @@ class MyReporter implements Reporter { } } ``` - -## Storing artifacts on file system + +## 在文件系统上存储附件 {#storing-artifacts-on-file-system} ::: tip -Vitest provides [`vitest.createReport`](/api/advanced/vitest.html#createreport) that exposes collection of utilities for writing artifacts on file system conveniently. +Vitest 提供了 [`vitest.createReport`](/api/advanced/vitest.html#createreport),它公开了一组工具函数,用于在文件系统上写入附件。 ::: -If your custom reporter needs to store any artifacts on file system it should place them inside `.vitest` directory. This directory is a convention that Vitest reporters and third party integrations can use to co-locate their results in a single directory. This way users of your custom reporter do not need to add multiple exclusion in their `.gitignore`. Only the `.vitest` is needed. +如果你的自定义报告器需要在文件系统上存储任何附件,应该将它们放在 `.vitest` 目录中。这个目录是一个约定,Vitest 报告器和第三方集成可以使用它将结果放在同一个目录中。这样,你的自定义报告器的用户就不需要在他们的 `.gitignore` 中添加多个排除项。只需要排除 `.vitest` 即可。 -Reporters and other integrations should respect following rules around `.vitest` directory: +报告器和其他集成应遵守以下关于 `.vitest` 目录的规则: -- `.vitest` directory is placed in [the `root` of the project](/config/root) -- Reporter can create `.vitest` directory if it does not already exist -- Reporter should never remove `.vitest` directory -- Reporter should create their own directory inside `.vitest`, for example `.vitest/yaml-reporter/` -- Reporter can remove their own specific directory inside `.vitest`, for example `.vitest/yaml-reporter/` +- `.vitest` 目录位于项目的 [根目录](/config/root) +- 如果 `.vitest` 目录不存在,报告器将自行创建 +- 报告器绝不会删除 `.vitest` 目录 +- 报告器会在 `.vitest` 内创建自己的目录,例如 `.vitest/yaml-reporter/` +- 报告器会删除其在 `.vitest` 内的特定目录,例如 `.vitest/yaml-reporter/` ```ansi .vitest diff --git a/guide/advanced/tests.md b/guide/advanced/tests.md index 3e70c0dc..785e13a3 100644 --- a/guide/advanced/tests.md +++ b/guide/advanced/tests.md @@ -67,7 +67,7 @@ finally { } ``` -如果我们打算保留 `Vitest` 实例,请确保至少调用 [`init`](/api/advanced/vitest#init) 。这将初始化报告器和覆盖率提供者,但不会运行任何测试。即使我们不打算使用 Vitest 观察器,但希望保持实例运行,也建议启用 `watch` 模式。Vitest 依赖此标志使其某些功能在连续过程中正常工作。 +如果我们打算保留 `Vitest` 实例,请确保至少调用 [`init`](/api/advanced/vitest#init) 。这将初始化报告器和覆盖率提供者,但不会运行任何测试。即使我们不打算使用 Vitest 观察器,但希望保持实例运行,也建议启用 `watch` 模式。Vitest 依赖此参数使其某些功能在连续过程中正常工作。 报告器初始化后,如果需要手动运行测试,可以使用 [`runTestSpecifications`](/api/advanced/vitest#runtestspecifications) 或 [`rerunTestSpecifications`](/api/advanced/vitest#reruntestspecifications) 来运行测试。 diff --git a/guide/browser/index.md b/guide/browser/index.md index c6b0ec06..bb94b4b5 100644 --- a/guide/browser/index.md +++ b/guide/browser/index.md @@ -306,7 +306,7 @@ Vitest 使用 [Vite dev server](https://cn.vitejs.dev/guide/#browser-support) ## 运行测试 {#running-tests} -要使用 CLI 指定浏览器,请使用 `--browser` 标志后跟浏览器名称,如下所示: +要使用 CLI 指定浏览器,请使用 `--browser` 参数后跟浏览器名称,如下所示: ```sh npx vitest --browser=chromium @@ -330,7 +330,7 @@ Vitest 默认会在开发模式下自动打开浏览器界面,测试会在页 无头模式是浏览器模式下可用的另一个选项。在无头模式下,浏览器在没有用户界面的情况下在后台运行,这对于运行自动化测试非常有用。Vitest 中的 headless 选项可以设置为布尔值以启用或禁用无头模式。 -在使用无头模式时,Vitest 不会自动打开用户界面。如果我们希望继续使用用户界面,同时让测试以 无头模式运行,我们可以安装 [`@vitest/ui`](/guide/ui) 包,并在运行Vitest时传递 `--ui` 标志。 +在使用无头模式时,Vitest 不会自动打开用户界面。如果我们希望继续使用用户界面,同时让测试以 无头模式运行,我们可以安装 [`@vitest/ui`](/guide/ui) 包,并在运行Vitest时传递 `--ui` 参数。 这是启用无头模式的示例配置: @@ -349,7 +349,7 @@ export default defineConfig({ }) ``` -你还可以在 CLI 中使用 `--browser.headless` 标志设置无头模式,如下所示: +你还可以在 CLI 中使用 `--browser.headless` 参数设置无头模式,如下所示: ```sh npx vitest --browser.headless diff --git a/guide/browser/multiple-setups.md b/guide/browser/multiple-setups.md index ffc0f3a1..9a36ddcb 100644 --- a/guide/browser/multiple-setups.md +++ b/guide/browser/multiple-setups.md @@ -82,7 +82,7 @@ test('ratio works', () => { ## 过滤 {#filtering} -你可以使用 [`--project` 标志](/guide/cli#project) 来过滤要运行的项目。如果未手动分配项目名称,Vitest 会自动将浏览器名称作为项目名称。如果根配置已经有一个名称,Vitest 会将它们合并:`custom` -> `custom (browser)`。 +你可以使用 [`--project` 参数](/guide/cli#project) 来过滤要运行的项目。如果未手动分配项目名称,Vitest 会自动将浏览器名称作为项目名称。如果根配置已经有一个名称,Vitest 会将它们合并:`custom` -> `custom (browser)`。 ```shell $ vitest --project=chromium diff --git a/guide/cli-generated.md b/guide/cli-generated.md index 045c7d1a..c2d59b16 100644 --- a/guide/cli-generated.md +++ b/guide/cli-generated.md @@ -298,13 +298,13 @@ Coverage reporters to use. Visit [`coverage.reporter`](/config/coverage#coverage - **配置:** [coverage.htmlDir](/config/coverage#coverage-htmldir) UI 模式和 HTML 报告器中提供的 HTML 覆盖率输出目录。 - + ### coverage.autoAttachSubprocess -- **CLI:** `--coverage.autoAttachSubprocess` -- **Config:** [coverage.autoAttachSubprocess](/config/coverage#coverage-autoattachsubprocess) +- **命令行终端:** `--coverage.autoAttachSubprocess` +- **配置:** [coverage.autoAttachSubprocess](/config/coverage#coverage-autoattachsubprocess) -Track coverage of the `node:child_process` and `node:worker_threads` spawned during test run. Supported only by `v8` provider. (default: false) +跟踪测试运行期间生成的 `node:child_process` 和 `node:worker_threads` 的覆盖率。仅 `v8` 提供程序支持。(默认值:false) ### mode diff --git a/guide/cli.md b/guide/cli.md index 5fcedf99..1a4a4d3e 100644 --- a/guide/cli.md +++ b/guide/cli.md @@ -104,15 +104,15 @@ describe > some-test > test 1 describe > some-test > test 2 ``` -你可以传递 `--json` 标志以 JSON 格式打印测试,也可以将其保存在单独的文件中: +你可以传递 `--json` 参数以 JSON 格式打印测试,也可以将其保存在单独的文件中: ```bash vitest list filename.spec.ts -t="some-test" --json=./file.json ``` -如果 `--json` 标志没有接收到值,它将把 JSON 输出到 stdout 中。 +如果 `--json` 参数没有接收到值,它将把 JSON 输出到 stdout 中。 -你还可以传递 `--filesOnly` 标志来仅打印测试文件: +你还可以传递 `--filesOnly` 参数来仅打印测试文件: ```bash vitest list --filesOnly diff --git a/guide/common-errors.md b/guide/common-errors.md index 5ba0da7d..28bd9f49 100644 --- a/guide/common-errors.md +++ b/guide/common-errors.md @@ -87,6 +87,7 @@ export default defineConfig({ ::: tip 为什么是 `ssr.resolve.conditions` 而不是 `resolve.conditions`? Vitest 遵循 Vite 的配置约定: + - [`resolve.conditions`](https://cn.vite.dev/config/shared-options#resolve-conditions) 适用于 Vite 的 `client` 环境,对应 Vitest 的浏览器模式、jsdom、happy-dom,以及使用 `viteEnvironment: 'client'` 的自定义环境。 - [`ssr.resolve.conditions`](https://cn.vite.dev/config/ssr-options#ssr-resolve-conditions) 适用于 Vite 的 `ssr` 环境,对应 Vitest 的 node 环境或使用 `viteEnvironment: 'ssr'` 的自定义环境。 @@ -167,20 +168,20 @@ test('rejects for missing user', async () => { await expect(fetchUser(123)).rejects.toThrow('User 123 not found') }) ``` - -## Package fails to load in Vitest but works in your app -Some packages work in an app build but fail in Vitest because they are only valid after a bundler has rewritten or resolved them. When Vitest externalizes a dependency, Node.js loads it directly, so Node's ESM and package rules apply. See Node.js documentation on [ECMAScript modules](https://nodejs.org/docs/latest/api/esm.html) and [packages](https://nodejs.org/docs/latest/api/packages.html) for the precise rules. +## Package 在 Vitest 中加载失败但在你的应用中正常工作 {#fails-to-load-in-vitest-but-works-in-your-app} + +有些包在应用构建中可以正常工作,但在 Vitest 中会失败,因为它们只有在经过打包器重写或解析后才是有效的。当 Vitest 将某个依赖外部化时,Node.js 会直接加载它,因此 Node 的 ESM 和包规则适用。请参阅 Node.js 关于 [ECMAScript 模块](https://nodejs.org/docs/latest/api/esm.html) 和 [packages](https://nodejs.org/docs/latest/api/packages.html) 的文档以了解具体规则。 -Common examples include packages that: +常见的例子包括以下类型的包: -- ship ESM syntax in `.js` files without `"type": "module"` -- use extensionless relative imports in ESM files -- have incorrect `exports`, `imports`, `main`, or `module` entries -- mix CommonJS and ESM entry points in a way that only works after bundling -- import CSS or other non-JavaScript files that are expected to be handled by a bundler +- 在 `.js` 文件中提供 ESM 语法但没有 `"type": "module"` +- 在 ESM 文件中使用无扩展名的相对导入 +- 具有错误的 `exports`、`imports`、`main` 或 `module` 配置项 +- 以仅适用于打包后的方式混合 CommonJS 和 ESM 入口点 +- 导入 CSS 或其他应由打包器处理的非 JavaScript 文件 -You might see errors such as: +你可能会看到如下错误: - `Cannot find module './relative-path' imported from ...` - `Unexpected token 'export'` @@ -188,9 +189,9 @@ You might see errors such as: - `Module ... seems to be an ES Module but shipped in a CommonJS package.` - `Unknown file extension ".css"` -When possible, fix the package so Node.js can load it directly: add `"type": "module"` for ESM `.js` files, use `.mjs`, include explicit file extensions in ESM imports, and make sure `exports` points to files Node.js can load. +如果可能,应修复该包,使 Node.js 可以直接加载它:为 ESM `.js` 文件添加 `"type": "module"`,使用 `.mjs`,在 ESM 导入中包含显式的文件扩展名,并确保 `exports` 指向 Node.js 可以加载的文件。 -If you cannot fix the package itself, inline it so Vite handles it instead of passing it to Node.js as an external dependency. Inline the whole dependency chain that leads to the invalid package. If your source imports `wrapper-package`, and `wrapper-package` imports `broken-package`, inline both packages: +如果你无法修复包本身,请将其内联,以便让 Vite 处理它,而不是将其作为外部依赖传递给 Node.js。将通向该无效包的整个依赖链都内联进来。如果你的源码导入了 `wrapper-package`,而 `wrapper-package` 导入 `broken-package`,请内联这两个包: ```ts [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -206,7 +207,7 @@ export default defineConfig({ }) ``` -You can also use Vite's [`ssr.resolve.noExternal`](https://vite.dev/config/ssr-options#ssr-resolve-noexternal) for the same purpose. Vitest merges `ssr.resolve.noExternal` into [`server.deps.inline`](/config/server#server-deps-inline), so this is useful when the dependency also needs to be bundled by Vite in SSR builds: +你也可以使用 Vite 的 [`ssr.resolve.noExternal`](https://vite.dev/config/ssr-options#ssr-resolve-noexternal) 达到相同目的。适用于当依赖在 SSR 构建中也需要由 Vite 打包时,Vitest 将 `ssr.resolve.noExternal` 合并到 [`server.deps.inline`](/config/server#server-deps-inline) 中: ```ts [vitest.config.js] import { defineConfig } from 'vitest/config' diff --git a/guide/comparisons.md b/guide/comparisons.md index 195abb7c..66c05bce 100644 --- a/guide/comparisons.md +++ b/guide/comparisons.md @@ -69,7 +69,7 @@ Vitest 还针对多项功能提供了开箱即用的支持,而这些功能在 尽管 Mocha 支持原生 ESM,但存在功能限制和配置约束。例如监听模式无法处理 ES 模块文件。 -在性能方面,Mocha 默认串行运行测试,但支持使用 `--parallel` 标志启用并行执行(不过部分报告器和功能在并行模式下不可用)。 +在性能方面,Mocha 默认串行运行测试,但支持使用 `--parallel` 参数启用并行执行(不过部分报告器和功能在并行模式下不可用)。 如果你的构建流程已使用 Vite,Vitest 允许复用相同的配置和插件进行测试,而 Mocha 则需要独立的测试配置。Vitest 提供与 Jest 兼容的 API,同时支持 Mocha 惯用的 `describe`、`it` 和钩子语法,使得大多数测试套件的迁移非常便捷。 diff --git a/guide/extending-matchers.md b/guide/extending-matchers.md index d7b9105e..bfcc4645 100644 --- a/guide/extending-matchers.md +++ b/guide/extending-matchers.md @@ -39,7 +39,7 @@ declare module 'vitest' { 导入 `vitest` 会使 TypeScript 将其视为 ES 模块文件,若无此声明则类型检查将无法生效。 ::: -扩展 `Matchers` 接口,让 `expect.extend` 、`expect().*` 和 `expect.*` 方法同时具备类型安全的断言支持。 +扩展 `Matchers` 接口,让 `expect.extend`、`expect().*` 和 `expect.*` 方法同时具备类型安全的断言支持。 ::: warning 不要忘记在 `tsconfig.json` 中包含声明文件。 @@ -59,7 +59,7 @@ interface MatcherResult { ``` ::: warning -如果你实现了一个异步匹配器,记得在测试里对它的结果使用 `await` (例如:`await expect('foo').toBeFoo()` ),否则可能不会按预期执行: +如果你实现了一个异步匹配器,记得在测试里对它的结果使用 `await`(例如:`await expect('foo').toBeFoo()`),否则可能不会按预期执行: ```ts expect.extend({ @@ -70,6 +70,7 @@ expect.extend({ await expect().toBeAsyncAssertion() ``` + ::: 断言的第一个参数是接收值(即 `expect(received)` 中的 received ),其余参数将直接传给断言。其余参数将直接传递给匹配器。自 4.1 起,Vitest 提供了多个类型供自定义匹配器使用: @@ -106,16 +107,16 @@ function customMatcher(this: MatcherState, received: unknown, arg1: unknown, arg expect.extend({ customMatcher }) ``` - + ::: tip -To build custom **snapshot matchers** (wrappers around `toMatchSnapshot()` / `toMatchInlineSnapshot()` / `toMatchFileSnapshot()`), use `Snapshots` exported from `vitest`. See [Custom Snapshot Matchers](/guide/snapshot#custom-snapshot-matchers). +要构建自定义的 **快照匹配器**(`toMatchSnapshot()`/`toMatchInlineSnapshot()`/`toMatchFileSnapshot()` 的包装器),请使用从 `vitest` 导出的 `Snapshots`。请参阅 [自定义快照匹配器](/guide/snapshot#custom-snapshot-matchers)。 ::: 断言方法可以访问上下文 `this` 对象中的这些属性: ## `isNot` -如果断言是在 `not` 方法上调用的( `expect(received).not.toBeFoo()` ),则返回 true。你无需手动处理该逻辑,Vitest 会自动反转 `pass` 的值。 +如果断言是在 `not` 方法上调用的(`expect(received).not.toBeFoo()`),则返回 true。你无需手动处理该逻辑,Vitest 会自动反转 `pass` 的值。 ## `promise` @@ -137,10 +138,10 @@ To build custom **snapshot matchers** (wrappers around `toMatchSnapshot()` / `to ## `task` 4.1.0 {#task} -Contains a reference to [the `Test` runner task](/api/advanced/runner#tasks) when available. +包含对 [测试运行器任务](/api/advanced/runner#tasks) 的引用(如果可用)。 ::: warning -When using the global `expect` with concurrent tests, `this.task` is `undefined`. Use `context.expect` instead to ensure `task` is available in custom matchers. +当在并发测试中使用全局 `expect` 时,`this.task` 为 `undefined`。请改用 `context.expect` 以确保 `task` 在自定义匹配器中可用。 ::: ## `testPath` @@ -157,7 +158,7 @@ When using the global `expect` with concurrent tests, `this.task` is `undefined` ## `assertion` 4.1.4 {#assertion} -底层 [Chai 断言](https://www.chaijs.com/guide/plugins/) 对象。这是与 Chai 插件接收的同一个实例,使你能够访问 Chai 的标志系统和可链式方法。适用于需要与 Chai 内部交互的自定义匹配器。 +底层 [Chai 断言](https://www.chaijs.com/guide/plugins/) 对象。这是与 Chai 插件接收的同一个实例,使你能够访问 Chai 的参数系统和可链式方法。适用于需要与 Chai 内部交互的自定义匹配器。 ::: tip 以上并非全部可用属性,仅列出最实用的部分。其他状态值由 Vitest 内部使用。 diff --git a/guide/features.md b/guide/features.md index b4a5caf5..19bc5191 100644 --- a/guide/features.md +++ b/guide/features.md @@ -13,21 +13,17 @@ import FeaturesList from '../.vitepress/components/FeaturesList.vue' 通过视频了解如何编写你的第一个测试 -## 一套配置可以运用在多种环境 {#shared-config-between-test-dev-and-build} - -
- ::: tip 本页为 Vitest 核心功能的概览指南。如果你初次接触 Vitest,建议先学习 [入门](/guide/learn/writing-tests) 教程,通过实践演练快速掌握测试编写基础。 ::: -## Shared Config between Test, Dev and Build +## 测试、开发与构建之间共享配置 {#shared-config-between-test-dev-and-build} 与 Vite 的配置、转换器、解析器和插件通用,将会使用应用中的相同配置来运行测试。 -更多详情请参阅 [配置 Vitest](/config/) 。 +更多详情请参阅 [配置 Vitest](/config/)。 -## 监听模式(watch mode) {#watch-mode} +## 监听模式 (watch mode) {#watch-mode} ```bash $ vitest @@ -37,7 +33,7 @@ $ vitest `vitest` **在开发环境下默认** 启动时使用 `监听模式`,在 CI 环境(当 `process.env.CI` 出现时)中以 `运行模式(run mode)` 启动。你可以使用 `vitest watch` 或 `vitest run` 明确指定所需的模式。 -使用 `--standalone` 标志启动 Vitest,使其在后台运行。它不会运行任何测试,直到测试发生变化。如果源代码发生变化,Vitest 不会运行测试,直到运行了导入源代码的测试为止 +使用 `--standalone` 参数启动 Vitest,使其在后台运行。它不会运行任何测试,直到测试发生变化。如果源代码发生变化,Vitest 不会运行测试,直到运行了导入源代码的测试为止 ## 开箱即用的常见 Web 支持 {#common-web-idioms-out-of-the-box} @@ -49,11 +45,11 @@ $ vitest Vitest 还隔离了每个测试文件的运行环境,因此一个文件中的运行环境改变不会影响其他文件。可以通过将 `--no-isolate` 传递给 CLI 来禁用隔离(以正确性换取运行性能)。 -## 测试可过滤 {#test-filtering} +## 测试筛选 {#test-filtering} Vitest 提供了许多缩小测试范围的方法,以便在开发过程中加快速度并集中精力。 -了解更多信息 [测试筛选](/guide/filtering) 。 +了解更多信息 [测试筛选](/guide/filtering)。 ## 同时运行多个测试 {#running-tests-concurrently} @@ -145,12 +141,15 @@ expect(fn.mock.results[1].value).toBe('world') Vitest 支持 [happy-dom](https://github.com/capricorn86/happy-dom) 或 [jsdom](https://github.com/jsdom/jsdom) 来模拟 DOM 和浏览器 API。Vitest 并不内置它们,所以你可能需要安装: ::: code-group + ```bash [happy-dom] $ npm i -D happy-dom ``` + ```bash [jsdom] $ npm i -D jsdom ``` + ::: 然后,更改 `environment` 配置文件中的选项: @@ -165,7 +164,7 @@ export default defineConfig({ }) ``` -了解更多信息 [模拟对象](/guide/mocking) 。 +了解更多信息 [模拟对象](/guide/mocking)。 ## 测试覆盖率 {#coverage} @@ -195,7 +194,7 @@ export default defineConfig({ }) ``` -了解更多信息 [覆盖率](/guide/coverage) 。 +了解更多信息 [覆盖率](/guide/coverage)。 ## 源码内联测试 {#in-source-testing} @@ -267,7 +266,7 @@ test('my types work properly', () => { ## 分片 {#sharding} -使用 [`--shard`](/guide/cli#shard) 和 [`--reporter=blob`](/guide/reporters#blob-reporter)标志在不同的计算机上运行测试。可以使用 `--merge-reports` 命令在 CI 管道的末尾合并所有测试结果: +使用 [`--shard`](/guide/cli#shard) 和 [`--reporter=blob`](/guide/reporters#blob-reporter) 参数在不同的计算机上运行测试。可以使用 `--merge-reports` 命令在 CI 管道的末尾合并所有测试结果: ```bash vitest --shard=1/2 --reporter=blob --coverage @@ -300,6 +299,7 @@ export default defineConfig(({ mode }) => ({ 你可以通过手动捕获这些错误来禁用此行为。Vitest 会认为回调已由你处理,不会再报告该错误。 ::: code-group + ```ts [setup.node.js] // 在 Node.js process.on('unhandledRejection', () => { @@ -310,6 +310,7 @@ process.on('uncaughtException', () => { // 你自己的处理程序 }) ``` + ```ts [setup.browser.js] // 在浏览器 window.addEventListener('error', () => { @@ -320,6 +321,7 @@ window.addEventListener('unhandledrejection', () => { // 你自己的处理程序 }) ``` + ::: 或者,你也可以使用 [`dangerouslyIgnoreUnhandledErrors`](/config/dangerouslyignoreunhandlederrors) 选项来忽略报告的错误。Vitest 仍会报告它们,但它们不会影响测试结果(退出码不会改变)。 diff --git a/guide/filtering.md b/guide/filtering.md index f21991b4..93084c24 100644 --- a/guide/filtering.md +++ b/guide/filtering.md @@ -1,38 +1,39 @@ --- title: 测试筛选 | 指南 --- - + # 测试筛选 {#test-filtering} -As your test suite grows, running every test on every change becomes slow and distracting. If you're fixing a bug in a single module, you don't need to wait for hundreds of unrelated tests to finish. Test filtering lets you narrow down which tests run so you can stay focused on the code you're actively working on. +随着测试套件不断增长,每次改动都运行全部测试会变得缓慢且干扰开发节奏。如果你只是在修复某个模块中的一个 bug,就没必要等待数百个无关测试全部跑完。测试过滤可以让你缩小执行范围,只运行当前正在处理的代码相关测试,从而更专注地开发。 -Vitest offers several ways to filter tests: from the command line, inside your test files, and through tags. Each approach is useful in different situations. +Vitest 提供了多种过滤测试的方式:可以通过命令行、在测试文件内部,或使用标签来过滤。不同的方法适用于不同的场景。 -::: tip Performance Note -Filters like `-t`, `--tags-filter`, `.only`, and `.skip` are applied *per test file* — Vitest still has to run each test file to discover which tests match. In a large project, this overhead adds up even if only a few tests actually execute. +::: tip 性能说明 +像 `-t`、`--tags-filter`、`.only` 和 `.skip` 这样的过滤方式,都是按 _文件级_ 应用的。也就是说,Vitest 仍然需要运行每个测试文件,才能找出哪些测试符合条件。在大型项目中,即使最终真正执行的测试只有少数几个,这部分开销也会逐渐累积变大。 -To avoid this, always pass a file path alongside your filter so Vitest only loads the files you care about: +为了避免这种情况,建议在使用过滤条件时同时传入文件路径,这样 Vitest 就只会加载你关注的哪些文件: ```bash vitest utils.test.ts -t "handles empty input" ``` -Alternatively, you can use the [`--experimental.preParse`](/config/experimental#experimental-preparse) flag, which parses test files to discover test names without fully executing them: +另外,你也可以使用 [`--experimental.preParse`](/config/experimental#experimental-preparse) 参数。它会通过解析测试文件来发现测试名称,而不需要完整执行这些文件: ```bash vitest --experimental.preParse -t "handles empty input" ``` + ::: -## Filtering by File Name +## 按文件名过滤 {#filtering-by-file-name} -The simplest way to run a subset of tests is to pass a filename pattern as a CLI argument. Vitest will only run test files whose path contains the given string: +在命令行参数中传入文件名的形式,是运行部分测试最简单的方式。Vitest 只会运行路径中包含该字符串的测试文件: ```bash vitest basic ``` -This matches any test file with `basic` in its path: +匹配路径中包含 `basic` 的任意测试文件: ``` basic.test.ts @@ -40,52 +41,52 @@ basic-foo.test.ts basic/foo.test.ts ``` -This is useful when you know which file you need to work on and want to skip everything else. +适用于明确知道需要处理哪些文件,并希望跳过其他所有内容。 -## Filtering by Test Name +## 按测试名称过滤 {#filtering-by-test-name} -Sometimes the test you care about is buried in a file with many other tests. The `-t` (or `--testNamePattern`) option filters by the test's name rather than the filename. It accepts a regex pattern and matches against the full test name, which includes any `describe` block names: +有时,你关心的那个测试会埋在一个包含许多其他测试的文件里。`-t`(或 `--testNamePattern`)选项会按测试名称而不是文件名进行过滤。它接受一个正则表达式,并会匹配完整的测试名称,其中也包括所有 `describe` 代码块的名称: ```bash vitest -t "handles empty input" ``` -You can combine this with a file filter to narrow things down further: +你可以与文件过滤器结合使用,进一步缩小范围: ```bash vitest utils -t "handles empty input" ``` -This runs only tests whose name matches `"handles empty input"` inside files matching `utils`. +这仅运行匹配 `utils` 的文件中名称匹配 `"handles empty input"` 的测试。 -## Filtering by Line Number +## 按行号过滤 {#filtering-by-line-number} -When you're looking at a specific test in your editor, you often just want to run *that one test*. You can point directly to a line number: +当你在编辑器里查看某个具体测试时,通常只想运行那 _一个测试_。你可以直接指定对应的行号: ```bash vitest basic/foo.test.ts:10 ``` -Vitest will run the test that contains line 10. This requires the full filename (relative or absolute): +Vitest 将运行包含第 10 行的测试。这需要完整的文件名(相对路径或绝对路径): ```bash vitest basic/foo.test.ts:10 # ✅ vitest ./basic/foo.test.ts:10 # ✅ vitest /users/project/basic/foo.test.ts:10 # ✅ -vitest foo:10 # ❌ partial name won't work -vitest ./basic/foo:10 # ❌ missing file extension +vitest foo:10 # ❌ 部分名称无效 +vitest ./basic/foo:10 # ❌ 缺少文件扩展名 ``` -To run multiple specific tests, separate them with spaces: +要运行多个特定测试,用空格分隔它们: ```bash vitest basic/foo.test.ts:10 basic/foo.test.ts:25 # ✅ -vitest basic/foo.test.ts:10-25 # ❌ ranges are not supported +vitest basic/foo.test.ts:10-25 # ❌ 不支持范围 ``` -## Filtering by Tags +## 按标签过滤 {#filtering-by-tags} -For larger projects, you may want to categorize tests and run them by category. [Tags](/guide/test-tags) let you label tests and then filter by those labels from the CLI: +对于更大的项目,你可能希望对测试进行分类,并按类别运行它们。通过 [标签](/guide/test-tags),可以让你为测试添加标记,然后通过命令行按这些标签进行过滤: ```ts test('renders a form', { tags: ['frontend'] }, () => { @@ -101,70 +102,70 @@ test('calls an external API', { tags: ['backend'] }, () => { vitest --tags-filter=frontend ``` -This is particularly helpful in CI pipelines where you might want to run frontend and backend tests in separate jobs, or skip slow integration tests during quick checks. +适合在 CI 流水线中使用,例如你可能希望在不同的任务中分别运行前端测试和后端测试,或者在快速检查时跳过耗时较长的集成测试。 -## Focusing on Specific Tests with `.only` +## 使用 `.only` 聚焦特定测试 {#focusing-on-specific-tests-with--only} -When you're debugging a failing test, you want to run just that test without modifying CLI arguments every time. Adding `.only` to a test or suite tells Vitest to skip everything else in the file: +当你调试失败的测试时,希望只运行该测试而无需每次都修改 CLI 参数。在测试用例或测试套件中添加 `.only` 会告诉 Vitest 跳过文件中的所有其他内容: ```ts import { describe, expect, it } from 'vitest' describe.only('suite', () => { it('test', () => { - // This runs because the suite is marked with .only + // 仅有这个会运行,因为测试套件被标记为 .only expect(Math.sqrt(4)).toBe(2) }) }) describe('another suite', () => { it('skipped test', () => { - // This does not run + // 这个不会运行 expect(Math.sqrt(4)).toBe(2) }) it.only('focused test', () => { - // This also runs because it is marked with .only + // 这个也会运行,因为它被标记为 .only expect(Math.sqrt(4)).toBe(2) }) }) ``` -You can use `.only` on both `describe` blocks and individual tests. When any test or suite in a file is marked with `.only`, all unmarked tests in that file are skipped. +你可以在 `describe` 块和单个测试上使用 `.only`。当文件中任何测试或测试套件被标记为 `.only` 时,该文件中所有未标记的测试都会被跳过。 ::: warning -Remember to remove `.only` before committing. By default, Vitest will fail the entire test run if it encounters `.only` in CI (when `process.env.CI` is set), preventing you from accidentally skipping tests in your pipeline. This behavior is controlled by the [`allowOnly`](/config/allowonly) option. +请记得在提交前移除 `.only`。默认情况下,在 CI 环境中(即设置了 `process.env.CI` 时), Vitest 遇到 `.only` 会使整个测试运行失败,以防你在流水线中意外跳过测试。此行为由 [`allowOnly`](/config/allowonly) 选项控制。 -To catch `.only` even earlier, the [`no-focused-tests`](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-focused-tests.md) ESLint rule (also available in [oxlint](https://oxc.rs/docs/guide/usage/linter/rules/jest/no-focused-tests.html)) can flag it in your editor before you commit. +为了更早地捕获 `.only`,[`no-focused-tests`](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/no-focused-tests.md) ESLint 规则(在 [oxlint](https://oxc.rs/docs/guide/usage/linter/rules/jest/no-focused-tests.html) 中也可用)这样你在提交前就能在编辑器里发现它。 ::: -## Skipping Tests with `.skip` +## 使用 `.skip` 跳过测试 {#skipping-tests-with-skip} -The opposite of `.only` is `.skip`. Use it to temporarily disable a test or suite without deleting it. Skipped tests still show up in the report so you don't forget about them: +`.skip` 与 `.only` 正好相反。使用它可以临时禁用某个测试或测试套件而无需删除它。被跳过的测试仍会显示在报告中,这样你就不会忘记它们: ```ts import { describe, expect, it } from 'vitest' describe.skip('skipped suite', () => { it('test', () => { - // This entire suite is skipped + // 整个测试套件都被跳过 expect(Math.sqrt(4)).toBe(2) }) }) describe('suite', () => { it.skip('skipped test', () => { - // Just this one test is skipped + // 只有这个测试被跳过 expect(Math.sqrt(4)).toBe(2) }) }) ``` -This is useful when a test is flaky or depends on an external service that's temporarily down. It lets you keep the test in place as a reminder while unblocking the rest of the suite. +它让你可以保留测试作为提醒,同时不影响套件的其他部分运行,适用于测试不稳定或依赖于暂时不可用的外部服务。 -## Placeholder Tests with `.todo` +## 使用 `.todo` 作为占位测试 {#placeholder-tests-with-todo} -When planning new features, you might know what tests you'll need before you write the actual implementation. `.todo` marks a test as planned but not yet written. It shows up in the report as a reminder: +在规划新功能时,你可能在编写实际实现之前,就知道需要哪些测试。`.todo` 用于将测试标记为已计划但尚未编写。它会作为提醒显示在报告中: ```ts import { describe, it } from 'vitest' @@ -176,4 +177,4 @@ describe('suite', () => { }) ``` -Unlike `.skip`, a `.todo` test has no test body. It's purely a placeholder for future work. +与 `.skip` 不同,`.todo` 测试没有测试体。它纯粹是为后续工作预留的占位符。 diff --git a/guide/improving-performance.md b/guide/improving-performance.md index 048c2a95..4400eabe 100644 --- a/guide/improving-performance.md +++ b/guide/improving-performance.md @@ -12,7 +12,7 @@ title: 性能优化 | 指南 - `forks` 进程池:每个测试文件在独立的 [子进程分支](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options) 中运行。 - `vmThreads` 虚拟线程池:每个测试文件在独立的 [VM 上下文](https://nodejs.org/api/vm.html#vmcreatecontextcontextobject-options) 中运行,但通过 Worker 实现并行执行。 -对于那些不依赖副作用并且能够正确清理其状态的项目来说,这可能不是所期望的(对于拥有 `node` 环境的项目来说,这通常是正确的),这会大大增加测试时间。在这种情况下,禁用隔离将提高测试速度。要做到这一点,我们可以在 CLI 中提供 `--no-isolate` 标志,或者在配置文件中将 [`test.isolate`](/config/isolate) 属性设置为 `false`。 +对于那些不依赖副作用并且能够正确清理其状态的项目来说,这可能不是所期望的(对于拥有 `node` 环境的项目来说,这通常是正确的),这会大大增加测试时间。在这种情况下,禁用隔离将提高测试速度。要做到这一点,我们可以在 CLI 中提供 `--no-isolate` 参数,或者在配置文件中将 [`test.isolate`](/config/isolate) 属性设置为 `false`。 ::: code-group @@ -63,7 +63,7 @@ export default defineConfig({ 如果使用的是 `vmThreads` 池,则不能禁用隔离。请改用 `threads` 池来提高测试性能。 ::: -对于某些项目,可能还需要禁用并行性以缩短启动时间。为此,请向 CLI 提供 `--no-file-parallelism` 标志,或将 config 中的 [`test.fileParallelism`](/config/fileparallelism) 属性设置为 `false`。 +对于某些项目,可能还需要禁用并行性以缩短启动时间。为此,请向 CLI 提供 `--no-file-parallelism` 参数,或将 config 中的 [`test.fileParallelism`](/config/fileparallelism) 属性设置为 `false`。 ::: code-group @@ -103,7 +103,7 @@ Duration 5.90s (transform 842ms, setup 543ms, import 2.35s, tests 2.94s, enviro ## 运行池 {#pool} -默认情况下,Vitest 在 `pool: 'forks'` 中运行测试。虽然 `'forks'` 池更适合解决兼容性问题([hanging process](/guide/common-errors.html#failed-to-terminate-worker) 和[segfaults](/guide/common-errors.html#segfaults-and-native-code-errors)),但在较大的项目中,它可能比 `pool: 'threads'` 稍慢。 +默认情况下,Vitest 在 `pool: 'forks'` 中运行测试。虽然 `'forks'` 池更适合解决兼容性问题([hanging process](/guide/common-errors.html#failed-to-terminate-worker) 和 [segfaults](/guide/common-errors.html#segfaults-and-native-code-errors)),但在较大的项目中,它可能比 `pool: 'threads'` 稍慢。 你可以尝试通过切换配置中的 `pool` 选项来改善测试运行时间: @@ -144,14 +144,14 @@ vitest run --reporter=blob --shard=3/3 # 3rd machine ```sh vitest run --merge-reports ``` - -When running the same shards across multiple environments, set the `VITEST_BLOB_LABEL` environment variable so merged reports can display them separately: + +在多个环境中运行相同的分片时,设置 `VITEST_BLOB_LABEL` 环境变量,以便合并的报告可以区分显示: ```sh VITEST_BLOB_LABEL=linux vitest run --reporter=blob --shard=1/3 ``` -::: details GitHub Actions example +::: details GitHub Actions 示例 This setup is also used at https://github.com/vitest-tests/test-sharding. ```yaml diff --git a/guide/index.md b/guide/index.md index 31917ad8..e5201138 100644 --- a/guide/index.md +++ b/guide/index.md @@ -1,7 +1,7 @@ --- title: 快速起步 | 指南 next: - text: Writing Tests + text: 编写测试用例 link: /guide/learn/writing-tests --- @@ -48,7 +48,6 @@ Vitest 需要 Vite >=v6.4.0 and 和 >=v22.12.0 如果在 `package.json` 中安装一份 `vitest` 的副本,可以使用上面列出的方法之一。然而,如果更倾向于直接运行 `vitest` ,可以使用 `npx vitest`( `npx` 会随着 npm 和 Node.js 一起被安装)。 `npx` 是一个命令行工具,用于执行指定的命令。默认情况下,`npx` 会首先检查本地项目的二进制文件中是否存在该命令。如果在那里没有找到,`npx` 会在系统的 `$PATH` 中查找并执行该命令(如果找到的话)。如果两个位置都没有找到该命令,`npx` 会在执行之前将其安装在临时位置。 - Vitest 及第三方集成可使用 `.vitest` 目录存储构建产物,建议将其添加到你的 `.gitignore` 文件中。 @@ -108,7 +107,7 @@ Test Files 1 passed (1) 你的第一个测试已通过!继续阅读 [编写测试用例](/guide/learn/writing-tests) 了解如何组织测试、解读测试输出以及日常使用的核心测试模式。 -要运行一次测试而不监听文件变化,请使用 `vitest run` 命令。你也可以传递额外的标志,如 `--reporter` 或 `--coverage`。查看完整的 CLI 选项列表,运行 `npx vitest --help` 或参阅 [CLI 指南](/guide/cli)。 +要运行一次测试而不监听文件变化,请使用 `vitest run` 命令。你也可以传递额外的参数,如 `--reporter` 或 `--coverage`。查看完整的 CLI 选项列表,运行 `npx vitest --help` 或参阅 [CLI 指南](/guide/cli)。 ## 配置 Vitest {#configuring-vitest} diff --git a/guide/migration.md b/guide/migration.md index f60aba89..742d76d0 100644 --- a/guide/migration.md +++ b/guide/migration.md @@ -6,16 +6,16 @@ outline: deep # 迁移指南 {#migration-guide} [迁移至 Vitest 3.0](https://v3.vitest.dev/guide/migration) | [迁移至 Vitest 2.0](https://v2.vitest.dev/guide/migration) - -## Migrating to Vitest 5.0 {#vitest-5} -::: warning Work in progress -Vitest 5.0 is currently in beta. This section tracks breaking changes as they are merged and may change before the stable release. +## 迁移至 Vitest 5.0 {#vitest-5} + +::: warning 进行中 +Vitest 5.0 目前处于 beta 阶段。本章节跟踪已合并的重大变更,在稳定版发布前可能还会发生变化。 ::: -### Removed `test.sequential`, `describe.sequential`, and `sequential` Options +### 移除 `test.sequential`, `describe.sequential`, 和 `sequential` 选项 {##removed-test-sequential-describe-sequential-and-sequential-options} -Vitest 5.0 removes the deprecated `test.sequential`, `describe.sequential`, and `sequential` test options. Use `concurrent: false` when you need a test or suite to opt out of inherited or globally configured concurrency. +Vitest 5.0 移除了已弃用的 `test.sequential`、`describe.sequential` 和 `sequential` 选项。当你需要让某个测试或测试套件不再沿用继承来的并发设置,或退出全局配置的并发时,请使用 `concurrent: false`。 ```ts test.sequential('example', async () => { /* ... */ }) // [!code --] @@ -34,14 +34,14 @@ test('example', { sequential: true }, async () => { /* ... */ }) // [!code --] test('example', { concurrent: false }, async () => { /* ... */ }) // [!code ++] ``` -### Locators in Commands are Serialized as Objects +### 命令中的定位器被序列化为对象 {#locators-in-commands-are-serialized-as-objects} -Locators forwarded to [browser commands](/api/browser/commands) are now serialized as a `SerializedLocator` object instead of a bare selector string. The object exposes two fields: +转发到 [浏览器命令](/api/browser/commands) 的定位器现在被序列化为 `SerializedLocator` 对象,而不是裸的选择器字符串。该对象导出两个字段: -- `selector`: the provider-specific selector string (the same value commands previously received). -- `locator`: a human-readable representation of the locator (e.g. `getByRole('button')`), used for error messages and tracing. +- `selector`:提供程序特定的选择器字符串(与 commands 先前接收的值相同)。 +- `locator`:定位器的人类可读的(例如 `getByRole('button')`),用于错误消息和跟踪。 -Update any custom commands that accept a locator to destructure `selector` from the new object: +更新所有接收定位器的自定义命令,改为从新的对象中解构出 selector: ```ts import type { SerializedLocator } from '@vitest/browser' @@ -56,18 +56,18 @@ export async function customClick( } ``` -### Removed Deprecated Entrypoints +### 移除了已弃用的入口 {#removed-deprecated-entrypoints} -Several entry points were marked as deprecated in Vitest 4.1. This release removes them entirely. +多个入口在 Vitest 4.1 中被标记为已弃用。此版本完全移除了它们。 -- `vitest/coverage`: use `vitest/node` instead -- `vitest/reporters`: use `vitest/node` instead -- `vitest/environments`: use `vitest/runtime` instead -- `vitest/snapshot`: use `vitest/runtime` instead -- `vitest/runners`: use `TestRunner` from `vitest` instead -- `vitest/suite`: use static methods on `TestRunner` from vitest instead (for example, `TestRunner.getCurrentTest()`) -- `vitest/mocker` is removed completely, use `@vitest/mocker` package directly (this was published by accident at one point and never removed) -- `vitest/internal/module-runner` is removed +- `vitest/coverage`:改用 `vitest/node` +- `vitest/reporters`:改用 `vitest/node` +- `vitest/environments`:改用 `vitest/runtime` +- `vitest/snapshot`:改用 `vitest/runtime` +- `vitest/runners`:改用 `vitest` 中的 `TestRunner` +- `vitest/suite`:改用 `vitest` 中 `TestRunner` 的静态方法(例如,`TestRunner.getCurrentTest()`) +- `vitest/mocker` 已移除,请直接使用 `@vitest/mocker` 包(这个包曾意外发布过一次且从未被移除) +- `vitest/internal/module-runner` 已移除 ## 迁移至 Vitest 4.0 {#vitest-4} @@ -93,7 +93,7 @@ Vitest 的 V8 覆盖率提供器现在使用了更精准的结果映射逻辑, 在之前的版本中,Vitest 会默认把所有未覆盖的文件包含到报告中。这是因为 `coverage.all` 默认为 `true`,`coverage.include` 默认为 `**`。这样设计是因为测试工具无法准确判断用户源码所在位置。 -然而,这导致 Vitest 覆盖率工具会处理很多意料之外的文件(例如压缩 JS 文件),造成报告生成速度很慢甚至卡死。在 Vitest v4 中,我们彻底移除了 `coverage.all`,并将默认行为改为**只在报告中包含被测试覆盖的文件**。 +然而,这导致 Vitest 覆盖率工具会处理很多意料之外的文件(例如压缩 JS 文件),造成报告生成速度很慢甚至卡死。在 Vitest v4 中,我们彻底移除了 `coverage.all`,并将默认行为改为 **只在报告中包含被测试覆盖的文件**。 升级至 v4 版本时,建议先在配置文件中定义 `coverage.include`,再根据需要逐步添加简单的 `coverage.exclude` 匹配规则。 @@ -132,6 +132,7 @@ export default defineConfig({ ``` 更多示例请参考: + - [覆盖率报告中的文件包含与排除](/guide/coverage.html#including-and-excluding-files-from-coverage-report) - [性能分析 | 代码覆盖率](/guide/profiling-test-performance.html#code-coverage) 了解调试覆盖率生成的方法 @@ -173,7 +174,7 @@ export default defineConfig({ }) ``` -### `spyOn` 和 `fn` 支持构造函数 {#spyon-and-fn-support-constructors} +### `spyOn` 和 `fn` 支持构造函数 {#spyon-and-fn-support-constructors} 在之前的版本中,如果尝试使用 `vi.spyOn` 监视构造函数,可能会收到类似 `Constructor requires 'new'` 的错误。自 Vitest 4 起,所有通过 `new` 关键字调用的模拟会构造实例,而不是调用 `mock.apply`。这意味着在这些情况下,模拟实现必须使用 `function` 或 `class` 关键字: @@ -234,6 +235,7 @@ expect(instance2.method()).toBe(100) expect(AutoMockedClass.prototype.method).toHaveBeenCalledTimes(4) ``` + - 自动 mock 方法一经生成即不可还原,手动 `.mockRestore` 无效;`spy: true` 的自动 mock 模块行为保持不变。 - 自动 mock 的 getter 不再执行原始逻辑,默认返回 `undefined`;如需继续监听并改写,请使用 `vi.spyOn(object, name, 'get')`。 - 执行 `vi.fn(implementation).mockReset()` 后,`.getMockImplementation()` 现可正确返回原 mock 实现。 @@ -252,6 +254,7 @@ $ vitest --standalone math.test.ts 这允许用户为独立模式创建可复用的 `package.json`。 ::: code-group + ```json [package.json] { "scripts": { @@ -259,6 +262,7 @@ $ vitest --standalone math.test.ts } } ``` + ```bash [CLI] # 以独立模式启动 Vitest,启动时不运行任何文件 $ pnpm run test:dev @@ -266,6 +270,7 @@ $ pnpm run test:dev # 立即运行 math.test.ts $ pnpm run test:dev math.test.ts ``` + ::: ### `vite-node` 替换为 [Module Runner](https://vite.dev/guide/api-environment-runtimes.html#modulerunner) {#replacing-vite-node-with-module-runner} @@ -288,6 +293,7 @@ Vite 已提供外部化机制,但为降低破坏性,仍保留旧方案;[`s 在 Vitest 3.2 中,`workspace` 配置选项更名为 [`projects`](/guide/projects)。除了不能指定其他文件作为工作区的源文件(以前可以指定导出项目数组的文件)外,它们在功能上是相同的。迁移到 `projects` 非常简单,只需将代码从 `vitest.workspace.js` 移动到 `vitest.config.ts`: ::: code-group + ```ts [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -305,6 +311,7 @@ export default defineConfig({ } }) ``` + ```ts [vitest.workspace.js] import { defineWorkspace } from 'vitest/config' // [!code --] @@ -317,11 +324,12 @@ export default defineWorkspace([ // [!code --] } // [!code --] ]) // [!code --] ``` + ::: ### 修改浏览器模式提供者 {#browser-provider-rework} -在 Vitest 4.0 中,浏览器提供者现在接受对象而非字符 (`'playwright'`, `'webdriverio'`)。 `preview` 不再是默认设置。这使得使用自定义选项变得更简单,而且不再需要添加 `/// -### Custom Snapshot Matchers experimental 4.1.3 -Jest imports snapshot composables from `jest-snapshot`. In Vitest, use `Snapshots` from `vitest` instead: +### 自定义快照匹配器 4.1.3 {#custom-snapshot-matchers} + +Jest 从 `jest-snapshot` 导入快照组合函数。在 Vitest 中,请改用 `vitest` 中的 `Snapshots`: ```ts const { toMatchSnapshot } = require('jest-snapshot') // [!code --] @@ -719,7 +731,7 @@ expect.extend({ }) ``` -For inline snapshots, the same applies: +对于内联快照,同样适用: ```ts const { toMatchInlineSnapshot } = require('jest-snapshot') // [!code --] @@ -733,7 +745,7 @@ expect.extend({ }) ``` -See [Custom Snapshot Matchers](/guide/snapshot#custom-snapshot-matchers) for the full guide. +完整指南请参阅 [自定义快照匹配器](/guide/snapshot#custom-snapshot-matchers)。 ## 从 Mocha + Chai + Sinon 迁移 {#mocha-chai-sinon} @@ -818,16 +830,16 @@ expect(spy).to.have.been.calledWith('arg1', 'arg2') Vitest supports all common sinon-chai assertions: -| Sinon-Chai | Vitest | 详情 | -|------------|--------|-------------| -| `spy.called` | `called` | Spy 至少被调用过一次 | -| `spy.calledOnce` | `calledOnce` | Spy 恰好被调用过一次 | -| `spy.calledTwice` | `calledTwice` | Spy 恰好被调用过两次 | -| `spy.calledThrice` | `calledThrice` | Spy 恰好被调用过三次 | -| `spy.callCount(n)` | `callCount(n)` | Spy 被调用过 n 次 | -| `spy.calledWith(...)` | `calledWith(...)` | Spy 以特定参数被调用 | +| Sinon-Chai | Vitest | 详情 | +| ------------------------- | --------------------- | ---------------------------- | +| `spy.called` | `called` | Spy 至少被调用过一次 | +| `spy.calledOnce` | `calledOnce` | Spy 恰好被调用过一次 | +| `spy.calledTwice` | `calledTwice` | Spy 恰好被调用过两次 | +| `spy.calledThrice` | `calledThrice` | Spy 恰好被调用过三次 | +| `spy.callCount(n)` | `callCount(n)` | Spy 被调用过 n 次 | +| `spy.calledWith(...)` | `calledWith(...)` | Spy 以特定参数被调用 | | `spy.calledOnceWith(...)` | `calledOnceWith(...)` | Spy 以特定参数恰好被调用一次 | -| `spy.returned(value)` | `returned` | Spy 返回了特定值 | +| `spy.returned(value)` | `returned` | Spy 返回了特定值 | 更多内容请参阅 [Chai 风格 Spy 断言](/api/expect#chai-style-spy-assertions) 文档中的完整列表。 @@ -909,6 +921,7 @@ vi.useRealTimers() 3. **并发执行**:Vitest 默认并发运行测试,Mocha 则顺序执行。 更多内容请参阅: + - [Chai 风格 Spy 断言](/api/expect#chai-style-spy-assertions) - [Mocking 指南](/guide/mocking) - [Vi API](/api/vi) diff --git a/guide/parallelism.md b/guide/parallelism.md index db7d888e..d577dc7a 100644 --- a/guide/parallelism.md +++ b/guide/parallelism.md @@ -3,32 +3,30 @@ title: 并行性 | 指南 outline: deep --- - - # 并行性 {#parallelism} -Vitest has two levels of parallelism: it can run multiple *test files* at the same time, and within each file it can run multiple *tests* at the same time. Understanding the difference between the two is important because they work differently and have different trade-offs. +Vitest 有两个层级的并行机制:它可以同时运行多个 _测试文件_,也可以在单个文件内同时运行多个 _测试_。理解这两者之间的区别至关重要,因为它们的工作方式不同,权衡内容也不同。 ## 文件级并行 {#file-parallelism} -By default, Vitest runs test files in parallel across multiple workers. Each file gets its own isolated environment, so tests in different files can't interfere with each other. +默认情况下,Vitest 会在多个 worker 中并行运行测试文件。每个文件都拥有独立的隔离环境,因此不同文件中的测试不会相互干扰。 -The mechanism Vitest uses to create workers depends on the configured [`pool`](/config/pool): +Vitest 创建 worker 的机制取决于配置的 [`pool`](/config/pool): -- `forks` (the default) and `vmForks` run each file in a separate [child process](https://nodejs.org/api/child_process.html) -- `threads` and `vmThreads` run each file in a separate [worker thread](https://nodejs.org/api/worker_threads.html) +- `forks`(默认值)和 `vmForks` 在单独的 [子进程](https://nodejs.org/api/child_process.html) 中运行每个文件 +- `threads` 和 `vmThreads` 在单独的 [工作线程](https://nodejs.org/api/worker_threads.html) 中运行每个文件 -You can control how many workers run simultaneously with the [`maxWorkers`](/config/maxworkers) option. More workers means more files run in parallel, but also more memory and CPU usage. The right number depends on your machine and how heavy your tests are. +你可以通过 [`maxWorkers`](/config/maxworkers) 选项控制同时运行的 worker 数量。更多的 worker 意味着可以并行运行更多文件,但也会占用更多内存和 CPU。具体的数量取决于你的机器性能和测试的负载情况。 -For most projects, file parallelism is the single biggest factor in test suite speed. However, there are cases where you might want to disable it — for example, if your tests share an external resource like a database that can't handle concurrent access. You can set [`fileParallelism`](/config/fileparallelism) to `false` to run files one at a time. +对于大多数项目而言,文件级并行是影响测试套件速度的最主要因素。然而,在某些情况下,你可能需要禁用它:例如,当你的测试共享一个无法处理并发访问的外部资源(如数据库)时。你可以将 [`fileParallelism`](/config/fileparallelism) 设置为 `false` 来逐个顺序运行文件。 -To learn more about tuning performance, see the [Performance Guide](/guide/improving-performance). +要了解更多关于性能优化的信息,请参阅 [性能指南](/guide/improving-performance)。 ## 测试级并行 {#test-parallelism} -Within a single file, Vitest runs tests sequentially by default. Tests execute in the order they are defined, one after another. This is the safest default because tests within a file often share setup and state through lifecycle hooks like `beforeEach`. +在单个文件内部,Vitest 默认按顺序运行测试。测试按照定义的顺序依次执行。这是最安全的默认设置,因为同一文件内的测试通常通过 `beforeEach` 等生命周期钩子共享初始化和状态。 -If the tests in a file are independent, you can opt into running them concurrently with the [`concurrent`](/api/test#test-concurrent) modifier: +如果文件中的测试是相互独立的,你可以选择使用 [`concurrent`](/api/test#test-concurrent) 修饰符来并发运行它们: ```ts import { expect, test } from 'vitest' @@ -44,14 +42,14 @@ test.concurrent('fetches user posts', async () => { }) ``` -When tests are marked as `concurrent`, Vitest groups them together and runs them with [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all). The number of tests running at once is bounded by the [`maxConcurrency`](/config/maxconcurrency) option. +当测试被标记为 `concurrent` 时,Vitest 会将它们分组,并使用 [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) 运行它们。同时运行的测试数量受 [`maxConcurrency`](/config/maxconcurrency) 参数限制。 -::: tip When does `concurrent` actually help? -Vitest doesn't create extra workers for concurrent tests — they all run in the same worker as the file they belong to. This means `concurrent` only speeds things up when your tests spend time *waiting* (on network requests, timers, file I/O, etc.). Purely synchronous tests won't benefit because they still block the single JavaScript thread: +::: tip `concurrent` 何时真正有效? +Vitest 不会为并发测试创建额外的 worker,它们都会在所属文件的同一个 worker 中运行。这意味着,只有当测试会花时间 “等待”(例如等待网络请求、定时器、文件 I/O 等)时,`concurrent` 才能带来提速。纯同步测试不会因此受益,因为它们仍然会阻塞单个 JavaScript 线程: ```ts -// These run one after another despite `concurrent`, -// because there is nothing to await +// 尽管使用了 `concurrent`,这些测试仍会依次运行, +// 因为没有任何需要等待的内容 test.concurrent('the first test', () => { expect(1).toBe(1) }) @@ -60,9 +58,10 @@ test.concurrent('the second test', () => { expect(2).toBe(2) }) ``` + ::: -You can also apply `concurrent` to an entire suite: +你也可以将 `concurrent` 应用于整个测试套件: ```ts import { describe, expect, test } from 'vitest' @@ -80,9 +79,9 @@ describe.concurrent('user API', () => { }) ``` -If you want *all* tests in your project to run concurrently by default, set [`sequence.concurrent`](/config/sequence#sequence-concurrent) to `true` in your config. +如果你希望项目中的 _所有_ 测试默认并发运行,可以在配置中将 [`sequence.concurrent`](/config/sequence#sequence-concurrent) 设置为 `true`。 -You can opt individual tests or suites out of inherited concurrency with `concurrent: false`: +你可以通过 `concurrent: false` 让单个测试或测试套件退出继承的并发设置: ```ts test('uses a shared resource', { concurrent: false }, async () => { @@ -95,8 +94,8 @@ describe('shared resource suite', { concurrent: false }, () => { }) ``` -### Hooks with Concurrent Tests +### 并发测试中的钩子 {#hooks-with-concurrent-tests} -When tests run concurrently, lifecycle hooks behave differently. `beforeAll` and `afterAll` still run once for the group, but `beforeEach` and `afterEach` run for each test — potentially at the same time, since the tests themselves overlap. +当测试并发运行时,生命周期钩子的行为会有所不同。`beforeAll` 和 `afterAll` 仍然会为整个组运行一次,但 `beforeEach` 和 `afterEach` 会为每个测试分别运行,而且由于测试本身会重叠执行,它们可能会在同一时间发生。 -The hook execution order is controlled by [`sequence.hooks`](/config/sequence#sequence-hooks). With `sequence.hooks: 'parallel'`, hooks are also bounded by the [`maxConcurrency`](/config/maxconcurrency) limit. +钩子的执行顺序由 [`sequence.hooks`](/config/sequence#sequence-hooks) 控制。当 `sequence.hooks` 设置为 `'parallel'` 时,钩子同样受 [`maxConcurrency`](/config/maxconcurrency) 限制。 diff --git a/guide/profiling-test-performance.md b/guide/profiling-test-performance.md index 69ac86ba..77641308 100644 --- a/guide/profiling-test-performance.md +++ b/guide/profiling-test-performance.md @@ -30,7 +30,7 @@ - [`--prof`](https://nodejs.org/api/cli.html#--prof) :::warning -由于 `node:worker_threads` 的限制, `--prof` 不能与 `pool: 'threads'` 一起使用。 +由于 `node:worker_threads` 的限制,`--prof` 不能与 `pool: 'threads'` 一起使用。 ::: 要将这些选项传递给 Vitest 的测试运行器,请在 Vitest 配置中定义 `execArgv`: @@ -53,7 +53,7 @@ export default defineConfig({ 测试运行后,应该会生成 `test-runner-profile/*.cpuprofile` 和 `test-runner-profile/*.heapprofile` 文件。想要知道如何分析这些文件,可以仔细查看 [性能分析记录](#inspecting-profiling-records)。 -也可以看看 [性能分析 | 示例](https://github.com/vitest-dev/vitest/tree/main/examples/profiling) 。 +也可以看看 [性能分析 | 示例](https://github.com/vitest-dev/vitest/tree/main/examples/profiling)。 ## 主线程 {#main-thread} @@ -74,18 +74,18 @@ $ node --cpu-prof --cpu-prof-dir=main-profile ./node_modules/vitest/vitest.mjs - # NodeJS arguments Vitest arguments ``` -测试运行后会生成一个 `main-profile/*.cpuprofile` 文件。有关如何分析这些文件的说明,可以查看[检查分析记录](#inspecting-profiling-records)。 +测试运行后会生成一个 `main-profile/*.cpuprofile` 文件。有关如何分析这些文件的说明,可以查看 [检查分析记录](#inspecting-profiling-records)。 ## 文件转换 {#file-transform} -This profiling strategy is a good way to identify unnecessary transforms caused by [barrel files](https://vitejs.dev/guide/performance.html#avoid-barrel-files). -If these logs contain files that should not be loaded when your test is run, you might have barrel files that are importing files unnecessarily. +种分析策略有助于识别由 [桶文件](https://cn.vitejs.dev/guide/performance.html#avoid-barrel-files) 引起的不必要转换。如果这些日志包含在运行测试时不应加载的文件,你可能有一些桶文件在导入不必要的文件。 -也可以使用 [Vitest UI](/guide/ui) 来调试由打包文件引起的缓慢问题。 -下面的例子展示了不使用打包文件导入文件可以减少约85%的转换文件数量。 +也可以使用 [UI 模式](/guide/ui) 来调试由打包文件引起的缓慢问题。 +下面的例子展示了不使用打包文件导入文件可以减少约 85% 的转换文件数量。 ::: code-group -``` [File tree] + +```[File tree] ├── src │ └── utils │ ├── currency.ts @@ -99,6 +99,7 @@ If these logs contain files that should not be loaded when your test is run, you │ └── formatters.test.ts └── vitest.config.ts ``` + ```ts [example.test.ts] import { expect, test } from 'vitest' import { formatter } from '../src/utils' // [!code --] @@ -108,18 +109,19 @@ test('formatter works', () => { expect(formatter).not.toThrow() }) ``` + ::: - -Vitest UI demonstrating barrel file issues -To see how files are transformed, you can open the "Module Info" view in the UI: +Vitest UI 模式展示桶文件问题 + +要查看文件是如何被转换的,你可以在 UI 模式 中打开 "模块信息" 视图: The module info view for an inlined module The module info view for an inlined module -## File Import +## 文件导入 {#file-import} -Some modules just take a long time to load. To identify which modules are the slowest, enable [`experimental.importDurations`](/config/experimental#experimental-importdurations) in your configuration: +有些模块加载时间较长。要识别哪些模块最慢,请在配置中启用 [`experimental.importDurations`](/config/experimental#experimental-importdurations): ```ts [vitest.config.ts] import { defineConfig } from 'vitest/config' @@ -135,7 +137,7 @@ export default defineConfig({ }) ``` -This will print a breakdown of the slowest imports after your tests finish: +这将在测试完成后打印最慢导入的详情: ```bash Import Duration Breakdown (Top 10) @@ -146,28 +148,28 @@ date-fns/index.js 500ms 500ms [████████████ src/utils/helpers.ts 10ms 120ms [████████░░░░░░░░░░░░] ``` -You can also use `--experimental.importDurations.print` from the CLI without changing your configuration: +你也可以在不更改配置的情况下,在 CLI 传递 `--experimental.importDurations.print` 参数: ```bash vitest --experimental.importDurations.print ``` -Once you've identified the slow modules, there are several strategies to speed up imports: +一旦识别出慢速模块,有几种策略可以加速导入: -### Use Specific Entry Points +### 使用特定入口 {#use-specific-entry-points} -Many libraries ship multiple entry points. Importing the main entry point (which is often a [barrel file](https://vitejs.dev/guide/performance.html#avoid-barrel-files)) can pull in far more code than you need. +许多库提供了多个入口点。导入主入口点(通常是 [桶文件](https://vitejs.dev/guide/performance.html#avoid-barrel-files))可能会引入比你所需多得多的代码。 -For example, `date-fns` re-exports hundreds of functions from its main entry point. Instead of importing from the top-level module, import directly from the specific function: +例如,`date-fns` 从其主入口点重新导出了数百个函数。与其从顶层模块导入,不如直接从特定入口导入: ```ts import { format } from 'date-fns' // [!code --] import { format } from 'date-fns/format' // [!code ++] ``` -### Use `resolve.alias` to Redirect Imports +### 使用 `resolve.alias` 重定向导入 {#use-resolve-alias-to-redirect-imports} -If a dependency doesn't provide granular entry points, or if third-party code imports the heavy entry point, you can use [`resolve.alias`](https://vite.dev/config/shared-options#resolve-alias) to redirect imports to a lighter alternative: +如果一个依赖没有提供细粒度的入口,或者第三方代码导入了重量级入口点,你可以使用 [`resolve.alias`](https://cn.vite.dev/config/shared-options#resolve-alias) 将导入重定向到更轻量的替代方案: ```ts [vitest.config.ts] import { defineConfig } from 'vitest/config' @@ -184,9 +186,9 @@ export default defineConfig({ }) ``` -### Use the Dependency Optimizer +### 使用依赖优化器 {#use-the-dependency-optimizer} -Vitest can bundle external libraries into a single file using [`deps.optimizer`](/config/deps#deps-optimizer), which reduces the overhead of importing packages with many internal modules: +Vitest 可以使用 [`deps.optimizer`](/config/deps#deps-optimizer) 将外部库打包到单个文件中,这减少了导入具有许多内部模块的包的开销: ```ts [vitest.config.ts] import { defineConfig } from 'vitest/config' @@ -205,7 +207,7 @@ export default defineConfig({ }) ``` -This is especially effective for UI libraries and packages with deep import trees. Use `optimizer.ssr` for `node`/`edge` environments and `optimizer.client` for `jsdom`/`happy-dom` environments. +这对于 UI 库和具有深层导入树的包极其有效。对于 `node`/`edge` 环境使用 `optimizer.ssr`,对于 `jsdom`/`happy-dom` 环境使用 `optimizer.client`。 ## 代码覆盖率 {#code-coverage} diff --git a/guide/projects.md b/guide/projects.md index b63914e2..2af93693 100644 --- a/guide/projects.md +++ b/guide/projects.md @@ -285,11 +285,10 @@ export default defineConfig({ ::: danger 不支持的选项 部分配置选项不允许在项目配置中使用,主要包括: - - `coverage`:覆盖率统计针对整个进程 - `reporters`:只支持根级别的 reporters - `resolveSnapshotPath`:只尊重根级别的快照路径解析器 -- `attachmentsDir`: attachments are stored in one root-level directory shared by all projects +- `attachmentsDir`:附件存储在由所有项目共享的一个根级目录中 - 其他不影响测试运行器的选项 所有不支持在项目配置中使用的配置选项,在 ["配置"](/config/) 指南中会用 标记。它们必须在根配置文件中定义一次。 diff --git a/guide/reporters.md b/guide/reporters.md index abd334ec..bbfe9627 100644 --- a/guide/reporters.md +++ b/guide/reporters.md @@ -34,16 +34,16 @@ export default defineConfig({ }, }) ``` - -## Default Configuration -When `reporters` is not configured, Vitest uses the following reporters: +## 默认配置 {#default-configuration} -- [`default`](#default-reporter) in normal terminal runs -- [`minimal`](#minimal-reporter) when Vitest detects an AI coding agent -- [`github-actions`](#github-actions-reporter) is added when `process.env.GITHUB_ACTIONS === 'true'` +当未配置 `reporters` 时,Vitest 使用以下报告器: -If you configure your own reporters, the configured list replaces the default list. To add a reporter while keeping Vitest's defaults, extend `configDefaults.reporters`: +- 在普通终端运行时使用 [`default`](#default-reporter) +- 当 Vitest 检测到 AI 编码智能体时使用 [`minimal`](#minimal-reporter) +- 当 `process.env.GITHUB_ACTIONS === 'true'` 时会额外添加 [`github-actions`](#github-actions-reporter) + +如果你自行配置报告器列表,配置的列表会替换默认列表。如果想保留 Vitest 默认配置的同时添加报告器,请扩展 `configDefaults.reporters`: ```ts import { configDefaults, defineConfig } from 'vitest/config' @@ -57,7 +57,7 @@ export default defineConfig({ ## 报告器输出 {#reporter-output} -默认情况下,Vitest 的报告器会将输出打印到终端。当使用 `json` 、`html` 或 `junit` 报告器时,你可以在 Vite 配置文件中或通过 CLI 加入 `outputFile` [配置选项](/config/outputfile),将测试输出写入文件。 +默认情况下,Vitest 的报告器会将输出打印到终端。当使用 `json`、`html` 或 `junit` 报告器时,你可以在 Vite 配置文件中或通过 CLI 加入 `outputFile` [配置选项](/config/outputfile),将测试输出写入文件。 :::code-group @@ -118,12 +118,13 @@ export default defineConfig({ ## 内置报告器 {#built-in-reporters} ### 默认报告器 {#default-reporter} - -The `default` reporter displays summary of running tests and their status at the bottom. Once a suite passes, its status will be reported on top of the summary. + +`default` 报告器会在底部显示当前运行中的测试摘要及其状态。某个测试套件一旦通过,其状态就会显示在摘要上方。 我们可以通过配置报告器来禁用摘要: :::code-group + ```ts [vitest.config.ts] export default defineConfig({ test: { @@ -133,6 +134,7 @@ export default defineConfig({ }, }) ``` + ::: 项目中的测试输出示例: @@ -184,7 +186,7 @@ export default defineConfig({ 除此之外,`verbose` 报告器会立即打印测试错误消息。完整的测试错误会在测试运行结束时报告。 -这是唯一一个在测试未失败时报告[注解](/guide/test-annotations)的终端报告器。 +这是唯一一个在测试未失败时报告 [注释](/guide/test-annotations) 的终端报告器。 :::code-group @@ -237,6 +239,7 @@ export default defineConfig({ 树状报告器与 `default` 报告器相同,但它还会在套件完成后显示每个单独的测试。与 `default` 报告器类似,你可以通过配置报告器来禁用摘要。 :::code-group + ```bash [CLI] npx vitest --reporter=tree ``` @@ -250,6 +253,7 @@ export default defineConfig({ }, }) ``` + ::: 使用默认 `slowTestThreshold: 300` 的情况下,测试进行中的示例输出: @@ -356,38 +360,40 @@ AssertionError: expected 5 to be 4 // Object.is equality ``` - -The output XML contains nested `testsuites` → `testsuite` → `testcase` tags. You can customize the reporter's behaviour with the following options: - -| Option | Description | Default | -|---|---|---| -| `suiteName` | `name` attribute of `` | `"vitest tests"` | -| `suiteNameTemplate` | Template for the `name` attribute of ``. Accepts a string with placeholders or a function. | Relative file path | -| `classnameTemplate` | Template for the `classname` attribute of ``. Accepts a string with placeholders or a function. | Relative file path | -| `titleTemplate` | Template for the `name` attribute of ``. Accepts a string with placeholders or a function. | Full test title with ancestor hierarchy | -| `ancestorSeparator` | Separator used when joining ancestor describe block names in the `{classname}` placeholder and in the default test title. | `" > "` | -| `addFileAttribute` | Add a `file` attribute to each ``. | `false` | -| `includeConsoleOutput` | Include `` / `` console output. | `true` | -| `stackTrace` | Include stack traces in `` elements. | `true` | - -The following placeholders are available for `suiteNameTemplate`: -- `{title}` – name of the first top-level `describe` block; falls back to the file basename when there is no top-level `describe` -- `{filename}` – relative file path from the root (e.g. `src/foo.test.ts`) -- `{filepath}` – absolute file path -- `{basename}` – file name without directory (e.g. `foo.test.ts`) -- `{displayName}` – Vitest project name - -The following placeholders are available for `classnameTemplate` and `titleTemplate`: -- `{classname}` – ancestor `describe` block names joined by `ancestorSeparator` (e.g. `outer > inner`) -- `{title}` – leaf test title (the string passed to `it`/`test`) -- `{suitename}` – top-level `describe` block name, empty string when the test has no enclosing `describe` -- `{filename}` – relative file path from the root -- `{filepath}` – absolute file path -- `{basename}` – file name without directory -- `{displayName}` – Vitest project name + +输出的 XML 包含嵌套的 `testsuites` → `testsuite` → `testcase` 标签。你可以通过以下选项自定义报告器的行为: + +| 选项 | 描述 | 默认值 | +| ---------------------- | ------------------------------------------------------------------------- | -------------------------- | +| `suiteName` | `` 的 `name` 属性 | `"vitest tests"` | +| `suiteNameTemplate` | `` 的 `name` 属性模板。接受带有占位符的字符串或函数。 | 相对文件路径 | +| `classnameTemplate` | `` 的 `classname` 属性模板。接受带有占位符的字符串或函数。 | 相对文件路径 | +| `titleTemplate` | `` 的 `name` 属性模板。接受带有占位符的字符串或函数。 | 包含祖先层级的完整测试标题 | +| `ancestorSeparator` | 在 `{classname}` 占位符和默认测试标题中连接祖先描述块名称时使用的分隔符。 | `" > "` | +| `addFileAttribute` | 为每个 `` 添加 `file` 属性。 | `false` | +| `includeConsoleOutput` | 包含 ``/`` 控制台输出。 | `true` | +| `stackTrace` | 在 `` 元素中包含堆栈跟踪。 | `true` | + +以下占位符可用于 `suiteNameTemplate`: + +- `{title}` – 第一个顶级 `describe` 块的名称;当没有顶级 `describe` 时回退到文件基本名 +- `{filename}` – 从根目录开始的相对文件路径(例如 `src/foo.test.ts`) +- `{filepath}` – 绝对文件路径 +- `{basename}` – 不带目录的文件名(例如 `foo.test.ts`) +- `{displayName}` – Vitest 项目名称 + +以下占位符可用于 `classnameTemplate` 和 `titleTemplate`: + +- `{classname}` – 由 `ancestorSeparator` 连接的祖先 `describe` 块名称(例如 `outer > inner`) +- `{title}` – 叶子测试标题(传递给 `it`/`test` 的字符串) +- `{suitename}` – 顶级 `describe` 块名称,当测试没有封闭的 `describe` 时为空字符串 +- `{filename}` – 从根目录开始的相对文件路径 +- `{filepath}` – 绝对文件路径 +- `{basename}` – 不带目录的文件名 +- `{displayName}` – Vitest 项目名称 ::: tip -`{filename}` follows Vitest's convention and resolves to the **relative path** from the project root (e.g. `src/foo.test.ts`). This differs from jest-junit where `{filename}` is the bare file name. Use `{basename}` to get only the file name. +`{filename}` 遵循 Vitest 的约定,解析为从项目根目录开始的 **相对路径**(例如 `src/foo.test.ts`)。这与 jest-junit 不同,在 jest-junit 中 `{filename}` 是纯文件名。使用 `{basename}` 来获取仅文件名。 ::: ```ts @@ -396,11 +402,11 @@ export default defineConfig({ reporters: [ ['junit', { suiteName: 'My Test Suite', - // Use the first top-level describe block name as the testsuite name + // 使用第一个顶级 describe 块名称作为 testsuite 名称 suiteNameTemplate: '{title}', - // classname = ancestor describe chain + // classname = 祖先 describe 链 classnameTemplate: '{classname}', - // name = leaf test title only (jest-junit-compatible) + // name = 仅叶子测试标题(与 jest-junit 兼容) titleTemplate: '{title}', ancestorSeparator: ' > ', }] @@ -409,7 +415,7 @@ export default defineConfig({ }) ``` -Function-based templates receive all available variables and can return any string: +基于函数的模板接收所有可用变量,并可以返回任意字符串: ```ts export default defineConfig({ @@ -492,10 +498,10 @@ JSON 报告示例: ``` ::: info -自Vitest 3 起,如果启用了代码覆盖率功能,JSON 报告器会在 `coverageMap` 中包含覆盖率信息。 +自 Vitest 3 起,如果启用了代码覆盖率功能,JSON 报告器会在 `coverageMap` 中包含覆盖率信息。 ::: - -The `meta` field in each assertion result can be filtered via the `filterMeta` reporter option. It receives the key and value of each field and should return a falsy value to exclude the field from the report: + +每个断言结果中的 `meta` 字段可以通过 `filterMeta` 报告器选项进行过滤。它接收每个字段的键和值,并应返回 false 以便将该字段从报告中排除: ```ts export default defineConfig({ @@ -508,6 +514,7 @@ export default defineConfig({ }, }) ``` + ### HTML 报告器 {#html-reporter} 生成 HTML 文件,通过交互式 [GUI](/guide/ui) 查看测试结果。文件生成后,Vitest 将保持本地开发服务器运行,并提供一个链接,以便在浏览器中查看报告。 @@ -531,7 +538,7 @@ export default defineConfig({ ::: ::: tip -该报告器需要安装 [`@vitest/ui`](/guide/ui) 。 +该报告器需要安装 [`@vitest/ui`](/guide/ui)。 ::: ### TAP 报告器 {#tap-reporter} @@ -635,14 +642,13 @@ export default defineConfig({ ::: ### GitHub Actions 报告器 {#github-actions-reporter} - -Output [workflow commands](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message) -to provide annotations for test failures. This reporter is [enabled automatically](#default-configuration) when `process.env.GITHUB_ACTIONS === 'true'` (on GitHub Actions environment). + +输出 [工作流命令](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message) 为测试失败提供注释。当 `process.env.GITHUB_ACTIONS === 'true'` 时(在 GitHub Actions 环境中),此报告器会 [自动启用](#default-configuration)。 GitHub Actions GitHub Actions -You can customize the file paths that are printed in [GitHub's annotation command format](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions) by using the `onWritePath` option. This is useful when running Vitest in a containerized environment, such as Docker, where the file paths may not match the paths in the GitHub Actions environment. +你可以使用 `onWritePath` 选项自定义在 [GitHub 的注释命令格式](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions) 中打印的文件路径。适用于在容器化环境(如 Docker)中运行 Vitest,因为容器内的文件路径可能与 GitHub Actions 环境中的路径不一致。 ```ts export default defineConfig({ @@ -670,13 +676,13 @@ export default defineConfig({ }, }) ``` - -The GitHub Actions reporter automatically generates a [Job Summary](https://github.blog/news-insights/product-news/supercharging-github-actions-with-job-summaries/) with an overview of your test results. The summary includes test file and test case statistics, and highlights flaky tests that required retries. -GitHub Actions Job Summary -GitHub Actions Job Summary +GitHub Actions 报告器会自动生成一个 [作业摘要](https://github.blog/news-insights/product-news/supercharging-github-actions-with-job-summaries/),其中包含你的测试结果概览。该摘要包括测试文件和测试用例的统计数据,并突出显示需要重试的测试。 -The job summary is enabled by default and writes to the path specified by `$GITHUB_STEP_SUMMARY`. You can override it by using the `jobSummary.outputPath` option: +GitHub Actions 作业摘要 +GitHub Actions 作业摘要 + +作业摘要默认启用,并写入 `$GITHUB_STEP_SUMMARY` 指定的路径。你可以使用 `jobSummary.outputPath` 选项来覆盖它: ```ts export default defineConfig({ @@ -692,7 +698,7 @@ export default defineConfig({ }) ``` -To disable the job summary: +要禁用作业摘要: ```ts export default defineConfig({ @@ -704,15 +710,15 @@ export default defineConfig({ }) ``` -The flaky tests section of the summary includes permalink URLs that link test names directly to the relevant source lines on GitHub. These links are generated automatically using environment variables that GitHub Actions provides (`$GITHUB_REPOSITORY`, `$GITHUB_SHA`, and `$GITHUB_WORKSPACE`), so no configuration is needed in most cases. +摘要中的容易失败测试部分会包含永久 URL 链接,可将测试名称直接链接到 GitHub 上对应的源码行。这些链接会利用 GitHubActions 提供的环境变量(`$GITHUB_REPOSITORY`、`$GITHUB_SHA` 和 `$GITHUB_WORKSPACE`)自动生成,因此在大多数情况下无需额外配置。 -If you need to override these values — for example, when running in a container or a custom environment — you can customize them via the `fileLinks` option: +如果你需要覆盖这些值:例如,在容器或自定义环境中运行时——可以通过 `fileLinks` 选项进行自定义: -- `repository`: the GitHub repository in `owner/repo` format. Defaults to `process.env.GITHUB_REPOSITORY`. -- `commitHash`: the commit SHA to use in permalink URLs. Defaults to `process.env.GITHUB_SHA`. -- `workspacePath`: the absolute path to the root of the repository on disk. Used to compute relative file paths for the permalink URLs. Defaults to `process.env.GITHUB_WORKSPACE`. +- `repository`:GitHub 仓库,格式为 `owner/repo`。默认为 `process.env.GITHUB_REPOSITORY`。 +- `commitHash`:用于永久链接 URL 的提交 SHA。默认为 `process.env.GITHUB_SHA`。 +- `workspacePath`:磁盘上仓库根目录的绝对路径。用于计算永久链接 URL 的相对文件路径。默认为 `process.env.GITHUB_WORKSPACE`。 -All three values must be available for the links to be generated. +这三个值都必填可用才能生成链接。 ```ts export default defineConfig({ @@ -732,16 +738,17 @@ export default defineConfig({ }) ``` -### Minimal Reporter +### 精简报告器 {#minimal-reporter} -- **Alias:** `agent` +- **别名:** `agent` -Outputs a minimal report containing only failed tests and their error messages. Console logs from passing tests and the summary section are also suppressed. +输出一份精简报告,只包含失败的测试及其错误信息。通过测试的控制台日志和摘要部分也会被一并隐藏。 -::: tip Agent Reporter -This reporter is well optimized for AI coding assistants and LLM-based workflows to reduce token usage. It is [enabled automatically](#default-configuration) when Vitest detects it is running inside an AI coding agent. +::: tip 智能体报告器 +此报告器针对 AI 编程助手和基于 LLM 的工作流程进行了优化,以减少词元使用量。当 Vitest 检测到它在 AI 智能体编程内部运行时,它会 [自动启用](#default-configuration)。 :::code-group + ```bash [CLI] npx vitest --reporter=minimal ``` @@ -753,30 +760,31 @@ export default defineConfig({ }, }) ``` + ::: -### Blob 报告器 +### Blob 报告器 {#blob-reporter} 将测试结果存储在计算机上,以便以后可以使用 [`--merge-reports`](/guide/cli#merge-reports) 命令进行合并。 -默认情况下,将所有结果存储在 `.vitest/blob/` 文件夹中,但可以用 `--outputFile` 或 `--outputFile.blob` 标志覆盖。 +默认情况下,将所有结果存储在 `.vitest/blob/` 文件夹中,但可以用 `--outputFile` 或 `--outputFile.blob` 参数覆盖。 ```bash npx vitest --reporter=blob --outputFile=reports/blob-1.json ``` - -We recommend using this reporter if you are running Vitest on different machines with the [`--shard`](/guide/cli#shard) flag or across multiple environments (e.g., linux/macos/windows). All blob reports can be merged into any report by using `--merge-reports` command at the end of your CI pipeline: + +如果你在不同的机器上使用 [`--shard`](/guide/cli#shard) 参数运行 Vitest,或者跨多个环境(例如,linux/macos/windows)运行,我们建议使用此报告器。所有 blob 报告都可以在 CI 流水线结束时使用 `--merge-reports` 命令合并到任何报告中: ```bash npx vitest --merge-reports=reports --reporter=json --reporter=default ``` -When running the same tests across multiple environments, use the `VITEST_BLOB_LABEL` environment variable to distinguish each environment's blob. Vitest reads labels at merge time and displays results separately: +在多个环境中运行相同的测试时,使用 `VITEST_BLOB_LABEL` 环境变量来区分每个环境的 blob。Vitest 在合并时读取标签并分别显示结果: ```bash VITEST_BLOB_LABEL=linux vitest run --reporter=blob ``` -You can also provide the label via the blob reporter option. This has higher priority than `VITEST_BLOB_LABEL`. +你也可以通过 blob 报告器参数传递标签。这比 `VITEST_BLOB_LABEL` 具有更高的优先级。 ```ts [vitest.config.ts] import { defineConfig } from 'vitest/config' @@ -790,8 +798,8 @@ export default defineConfig({ }) ``` -Blob reporter output doesn't include file-based [attachments](/api/advanced/artifacts.html#testattachment). -Make sure to merge [`attachmentsDir`](/config/attachmentsdir) separately alongside blob reports on CI when using this feature. +Blob 报告器输出不包含基于文件的 [附件](/api/advanced/artifacts.html#testattachment)。 +在使用此功能时,请确保在 CI 中合并 blob 报告的同时,一并处理 [`attachmentsDir`](/config/attachmentsdir)。 ::: tip `--reporter=blob` 和 `--merge-reports` 这两个选项在监听模式下均不可用。 diff --git a/guide/snapshot.md b/guide/snapshot.md index c4352b09..3a2652c4 100644 --- a/guide/snapshot.md +++ b/guide/snapshot.md @@ -106,7 +106,7 @@ it('render basic', async () => { }) ``` -它将与 `./test/basic.output.html` 的内容进行比较。并且可以用 `--update` 标志写回。 +它将与 `./test/basic.output.html` 的内容进行比较。并且可以用 `--update` 参数写回。 ## 图像快照 {#visual-snapshots} @@ -292,7 +292,7 @@ expect.extend({ ::: ::: warning -当自定义内联快照匹配器为异步时,Vitest 无法自动推断内联快照重写的调用位置。你必须通过在 chai 断言对象上设置 `'error'` 标志来捕获调用点: +当自定义内联快照匹配器为异步时,Vitest 无法自动推断内联快照重写的调用位置。你必须通过在 chai 断言对象上设置 `'error'` 参数来捕获调用点: ```ts import { chai, expect, Snapshots } from 'vitest' diff --git a/guide/testing-types.md b/guide/testing-types.md index 03cce731..d83ecb23 100644 --- a/guide/testing-types.md +++ b/guide/testing-types.md @@ -22,7 +22,7 @@ Vitest 允许你使用 `expectTypeOf` 或 `assertType` 语法为你的类型编 自 Vitest 2.1 起,如果你的 `include` 和 `typecheck.include` 重叠,Vitest 将分别报告类型测试和运行时测试。 ::: -使用 CLI 标志,如 `--allowOnly` 和 `-t` 也支持类型检查。 +使用 CLI 参数,如 `--allowOnly` 和 `-t` 也支持类型检查。 ```ts [mount.test-d.ts] import { assertType, expectTypeOf } from 'vitest' @@ -124,7 +124,7 @@ assertType(answr) ## 运行类型检查 {#run-typechecking} -要启用类型检查,只需在 `package.json` 文件中的 Vitest 命令中添加 [`--typecheck`](/config/typecheck) 标志: +要启用类型检查,只需在 `package.json` 文件中的 Vitest 命令中添加 [`--typecheck`](/config/typecheck) 参数: ```json [package.json] { diff --git a/guide/ui.md b/guide/ui.md index 4813ac49..70d61b1a 100644 --- a/guide/ui.md +++ b/guide/ui.md @@ -38,9 +38,9 @@ export default defineConfig({ ``` 你可以在 Vitest UI 中查看覆盖率报告:查看 [覆盖率 | UI 模式](/guide/coverage#vitest-ui) 了解更多详情。 - + ::: warning -If you still want to see how your tests are running in real time in the terminal, add `configDefaults.reporters` to the `reporters` option: `['html', ...configDefaults.reporters]`. +如果你仍然希望在终端中实时查看测试运行情况,请将 `configDefaults.reporters` 添加到 `reporters` 选项中:`['html', ...configDefaults.reporters]`。 ::: ::: tip