diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 0c4a7daf3..12cd4a416 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,6 +1,6 @@
-### 在提交PR之前,请确保您执行以下操作:
+### 在提交PR之前,请确保你执行以下操作:
- [ ] 曾阅读过[翻译须知](https://github.com/vitest-dev/docs-cn/issues/391)。
- [ ] 检查是否已经有PR以同样的方式解决问题,以避免创建重复。
- [ ] 在此PR中描述正在解决的问题,或引用它解决的问题(例如:`fixes #123`)。
@@ -8,7 +8,7 @@
---
### 描述
-
+
### 附加上下文
diff --git a/api/advanced/plugin.md b/api/advanced/plugin.md
index 1b447e17e..de755dcf6 100644
--- a/api/advanced/plugin.md
+++ b/api/advanced/plugin.md
@@ -93,7 +93,7 @@ function injectTestProjects(
```ts
// 为单个项目注入自定义别名
const newProjects = await injectTestProjects({
- // 您可以通过引用 `extends` 来继承当前项目配置
+ // 你可以通过引用 `extends` 来继承当前项目配置
// 注意,不能使用已经存在的项目名称,
// 所以定义自定义名称是一个好实践。
extends: project.vite.config.configFile,
diff --git a/api/advanced/reporters-life-cycle.md b/api/advanced/reporters-life-cycle.md
new file mode 100644
index 000000000..42646f49e
--- /dev/null
+++ b/api/advanced/reporters-life-cycle.md
@@ -0,0 +1,24 @@
+
+
+- [`onInit`](#oninit)
+- [`onTestRunStart`](#ontestrunstart)
+ - [`onTestModuleQueued`](#ontestmodulequeued)
+ - [`onTestModuleCollected`](#ontestmodulecollected)
+ - [`onTestModuleStart`](#ontestmodulestart)
+ - [`onTestSuiteReady`](#ontestsuiteready)
+ - [`onHookStart(beforeAll)`](#onhookstart)
+ - [`onHookEnd(beforeAll)`](#onhookend)
+ - [`onTestCaseReady`](#ontestcaseready)
+ - [`onTestCaseAnnotate`](#ontestcaseannotate) 3.2.0
+ - [`onTestCaseArtifactRecord`](#ontestcaseartifactrecord) 4.0.11
+ - [`onHookStart(beforeEach)`](#onhookstart)
+ - [`onHookEnd(beforeEach)`](#onhookend)
+ - [`onHookStart(afterEach)`](#onhookstart)
+ - [`onHookEnd(afterEach)`](#onhookend)
+ - [`onTestCaseResult`](#ontestcaseresult)
+ - [`onHookStart(afterAll)`](#onhookstart)
+ - [`onHookEnd(afterAll)`](#onhookend)
+ - [`onTestSuiteResult`](#ontestsuiteresult)
+ - [`onTestModuleEnd`](#ontestmoduleend)
+ - [`onCoverage`](#oncoverage)
+- [`onTestRunEnd`](#ontestrunend)
diff --git a/api/advanced/reporters.md b/api/advanced/reporters.md
index aabaccba1..fa7135f33 100644
--- a/api/advanced/reporters.md
+++ b/api/advanced/reporters.md
@@ -6,24 +6,7 @@
Vitest 拥有自己的测试运行生命周期。这些生命周期通过报告器的方法来表示:
-- [报告器 {#reporters}](#报告器-reporters)
- - [onInit](#oninit)
- - [onBrowserInit {#onbrowserinit}](#onbrowserinit-onbrowserinit)
- - [onTestRunStart](#ontestrunstart)
- - [onTestRunEnd](#ontestrunend)
- - [onCoverage](#oncoverage)
- - [onTestModuleQueued](#ontestmodulequeued)
- - [onTestModuleCollected](#ontestmodulecollected)
- - [onTestModuleStart](#ontestmodulestart)
- - [onTestModuleEnd](#ontestmoduleend)
- - [onHookStart](#onhookstart)
- - [onHookEnd](#onhookend)
- - [onTestSuiteReady](#ontestsuiteready)
- - [onTestSuiteResult](#ontestsuiteresult)
- - [onTestCaseReady](#ontestcaseready)
- - [onTestCaseResult](#ontestcaseresult)
- - [onTestCaseAnnotate 3.2.0 {#ontestcaseannotate}](#ontestcaseannotate-320-ontestcaseannotate)
- - [onTestCaseArtifactRecord 4.0.11 {#ontestcaseartifactrecord}](#ontestcaseartifactrecord-4011-ontestcaseartifactrecord)
+
除非被跳过,否则单个模块中的测试和 reporters 将按顺序报告。所有跳过的测试将在 reporters 测试套件或模块的末尾报告。
diff --git a/api/advanced/runner.md b/api/advanced/runner.md
index 157e935eb..b7279c69a 100644
--- a/api/advanced/runner.md
+++ b/api/advanced/runner.md
@@ -275,7 +275,7 @@ export interface TaskResult {
## 你的任务函数 {#your-task-function}
-Vitest 提供了 `createTaskCollector` 工具来创建您自己的 `test` 方法。它的行为与测试相同,但在收集期间会调用自定义方法。
+Vitest 提供了 `createTaskCollector` 工具来创建你自己的 `test` 方法。它的行为与测试相同,但在收集期间会调用自定义方法。
任务是套件的一部分对象。它会通过 `suite.task` 方法自动添加到当前套件中:
diff --git a/api/advanced/test-case.md b/api/advanced/test-case.md
index 356e1aab0..8fbccd5a7 100644
--- a/api/advanced/test-case.md
+++ b/api/advanced/test-case.md
@@ -1,8 +1,8 @@
# TestCase
-`TestCase` 类表示单个测试。此类仅在主线程中可用。如果您正在处理运行时任务,请参阅 [“运行器 API”](/api/advanced/runner#tasks)。
+`TestCase` 类表示单个测试。此类仅在主线程中可用。如果你正在处理运行时任务,请参阅 [“运行器 API”](/api/advanced/runner#tasks)。
-`TestCase` 实例始终有一个值为 `test` 的 `type` 属性。您可以使用它来区分不同的任务类型:
+`TestCase` 实例始终有一个值为 `test` 的 `type` 属性。你可以使用它来区分不同的任务类型:
```ts
if (task.type === 'test') {
diff --git a/api/advanced/test-specification.md b/api/advanced/test-specification.md
index 6ae9a1670..9b95cba24 100644
--- a/api/advanced/test-specification.md
+++ b/api/advanced/test-specification.md
@@ -44,10 +44,8 @@ Vite 模块图中的模块 ID。通常,它是一个使用 POSIX 分隔符的
测试模块将运行的 [`pool`](/config/pool)。
-
-
::: danger
-It's possible to have multiple pools in a single test project with [`typecheck.enabled`](/config/typecheck#typecheck-enabled). This means it's possible to have several specifications with the same `moduleId` but different `pool`. In later versions, the project will only support a single pool.
+在启用 [`typecheck.enabled`](/config/typecheck#typecheck-enabled) 配置的情况下,单个测试项目中可能存在多个运行池。这意味着可能出现多个测试规范共享相同 `moduleId` 但使用不同 `pool` 的情况。请注意,后续版本将仅支持单一运行池模式。
:::
## testLines
@@ -79,15 +77,15 @@ describe('a group of tests', () => { // [!code error]
## testNamePattern 4.1.0 {#testnamepattern}
-A regexp that matches the name of the test in this module. This value will override the global [`testNamePattern`](/config/testnamepattern) option if it's set.
+用于匹配当前模块中测试名称的正则表达式。如果已设置,该值将覆盖全局 [`testNamePattern`](/config/testnamepattern) 配置。
## testIds 4.1.0 {#testids}
-The ids of tasks inside of this specification to run.
+当前测试规范中需要运行的任务 ID 集合。
## testTagsFilter 4.1.0 {#testtagsfilter}
-The [tags filter](/guide/test-tags#syntax) that a test must pass in order to be included in the run. Multiple filters are treated as `AND`.
+测试必须通过的 [标签过滤器](/guide/test-tags#syntax) 才能被纳入运行范围。多个过滤器将按 `AND` 逻辑处理。
## toJSON
diff --git a/api/advanced/vitest.md b/api/advanced/vitest.md
index 6b9f78284..e96687c9f 100644
--- a/api/advanced/vitest.md
+++ b/api/advanced/vitest.md
@@ -304,8 +304,6 @@ function rerunTestSpecifications(
此方法发出 `reporter.onWatcherRerun` 和 `onTestsRerun` 事件,然后使用 [`runTestSpecifications`](#runtestspecifications) 运行测试。如果主进程中没有错误,它将发出 `reporter.onWatcherStart` 事件。
-
-
## runTestFiles 4.1.0 {#runtestfiles}
```ts
@@ -315,11 +313,11 @@ function runTestFiles(
): Promise
```
-This automatically creates specifications to run based on filepaths filters.
+该功能会根据文件路径过滤器自动创建待运行的测试规范。
-This is different from [`start`](#start) because it does not create a coverage provider, trigger `onInit` and `onWatcherStart` events, or throw an error if there are no files to run (in this case, the function will return empty arrays without triggering a test run).
+这与 [`start`](#start) 的不同之处在于:它不会创建覆盖率提供程序、不会触发 `onInit` 和 `onWatcherStart` 事件,且在无文件可运行时也不会抛出错误(此时函数将返回空数组且不会触发测试运行)。
-This function accepts the same filters as [`start`](#start) and the CLI.
+此函数接受的过滤器参数与 [`start`](#start) 及命令行接口完全一致。
## updateSnapshot
@@ -482,8 +480,7 @@ function onCancel(fn: (reason: CancelReason) => Awaitable): () => void
注册一个处理程序,当测试运行被 [`vitest.cancelCurrentRun`](#cancelcurrentrun) 取消时调用。
-
-Since 4.0.10, `onCancel` experimentally returns a teardown function that will remove the listener. Since 4.1.0 this behaviour is considered stable.
+自 4.0.10 起,`onCancel` 实验性地返回一个清理函数,该函数会移除监听器。自 4.1.0 起,此行为被视为稳定。
## onClose
@@ -696,26 +693,26 @@ export interface SourceModuleDiagnostic {
::: warning
[浏览器模式](/guide/browser/) 暂不支持。
:::
-
+
## createReport 5.0.0 {#createreport}
```ts
function createReport(scope: string): Report
```
-Creates a report that is limited to the given scope. `Report` follows Vitest's rules around [Storing artifacts on file system](/guide/advanced/reporters.html#storing-artifacts-on-file-system).
+创建一个仅限于给定作用域的报告。`Report` 遵循 Vitest 关于 [在文件系统中存储工件](/guide/advanced/reporters.html#storing-artifacts-on-file-system) 的规则。
-`Report` provides collection of utilities for writing test results, temporary files and other artifacts on the file system. It's especially intended for third party integrations like custom reporters.
+`Report` 提供了一系列用于在文件系统中写入测试结果、临时文件和其他产物的工具函数。它特别适用于第三方集成,例如自定义报告器。
-All operations of `Report` are limited to given `scope`. A single report cannot interfere with other reports. Internally Vitest creates `.vitest` directory where each `scope` creates their own directory. This convention of `.vitest` directory reduces the amount of entries end-users need to specify in their `.gitignore`.
+`Report` 的所有操作都限制在给定的 `scope` 内。单个报告不会干扰其他报告。Vitest 内部会创建一个 `.vitest` 目录,每个 `scope` 在其中创建自己的子目录。这种 `.vitest` 目录的约定减少了最终用户需要在 `.gitignore` 中指定的条目数量。
```ts
import type { Report } from 'vitest/node'
const scope = 'example-yaml-reporter'
-// Automatically creates `/.vitest/example-yaml-reporter/`
-// directory if it does not exist already
+// 自动创建 `/.vitest/example-yaml-reporter/`
+// 如果目录不存在
const report: Report = vitest.createReport(scope)
```
@@ -730,7 +727,7 @@ The root directory for this scope.
```ts
const report = vitest.createReport('my-json-reporter')
-// Is /.vitest/my-json-reporter
+// 即 /.vitest/my-json-reporter
const root = report.root
```
@@ -740,12 +737,12 @@ const root = report.root
function clean(): Promise
```
-Clean up the report directory for this scope.
+清理此作用域的报告目录。
```ts
const report = vitest.createReport('my-json-reporter')
-// Removes everything inside /.vitest/my-json-reporter/
+// 删除 /.vitest/my-json-reporter/ 内的所有内容
await report.clean()
```
@@ -759,12 +756,12 @@ function writeFile(
): Promise
```
-Write a file to the report directory for this scope. By default the file will be written with UTF-8 encoding. The filename is relative to the scope directory.
+向此作用域的报告目录写入文件。默认情况下,文件将以 UTF-8 编码写入。文件名是相对于作用域目录的。
```ts
const report = vitest.createReport('my-json-reporter')
-// Writes file to .vitest/my-json-reporter/test-report.json
+// 将文件写入 .vitest/my-json-reporter/test-report.json
await report.writeFile('test-report.json', JSON.stringify(results))
```
@@ -774,12 +771,12 @@ await report.writeFile('test-report.json', JSON.stringify(results))
function readFile(filename: string, encoding?: BufferEncoding): Promise
```
-Read a file from the report directory for this scope.
+从此作用域的报告目录读取文件。
```ts
const report = vitest.createReport('my-json-reporter')
-// Reads file from .vitest/my-json-reporter/test-report.json
+// 从 .vitest/my-json-reporter/test-report.json 读取文件
const content: string = await report.readFile('test-report.json')
```
@@ -789,12 +786,12 @@ const content: string = await report.readFile('test-report.json')
function readdir(): Promise
```
-Read contents of the report directory for this scope.
+读取此作用域报告目录的内容。
```ts
const report = vitest.createReport('my-json-reporter')
-// Reads contents from .vitest/my-json-reporter
+// 从 from .vitest/my-json-reporter 读取内容
const filenames: string[] = await report.readdir()
```
@@ -805,11 +802,11 @@ const filenames: string[] = await report.readdir()
function delete(filename: string): Promise
```
-Delete a file from the report directory for this scope.
+从此作用域的报告目录删除文件。
```ts
const report = vitest.createReport('my-json-reporter')
-// Deletes file from .vitest/my-json-reporter/test-report.json
+// 从 .vitest/my-json-reporter/test-report.json 删除文件
await report.delete('test-report.json')
```
diff --git a/api/browser/commands.md b/api/browser/commands.md
index 3f43b0794..0293fe511 100644
--- a/api/browser/commands.md
+++ b/api/browser/commands.md
@@ -131,7 +131,7 @@ declare module 'vitest/browser' {
Vitest 在命令上下文中公开了几个`playwright`特定属性。
- `page`引用包含测试 iframe 的完整页面。这是协调器 HTML,为避免出现问题,最好不要碰它。
-- `frame` 是一个异步方法,用于解析测试器 [`Frame`](https://playwright.dev/docs/api/class-frame)。它的 API 与 `page` 类似,但不支持某些方法。如果您需要查询元素,应优先使用 `context.iframe` 代替,因为它更稳定、更快速。
+- `frame` 是一个异步方法,用于解析测试器 [`Frame`](https://playwright.dev/docs/api/class-frame)。它的 API 与 `page` 类似,但不支持某些方法。如果你需要查询元素,应优先使用 `context.iframe` 代替,因为它更稳定、更快速。
- `iframe` 是一个 [`FrameLocator`](https://playwright.dev/docs/api/class-framelocator),用于查询页面上的其他元素。
- `context` 是指唯一的[BrowserContext](https://playwright.dev/docs/api/class-browsercontext)。
diff --git a/api/browser/context.md b/api/browser/context.md
index 12d649ff1..8e7215e0c 100644
--- a/api/browser/context.md
+++ b/api/browser/context.md
@@ -59,10 +59,10 @@ export const commands: BrowserCommands
页面导出提供了与当前页面交互的实用程序。
::: warning
-虽然它从 Playwright 的 `page` 中获取了一些实用程序,但它与 Playwright 的 `page` 并不是同一个对象。由于浏览器上下文是在浏览器中评估的,您的测试无法访问 Playwright 的 `page`,因为它是在服务器上运行的。
+虽然它从 Playwright 的 `page` 中获取了一些实用程序,但它与 Playwright 的 `page` 并不是同一个对象。由于浏览器上下文是在浏览器中评估的,你的测试无法访问 Playwright 的 `page`,因为它是在服务器上运行的。
:::
-使用 [Commands API](/api/browser/commands) 如果您需要访问 Playwright 的 `page` 对象。
+使用 [Commands API](/api/browser/commands) 如果你需要访问 Playwright 的 `page` 对象。
```ts
export const page: {
diff --git a/api/browser/interactivity.md b/api/browser/interactivity.md
index cdf212112..b154bb300 100644
--- a/api/browser/interactivity.md
+++ b/api/browser/interactivity.md
@@ -259,7 +259,7 @@ test('update input', async () => {
})
```
-该方法聚焦元素、填充元素并在填充后触发一个 `input` 事件。您可以使用空字符串来清除字段。
+该方法聚焦元素、填充元素并在填充后触发一个 `input` 事件。你可以使用空字符串来清除字段。
::: tip
该 API 比使用 [`userEvent.type`](#userevent-type) 或 [`userEvent.keyboard`](#userevent-keyboard) 更快,但**不支持** [user-event `keyboard` syntax](https://testing-library.com/docs/user-event/keyboard) (例如,`{Shift}{selectall}`)。
diff --git a/api/browser/locators.md b/api/browser/locators.md
index 023a8bc1c..1ee3c6533 100644
--- a/api/browser/locators.md
+++ b/api/browser/locators.md
@@ -12,15 +12,15 @@ outline: [2, 3]
::: tip
本页介绍了 API 的使用。为了更好地了解定位器及其用法,请阅读 [Playwright 的“定位器”文档](https://playwright.dev/docs/locators)。
:::
-
-::: tip Difference from `testing-library`
-Vitest's `page.getBy*` methods return a locator object, not a DOM element. This makes locator queries composable and allows Vitest to retry interactions and assertions when needed.
-Compared to testing-library queries:
+::: tip 与 `testing-library` 的区别
+Vitest 的 `page.getBy*` 方法返回的是一个定位器对象,而非 DOM 元素。这使得定位器查询可组合,并允许 Vitest 在需要时重试交互和断言。
-- Use locator chaining (`.getBy*`, `.filter`, `.nth`) instead of `within(...)`.
-- Keep locators around and interact with them later (`await locator.click()`), instead of resolving elements up front.
-- Single-element escape hatches like `.element()` and `.query()` are strict and throw if multiple elements match.
+与 testing-library 查询的对比:
+
+- 使用定位器链式调用(如 `.getBy*`、`.filter`、`.nth`)代替 `within(...)`。
+- 保留定位器并在后续操作中使用(如 `await locator.click()`),而非提前解析元素。
+- 单元素应急方法(如 `.element()` 和 `.query()`)是严格的,如果匹配到多个元素会抛出错误。
```ts
import { expect } from 'vitest'
@@ -679,7 +679,7 @@ await page.getByRole('img', { name: 'Rose' }).tripleClick()
function wheel(options: UserEventWheelOptions): Promise
```
-Triggers a [`wheel` event](https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event) on an element. You can use the options to choose a general scroll `direction` or a precise `delta` value.
+触发元素上的 [`wheel` 事件](https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event)。你可以通过选项选择通用的滚动 `direction` 或精确的 `delta` 值。
```ts
import { page } from 'vitest/browser'
@@ -850,9 +850,9 @@ const { path, base64 } = await button.screenshot({
function mark(name: string, options?: { stack?: string }): Promise
```
-Adds a named marker to the trace timeline and uses the current locator as marker context.
+在追踪时间线上添加一个具名标记,并使用当前定位器作为标记上下文。
-Pass `options.stack` to override the callsite location in trace metadata. This is useful for wrapper libraries that need to preserve the end-user source location.
+传入 `options.stack` 以覆盖追踪元数据中的调用位置。适用于二次封装库并且需要保留用户调用源码位置的场景。
```ts
import { page } from 'vitest/browser'
@@ -865,7 +865,7 @@ await submitButton.mark('after submit')
```
::: tip
-This method is useful only when [`browser.trace`](/config/browser/trace) is enabled.
+此方法适用于启用 [`browser.trace`](/config/browser/trace) 配置时有效。
:::
### query
@@ -878,10 +878,8 @@ function query(): Element | null
如果多个元素匹配该选择器,此方法将抛出错误。如果你需要所有匹配的 DOM 元素,可以使用 [`.elements()`](#elements);如果你需要匹配选择器的定位器数组,可以使用 [`.all()`](#all)。
-
-
::: danger
-This is an escape hatch for external APIs that do not support locators. Prefer using locator methods instead.
+这是针对不支持定位器的外部 API 的变通方案。优先使用定位器方法。
:::
考虑以下 DOM 结构:
@@ -920,12 +918,11 @@ function element(): Element
如果 _多个元素_ 匹配该选择器,则会抛出错误。如果你需要所有匹配的 DOM 元素,可以使用 [`.elements()`](#elements);如果你需要匹配选择器的定位器数组,可以使用 [`.all()`](#all)。
-
-
::: danger
-This is an escape hatch for external APIs that do not support locators. Prefer using locator methods instead.
-It is called automatically when locator is used with `expect.element` every time the assertion is [retried](/api/browser/assertions):
+这是一个用于不支持定位器的外部 API 的应急方案。建议优先使用定位器方法。
+
+当定位器与 `expect.element` 一起使用时,每次断言 [重试](/api/browser/assertions) 时,该方法会自动调用:
```ts
await expect.element(page.getByRole('button')).toBeDisabled()
@@ -996,21 +993,21 @@ function findElement(
```
::: danger WARNING
-This is an escape hatch for cases where you need the raw DOM element — for example, to pass it to a third-party library like FormKit that doesn't accept Vitest locators. If you are interacting with the element yourself, use other [builtin methods](#methods) instead.
+这是一个应急方案,适用于需要直接操作原始 DOM 元素的场景,例如将其传递给不支持 Vitest 定位器的第三方库,如 FormKit。如果你需要与元素交互,请改用其他 [内置方法](#methods)。
:::
-This method returns an element matching the locator. Unlike [`.element()`](#element), this method will wait and retry until a matching element appears in the DOM, using increasing intervals (0, 20, 50, 100, 100, 500ms).
+此方法返回一个与定位器匹配的元素。与 [`.element()`](#element) 不同,该方法会等待并重试,直到匹配的元素出现在 DOM 中,重试间隔逐步增加(0、20、50、100、100、500 毫秒)。
-If _no element_ is found before the timeout, an error is thrown. By default, the timeout matches the test timeout.
+如果在超时前 _未找到任何元素_,将抛出错误。默认情况下,超时时间与测试的超时时间一致。
-If _multiple elements_ match the selector and `strict` is `true` (the default), an error is thrown immediately without retrying. Set `strict` to `false` to return the first matching element instead.
+如果匹配到 _多个元素_ 选择器且 `strict` 为 `true`(默认值),则会立即抛出错误而不会重试。将 `strict` 设为 `false` 可返回第一个匹配的元素。
-It accepts options:
+支持的选项:
-- `timeout: number` - How long to wait in milliseconds until at least one element is found. By default, this shares timeout with the test.
-- `strict: boolean` - When `true` (default), throws an error if multiple elements match the locator. When `false`, returns the first matching element.
+- `timeout: number` - 等待至少一个元素出现的毫秒数。默认与测试的超时时间一致。
+- `strict: boolean` - 为 `true`(默认)时,如果多个元素匹配定位器,则抛出错误;为 `false` 时,返回第一个匹配的元素。
-Consider the following DOM structure:
+考虑以下 DOM 结构:
```html
Hello World
@@ -1018,7 +1015,7 @@ Consider the following DOM structure:
Hello
```
-These locators will resolve successfully:
+以下定位器会成功解析:
```ts
await page.getByText('Hello World').findElement() // ✅ HTMLDivElement
@@ -1026,21 +1023,21 @@ await page.getByText('World').findElement() // ✅ HTMLSpanElement
await page.getByText('Hello Germany').findElement() // ✅ HTMLDivElement
```
-These locators will throw an error:
+以下定位器会抛出错误:
```ts
-// multiple elements match, strict mode rejects
+// 多个元素匹配,严格模式会拒绝
await page.getByText('Hello').findElement() // ❌
await page.getByText(/^Hello/).findElement() // ❌
-// no matching element before timeout
+// 超时前未找到匹配元素
await page.getByText('Hello USA').findElement() // ❌
```
-Using `strict: false` to allow multiple matches:
+使用 `strict: false` 以允许匹配多个:
```ts
-// returns the first matching element instead of throwing
+// 返回第一个匹配元素而不是抛出错误
await page.getByText('Hello').findElement({ strict: false }) // ✅ HTMLDivElement
```
@@ -1082,7 +1079,7 @@ import { commands, page } from 'vitest/browser'
test('works correctly', async () => {
await commands.test(page.getByText('Hello').selector) // ✅
- // vitest will automatically unwrap it to a string
+ // Vitest 会自动将其解包为字符串
await commands.test(page.getByText('Hello')) // ✅
})
```
@@ -1109,7 +1106,7 @@ page.getByRole('alert').length // ✅ 0
## 自定义定位器 3.2.0advanced {#custom-locators}
-您可以通过定义定位器工厂对象来扩展内置定位器 API。这些方法将作为 `page` 对象和所有已创建定位器的方法存在。
+你可以通过定义定位器工厂对象来扩展内置定位器 API。这些方法将作为 `page` 对象和所有已创建定位器的方法存在。
当内置定位器无法满足需求时(例如使用自定义 UI 框架时),这些定位器会非常有用。
diff --git a/api/browser/react.md b/api/browser/react.md
index 00aae59da..169e8008c 100644
--- a/api/browser/react.md
+++ b/api/browser/react.md
@@ -155,10 +155,10 @@ function debug(
```ts
function rerender(ui: React.ReactNode): Promise
```
-
-Also records a `react.rerender` trace mark in the [Trace View](/guide/browser/trace-view).
-It is better if you test the component that's doing the prop updating to ensure that the props are being updated correctly to avoid relying on implementation details in your tests. That said, if you'd prefer to update the props of a rendered component in your test, this function can be used to update props of the rendered component.
+同时会在 [Trace View](/guide/browser/trace-view) 中记录一个 `react.rerender` 追踪标记。
+
+为了更好地确保组件正确地更新属性,建议测试负责属性更新的组件本身,以避免在测试中依赖实现细节。尽管如此,如果你更倾向于在测试中更新已渲染组件的属性,可以使用此函数来实现。
```jsx
import { render } from 'vitest-browser-react'
@@ -174,10 +174,10 @@ await rerender()
```ts
function unmount(): Promise
```
-
-Also records a `react.unmount` trace mark in the [Trace View](/guide/browser/trace-view).
-This will cause the rendered component to be unmounted. This is useful for testing what happens when your component is removed from the page (like testing that you don't leave event handlers hanging around causing memory leaks).
+同时会在 [Trace View](/guide/browser/trace-view) 中记录一个 `react.unmount` 追踪标记。
+
+此操作将卸载已渲染的组件。适用于测试组件从页面中移除时的行为(例如测试是否未遗留事件监听器导致内存泄漏)。
```jsx
import { render } from 'vitest-browser-react'
diff --git a/api/browser/svelte.md b/api/browser/svelte.md
index 119146249..63b9172d6 100644
--- a/api/browser/svelte.md
+++ b/api/browser/svelte.md
@@ -41,11 +41,11 @@ export function render(
renderOptions?: SetupOptions
): RenderResult & PromiseLike>
```
-
-The `render` function records a `svelte.render` trace mark, visible in the [Trace View](/guide/browser/trace-view).
+
+`render` 函数会记录一个 `svelte.render` 追踪标记,该标记可在 [Trace View](/guide/browser/trace-view) 中查看。
::: warning
-Synchronous usage of `render` is deprecated and will be removed in the next major version. Please always `await` the result:
+同步调用 `render` 的方式已被弃用,并将在下一个主要版本中移除。请始终使用 `await` 处理其返回结果:
```ts
const screen = render(Component) // [!code --]
@@ -152,8 +152,8 @@ function debug(
```ts
function rerender(props: Partial>): Promise
```
-
-Updates the component's props and waits for Svelte to apply the changes. Use this to test how your component responds to prop changes. Also records a `svelte.rerender` trace mark in the [Trace View](/guide/browser/trace-view).
+
+更新组件的属性,并等待 Svelte 应用这些更改。此功能可用于测试组件对属性变化的响应。同时会在 [Trace View](/guide/browser/trace-view) 中记录一个 `svelte.rerender` 追踪标记。
```ts
import { render } from 'vitest-browser-svelte'
@@ -171,11 +171,11 @@ await rerender({ number: 2 })
```ts
function unmount(): Promise
```
-
-Unmount and destroy the Svelte component. Also records a `svelte.unmount` trace mark in the [Trace View](/guide/browser/trace-view). This is useful for testing what happens when your component is removed from the page (like testing that you don't leave event handlers hanging around causing memory leaks).
+
+卸载并销毁 Svelte 组件。同时会在 [Trace View](/guide/browser/trace-view) 中记录一个 `svelte.unmount` 追踪标记。此功能适用于测试组件从页面中移除时的行为(例如测试是否未遗留事件监听器导致内存泄漏)。
::: warning
-Synchronous usage of `unmount` is deprecated and will be removed in the next major version. Please always `await` the result.
+同步调用 `unmount` 的方式已被弃用,并将在下一个主要版本中移除。请始终使用 `await` 处理其返回结果:
:::
```ts
@@ -216,7 +216,7 @@ await expect.element(
## 代码片段 {#snippets}
-对于简单的代码片段,您可以使用包装组件和 “占位” 子元素进行测试。通过设置 `data-testid` 属性帮助测试插槽内容。
+对于简单的代码片段,你可以使用包装组件和 “占位” 子元素进行测试。通过设置 `data-testid` 属性帮助测试插槽内容。
::: code-group
```ts [basic.test.js]
diff --git a/api/browser/vue.md b/api/browser/vue.md
index 5cab3cfa4..eb2453760 100644
--- a/api/browser/vue.md
+++ b/api/browser/vue.md
@@ -42,11 +42,11 @@ export function render(
options?: ComponentRenderOptions,
): RenderResult & PromiseLike
```
-
-The `render` function records a `vue.render` trace mark, visible in the [Trace View](/guide/browser/trace-view).
+
+`render` 函数会记录一个 `vue.render` 追踪标记,该标记可在 [Trace View](/guide/browser/trace-view) 中查看。
::: warning
-Synchronous usage of `render` is deprecated and will be removed in the next major version. Please always `await` the result:
+同步调用 `render` 的方式已被弃用,并将在下一个主要版本中移除。请始终使用 `await` 处理其返回结果:
```ts
const screen = render(Component) // [!code --]
@@ -138,13 +138,12 @@ function debug(
```ts
function rerender(props: Partial): void & PromiseLike
```
-
-Also records a `vue.rerender` trace mark in the [Trace View](/guide/browser/trace-view).
+同时还会在 [Trace View](/guide/browser/trace-view) 中记录一个 `vue.rerender` 追踪标记。
-It is better if you test the component that's doing the prop updating to ensure that the props are being updated correctly to avoid relying on implementation details in your tests. That said, if you'd prefer to update the props of a rendered component in your test, this function can be used to update props of the rendered component.
+为了更好地确保组件正确地更新属性,建议测试负责属性更新的组件本身,以避免在测试中依赖实现细节。尽管如此,如果你更倾向于在测试中更新已渲染组件的属性,可以使用此函数来实现。
::: warning
-Synchronous usage of `rerender` is deprecated and will be removed in the next major version. Please always `await` the result.
+同步调用 `render` 的方式已被弃用,并将在下一个主要版本中移除。请始终使用 `await` 处理其返回结果:
:::
```js
@@ -161,11 +160,11 @@ rerender({ number: 2 })
```ts
function unmount(): void & PromiseLike
```
-
-This will cause the rendered component to be unmounted. Also records a `vue.unmount` trace mark in the [Trace View](/guide/browser/trace-view). This is useful for testing what happens when your component is removed from the page (like testing that you don't leave event handlers hanging around causing memory leaks).
+
+该操作会触发组件卸载,同时在 [跟踪视图](/guide/browser/trace-view) 中记录 `vue.unmount` 标记点。此功能特别适用于测试组件从页面移除时的行为(例如验证是否残留事件处理器导致内存泄漏)。
::: warning
-Synchronous usage of `unmount` is deprecated and will be removed in the next major version. Please always `await` the result.
+同步调用 `unmount` 的方式已被弃用,将在下一主要版本中移除。请使用 `await` 进行异步调用。
:::
#### emitted
diff --git a/api/expect.md b/api/expect.md
index a8d3b02bb..0807596d0 100644
--- a/api/expect.md
+++ b/api/expect.md
@@ -1393,7 +1393,7 @@ test('spy function resolved a value two times', async () => {
- **类型:** `(returnValue: any) => Awaitable`
-您可以调用此断言来检查函数是否至少成功解析过一次某个值。需要将 spy 函数传递给`expect`。
+你可以调用此断言来检查函数是否至少成功解析过一次某个值。需要将 spy 函数传递给`expect`。
如果函数返回了一个 promise,但尚未 resolved,则将会失败。
@@ -1413,7 +1413,7 @@ test('spy function resolved a product', async () => {
- **类型:** `(returnValue: any) => Awaitable`
-您可以调用此断言来检查函数在上次调用时是否已成功解析某个值。需要将 spy 函数传递给`expect`。
+你可以调用此断言来检查函数在上次调用时是否已成功解析某个值。需要将 spy 函数传递给`expect`。
如果函数返回了一个 promise,但尚未 resolved,则将会失败。
diff --git a/api/test.md b/api/test.md
index 84ca72506..31f9a2b37 100644
--- a/api/test.md
+++ b/api/test.md
@@ -311,7 +311,6 @@ describe('use scoped values', () => {
- **别名:** `it.scoped`
::: danger 弃用
-`test.scoped` is deprecated in favor of [`test.override`](#test-override) and will be removed in a future major version.
`test.scoped` 已弃用,建议使用 [`test.override`](#test-override),将在未来的主版本中移除。
:::
@@ -344,7 +343,7 @@ test('skipped test', (context) => {
})
```
-If the condition is unknown, you can provide it to the `skip` method as the first arguments:
+如果条件状态未知,可将其作为第一个参数传递给 `skip` 方法:
```ts
import { assert, test } from 'vitest'
@@ -614,9 +613,9 @@ test.each`
expect(a + b).toBe(expected)
})
```
-
+
::: tip
-Vitest formats interpolated title values with its display formatter. If the value is too truncated, you can increase [taskTitleValueFormatTruncate](/config/tasktitlevalueformattruncate) in your config file.
+Vitest 会使用其显示格式化器处理插入标题的值。如果值被过度截断,可在配置文件中调整 [taskTitleValueFormatTruncate](/config/tasktitlevalueformattruncate) 参数。
:::
## test.for
diff --git a/api/vi.md b/api/vi.md
index 13f78fbc3..76990d300 100644
--- a/api/vi.md
+++ b/api/vi.md
@@ -225,7 +225,7 @@ test('importing the next module imports mocked one', async () => {
```
::: tip
-In environments that support [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management), you can use `using` on the value returned from `vi.doMock()` to automatically call [`vi.doUnmock()`](#vi-dounmock) on the mocked module when the containing block is exited. This is especially useful when mocking a dynamically imported module for a single test case.
+在支持 [显式资源管理](https://github.com/tc39/proposal-explicit-resource-management) 的环境中,可对 `vi.doMock()` 返回值使用 `using` 语法,当代码块退出时自动调用 [`vi.doUnmock()`](#vi-dounmock) 取消模块模拟。该特性特别适用于在针对单个测试用例模拟动态导入模块。
```ts
it('uses a mocked version of my-module', () => {
@@ -233,7 +233,7 @@ it('uses a mocked version of my-module', () => {
const myModule = await import('my-module') // mocked
- // my-module is restored here
+ // 此处 my-module 已恢复原始状态
})
it('uses the normal version of my-module again', () => {
@@ -1073,40 +1073,40 @@ function useFakeTimers(config?: FakeTimerInstallOpts): Vitest
- **类型:**`(mode: 'manual' | 'nextTimerAsync') => Vitest | (mode: 'interval', interval?: number) => Vitest`
-Controls how fake timers are advanced.
+控制模拟计时器的推进方式:
-- `manual`: The default behavior. Timers will only advance when you call one of `vi.advanceTimers...()` methods.
-- `nextTimerAsync`: Timers will be advanced automatically to the next available timer after each macrotask.
-- `interval`: Timers are advanced automatically by a specified interval.
+- `manual`:默认行为。仅当调用 `vi.advanceTimers...()` 系列方法时才会推进计时器
+- `nextTimerAsync`:每个宏任务执行后自动推进到下一个可用计时器
+- `interval`:按指定间隔自动推进计时器
-When `mode` is `'interval'`, you can also provide an `interval` in milliseconds.
+当 `mode` 为 `'interval'` 时,可额外传入毫秒级 `interval` 参数。
-**Example:**
+**示例:**
```ts
import { vi } from 'vitest'
vi.useFakeTimers()
-// Manual mode (default)
+// 手动模式(默认)
vi.setTimerTickMode('manual')
let i = 0
setInterval(() => console.log(++i), 50)
-vi.advanceTimersByTime(150) // logs 1, 2, 3
+vi.advanceTimersByTime(150) // 输出 1, 2, 3
-// nextTimerAsync mode
+// nextTimerAsync 模式
vi.setTimerTickMode('nextTimerAsync')
-// Timers will advance automatically after each macrotask
-await new Promise(resolve => setTimeout(resolve, 150)) // logs 4, 5, 6
+// 每个宏任务后定时器会自动推进
+await new Promise(resolve => setTimeout(resolve, 150)) // 输出 4, 5, 6
-// interval mode (default when 'fakeTimers.shouldAdvanceTime' is `true`)
+// 间隔模式(当配置中 fakeTimers.shouldAdvanceTime 为 true 时的默认行为)
vi.setTimerTickMode('interval', 50)
-// Timers will advance automatically every 50ms
-await new Promise(resolve => setTimeout(resolve, 150)) // logs 7, 8, 9
+// 每50毫秒自动推进计时器
+await new Promise(resolve => setTimeout(resolve, 150)) // 输出 7, 8, 9
```
### vi.isFakeTimers {#vi-isfaketimers}
diff --git a/config/bail.md b/config/bail.md
index 855d23d0b..31fa8754d 100644
--- a/config/bail.md
+++ b/config/bail.md
@@ -11,4 +11,4 @@ outline: deep
当指定数量的测试用例失败时立即终止测试执行。
-默认情况下,即使部分测试失败,Vitest 仍会继续运行所有测试用例。对于仅关注 100% 成功构建的 CI 环境而言,这种行为可能不符合需求——您可能希望在测试出现失败时尽早终止执行。通过配置 `bail` 选项,可在发生失败时阻止后续测试运行,从而加速 CI 流程。
+默认情况下,即使部分测试失败,Vitest 仍会继续运行所有测试用例。对于仅关注 100% 成功构建的 CI 环境而言,这种行为可能不符合需求——你可能希望在测试出现失败时尽早终止执行。通过配置 `bail` 选项,可在发生失败时阻止后续测试运行,从而加速 CI 流程。
diff --git a/config/browser/preview.md b/config/browser/preview.md
index 56534fbc6..509d11837 100644
--- a/config/browser/preview.md
+++ b/config/browser/preview.md
@@ -20,7 +20,7 @@ export default defineConfig({
})
```
-这将使用默认浏览器打开一个新的浏览器窗口来运行测试。您可以通过设置 `instances` 数组中的 `browser` 属性来配置使用哪个浏览器。Vitest 会尝试自动打开浏览器,但在某些环境下可能无法正常工作。在这种情况下,您可以在所需的浏览器中手动打开所提供的 URL。
+这将使用默认浏览器打开一个新的浏览器窗口来运行测试。你可以通过设置 `instances` 数组中的 `browser` 属性来配置使用哪个浏览器。Vitest 会尝试自动打开浏览器,但在某些环境下可能无法正常工作。在这种情况下,你可以在所需的浏览器中手动打开所提供的 URL。
## 与其他 Providers 的差异
diff --git a/config/browser/traceview.md b/config/browser/traceview.md
index 8af97f3a1..a8ed639d1 100644
--- a/config/browser/traceview.md
+++ b/config/browser/traceview.md
@@ -1,15 +1,15 @@
---
-title: browser.traceView | Config
+title: browser.traceView | 配置
outline: deep
---
# browser.traceView 5.0.0
-- **Type:** `boolean | { enabled?: boolean; recordCanvas?: boolean; inlineImages?: boolean }`
-- **CLI:** `--browser.traceView`
-- **Default:** `false`
-
-Enable trace-view collection for browser tests. Vitest captures DOM snapshots for browser interactions and can show them in the browser UI, Vitest UI, or HTML reporter when those surfaces are enabled — no external tools required.
+- **类型:** `boolean | { enabled?: boolean; recordCanvas?: boolean; inlineImages?: boolean }`
+- **命令行终端:** `--browser.traceView`
+- **默认值:** `false`
+
+启用浏览器测试的 trace-view(追踪视图)收集功能。Vitest 会捕获浏览器交互的 DOM 快照,当启用浏览器 UI 模式、UI 模式 或 HTML 报告器时,可在这些界面中无需外部工具直接展示。
```ts
export default defineConfig({
@@ -21,7 +21,7 @@ export default defineConfig({
})
```
-Use the object form to enable additional snapshot fidelity options:
+使用对象形式可启用额外的快照保真度选项:
```ts
export default defineConfig({
@@ -37,34 +37,34 @@ export default defineConfig({
})
```
-| Option | Default | Description |
+| 选项 | 默认值 | 详情 |
| --- | --- | --- |
-| `enabled` | `false` | Enables Vitest trace-view artifact collection. |
-| `inlineImages` | `false` | Inlines loaded `` pixels into snapshots for more portable replay, useful in the HTML reporter. |
-| `recordCanvas` | `false` | Captures canvas pixels in snapshots. |
+| `enabled` | `false` | 启用 Vitest trace-view 收集产物。 |
+| `inlineImages` | `false` | 将加载的 `` 像素内联到快照中,实现更便捷的回放功能,适用于 HTML 报告器。 |
+| `recordCanvas` | `false` | 在快照中捕获 canvas 像素。 |
## browser.traceView.enabled {#traceview-enabled}
-- **Type:** `boolean`
-- **Default:** `false`
-- **CLI:** `--browser.traceView.enabled`
+- **类型:** `boolean`
+- **默认值:** `false`
+- **命令行终端:** `--browser.traceView.enabled`
-Enables Vitest trace-view artifact collection.
+启用 Vitest 追踪视图构建产物收集。
## browser.traceView.inlineImages {#traceview-inlineimages}
-- **Type:** `boolean`
-- **Default:** `false`
-- **CLI:** `--browser.traceView.inlineImages`
+- **类型:** `boolean`
+- **默认值:** `false`
+- **命令行终端:** `--browser.traceView.inlineImages`
-Inlines loaded `` pixels into snapshots for more portable replay, useful in the HTML reporter.
+将加载的 `` 像素内联到快照中,实现更便捷的回放功能,适用于 HTML 报告器。
## browser.traceView.recordCanvas {#traceview-recordcanvas}
-- **Type:** `boolean`
-- **Default:** `false`
-- **CLI:** `--browser.traceView.recordCanvas`
+- **类型:** `boolean`
+- **默认值:** `false`
+- **命令行终端:** `--browser.traceView.recordCanvas`
-Captures canvas pixels in snapshots. This enables a weaker replay iframe sandbox because rrweb needs scripts to redraw canvas data.
+在快照中捕获 canvas 像素。这会启用较弱的回放 iframe 沙盒,因为 rrweb 需要脚本重绘 canvas数据。
-See [Trace View](/guide/browser/trace-view) for full documentation.
+完整文档请参阅 [追踪视图](/guide/browser/trace-view)。
diff --git a/config/coverage.md b/config/coverage.md
index 427031497..14ec711dd 100644
--- a/config/coverage.md
+++ b/config/coverage.md
@@ -132,9 +132,9 @@ npx vitest --coverage.enabled --coverage.provider=istanbul
```
你可以在 Vitest UI 模式中查看代码覆盖率报告。更多详情请参阅 [Vitest UI Coverage](/guide/coverage#vitest-ui)。
-
-::: tip AI coding agents
-When Vitest detects it is running inside an AI coding agent, it automatically adds the `text-summary` reporter and sets `skipFull: true` on the `text` reporter to reduce output and minimize token usage.
+
+::: tip AI 智能体编程
+当 Vitest 检测到运行环境为 AI 智能体编程环境时,会自动启用 `text-summary` 报告器,并对 `text` 报告器设置 `skipFull: true` 以减少输出内容,从而降低词元的消耗。
:::
## coverage.reportOnFailure {#coverage-reportonfailure}
@@ -389,15 +389,15 @@ Vitest 会将所有文件(包括匹配 glob 模式的文件)计入全局覆
- **命令行终端:** `--coverage.processingConcurrency=`
处理代码覆盖率结果时使用的并发限制。
-
+
## coverage.instrumenter 4.1.5 {#coverage-instrumenter}
-- **Type:** `(options: InstrumenterOptions) => CoverageInstrumenter`
-- **Available for providers:** `'istanbul'`
+- **类型:** `(options: InstrumenterOptions) => CoverageInstrumenter`
+- **可用的测试提供者:** `'istanbul'`
-Factory for a custom instrumenter to use in place of the default `istanbul-lib-instrument`. Vitest calls the factory once during initialization and reuses the returned instrumenter for every file. The rest of the Istanbul pipeline (collection, merging, reporting) is unchanged.
+用于替代默认 `istanbul-lib-instrument` 的自定义检测器工厂函数。Vitest 在初始化期间调用该工厂函数一次,并对每个文件复用返回的检测器。Istanbul 管道的其余部分(收集、合并、报告)保持不变。
-The factory receives an `InstrumenterOptions` object with Vitest's runtime coverage settings, and must return an object implementing the `CoverageInstrumenter` interface. Both types are exported from `vitest/node`.
+该工厂函数接收包含 Vitest 运行时覆盖率设置的 `InstrumenterOptions` 对象,必须返回实现 `CoverageInstrumenter` 接口的对象。两种类型均从 `vitest/node` 导出。
```ts
diff --git a/config/css.md b/config/css.md
index 05806a871..4c4b80c98 100644
--- a/config/css.md
+++ b/config/css.md
@@ -41,12 +41,12 @@ outline: deep
- **类型:** `'stable' | 'scoped' | 'non-scoped'`
- **默认值:** `'stable'`
-如果您决定处理 CSS 文件,可以配置 CSS modules 中的类名是否应限定作用域。您可以选择以下选项之一:
+如果你决定处理 CSS 文件,可以配置 CSS modules 中的类名是否应限定作用域。你可以选择以下选项之一:
- `stable`: 类名将生成为 `_${name}_${hashedFilename}`,这意味着如果 CSS 内容发生变化,生成的类将保持不变,但如果文件名被修改或文件移动到另一个文件夹,则会更改。适用于使用快照功能。
- `scoped`: 类名将照常生成,如果你有 `css.modules.generateScopedName` 方法并且已启用 CSS 处理,则会尊重该方法。默认情况下,文件名将生成为 `_${name}_${hash}`,其中 hash 包含文件名和文件内容。
- `non-scoped`: 类名将不会被哈希。
::: warning
-默认情况下,Vitest 导出一个代理,绕过 CSS 模块处理。如果您依赖类上的 CSS 属性,则必须使用 `include` 选项启用 CSS 处理。
+默认情况下,Vitest 导出一个代理,绕过 CSS 模块处理。如果你依赖类上的 CSS 属性,则必须使用 `include` 选项启用 CSS 处理。
:::
diff --git a/config/experimental.md b/config/experimental.md
index 754109633..4b3f6e66b 100644
--- a/config/experimental.md
+++ b/config/experimental.md
@@ -379,7 +379,7 @@ const fs = require('node:fs') // 报错
如果你使用的是 Node.js 22.18/23.6 或更高版本,TypeScript 将由 Node.js [原生支持转换](https://nodejs.org/en/learn/typescript/run-natively)。
::: warning 在 Node.js 22.6-22.18 环境中的使用 TypeScript
-如果您使用的 Node.js 版本介于 22.6 至 22.18 之间,还可通过 `--experimental-strip-types` 参数启用原生 TypeScript 支持:
+如果你使用的 Node.js 版本介于 22.6 至 22.18 之间,还可通过 `--experimental-strip-types` 参数启用原生 TypeScript 支持:
```shell
NODE_OPTIONS="--experimental-strip-types" vitest
@@ -479,35 +479,35 @@ export default {
如果禁用模块运行器,Vitest 会使用原生 [Node.js 模块加载器](https://nodejs.org/api/module.html#customization-hooks) 来转换文件,以支持 `import.meta.vitest`、`vi.mock` 和 `vi.hoisted` 功能。
如果你不使用这些特性,可禁用此功能以提升性能。
-
+
## experimental.preParse 4.1.3 {#experimental-preparse}
-- **Type:** `boolean`
-- **Default:** `false`
+- **类型:** `boolean`
+- **默认值:** `false`
-Parses test specifications before running them. This applies the [`.only`](/api/test#test-only) modifier, the [`-t`](/config/testnamepattern) test name pattern, [`--tags-filter`](/guide/test-tags#syntax), [test lines](/api/advanced/test-specification#testlines), and [test IDs](/api/advanced/test-specification#testids) across all files without executing them. For example, if only a single test is marked with `.only`, Vitest will skip all other tests in all files.
+在运行测试前预解析测试规范。这会在所有文件中应用 [`.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
-This option is recommended when using [`.only`](/api/test#test-only), the [`-t`](/config/testnamepattern) flag, or [`--tags-filter`](/guide/test-tags#syntax).
+使用 [`.only`](/api/test#test-only)、[`-t`](/config/testnamepattern) 标志或 [`--tags-filter`](/guide/test-tags#syntax) 时推荐启用此选项。
-Enabling it unconditionally may slow down your test runs due to the additional parsing step.
+无条件启用可能会因额外的解析步骤而降低测试运行速度。
:::
::: warning
-Pre-parsing uses static analysis (AST parsing) instead of executing your test files. This means that test names, tags, and modifiers (`.only`, `.skip`, `.todo`) must be statically analyzable. Dynamic test names (e.g., names stored in variables or returned from function calls) and non-literal tags will not be resolved correctly.
+预解析使用静态分析(AST 解析)而非执行测试文件。这意味着测试名称、标签和修饰符(`.only`、`.skip`、`.todo`)必须可静态分析的。动态测试名称(例如,存储在变量中或从函数调用返回的名称)和非字面量标签将无法正确解析。
```ts
-// ✅ works — static string literal
+// ✅ 有效 —— 静态字符串字面量
test('adds numbers', () => {})
-// ✅ works — static tags
+// ✅ 有效 —— 静态标签
test('my test', { tags: ['unit'] }, () => {})
-// ❌ won't match correctly — dynamic name
+// ❌ 无法正确匹配 —— 动态名称
const name = getName()
test(name, () => {})
-// ❌ won't match correctly — dynamic tags
+// ❌ 无法正确匹配 —— 动态标签
const tags = getTags()
test('my test', { tags }, () => {})
```
diff --git a/config/file.md b/config/file.md
index bc4a239a9..83e4c89d3 100644
--- a/config/file.md
+++ b/config/file.md
@@ -25,7 +25,7 @@ export default defineConfig({
})
```
-`` 将在 Vitest 3 中停止工作,但您可以在 Vitest 2.1 中开始迁移到 `vitest/config`:
+`` 将在 Vitest 3 中停止工作,但你可以在 Vitest 2.1 中开始迁移到 `vitest/config`:
```ts
///
diff --git a/config/index.md b/config/index.md
index 8868207bc..d9fbbcd98 100644
--- a/config/index.md
+++ b/config/index.md
@@ -78,11 +78,11 @@ export default defineConfig(configEnv => mergeConfig(
```
由于 Vitest 使用 Vite 的配置,我们也可以使用 [Vite](https://vitejs.dev/config/) 中的任何配置选项。例如,使用 `define` 来定义全局变量,或者使用 `resolve.alias` 来定义别名——这些选项应该在顶级定义,而不是在 `test` 属性内部。
-
-## Automatic Dependency Installation
-Vitest will prompt you to install certain dependencies if they are not already installed. You can disable this behavior by setting the `VITEST_SKIP_INSTALL_CHECKS=1` environment variable.
+## 自动依赖安装 {#automatic-dependency-installation}
-## Config Options
+当检测到必要依赖未安装时,Vitest 将提示你进行安装。如需禁用此功能,可通过设置环境变量 `VITEST_SKIP_INSTALL_CHECKS=1` 实现。
+
+## 配置选项 {#config-options}
在 [项目](/guide/projects) 配置中不支持的配置选项旁边会显示 图标。这意味着它们只能在 Vitest 根配置文件中进行设置。
diff --git a/config/pool.md b/config/pool.md
index 98814f20b..ad4642f4f 100644
--- a/config/pool.md
+++ b/config/pool.md
@@ -12,8 +12,8 @@ outline: deep
用于运行测试的线程池。
## threads
-
-Enable multi-threading. When using threads you are unable to use process related APIs such as `process.chdir()`. Some libraries written in native languages, such as `Prisma`, `bcrypt` and `canvas`, have problems when running in multiple threads and run into segfaults. In these cases it is advised to use `forks` pool instead.
+
+启用多线程模式。使用线程时,你无法调用进程相关 API 例如 `process.chdir()`。某些原生语言编写的库(如 `Prisma`、`bcrypt` 和 `canvas`)在多线程运行时会出现问题并导致存储器区段错误。此类情况下建议改用 `forks` 执行池。
## forks
diff --git a/config/printconsoletrace.md b/config/printconsoletrace.md
index d683d1560..a3548cdf7 100644
--- a/config/printconsoletrace.md
+++ b/config/printconsoletrace.md
@@ -8,4 +8,4 @@ outline: deep
- **类型:** `boolean`
- **默认值:** `false`
-Always print console traces when calling any `console` method. This is useful for debugging.
+始终在调用任何 `console` 方法时打印调用堆栈。特别适用于调试阶段。
diff --git a/config/snapshotformat.md b/config/snapshotformat.md
index 48d630a3a..1eead7043 100644
--- a/config/snapshotformat.md
+++ b/config/snapshotformat.md
@@ -11,7 +11,7 @@ outline: deep
关于 `PrettyFormatOptions` 的完整选项说明,请参阅 [`@vitest/pretty-format`](https://npmx.dev/package/@vitest/pretty-format)。本文档重点介绍 Vitest 快照特有的默认值和限制。
-Vitest 快照在应用您的 `snapshotFormat` 覆盖前已预设以下默认值:
+Vitest 快照在应用你的 `snapshotFormat` 覆盖前已预设以下默认值:
- `printBasicPrototype: false`
- `escapeString: false`
diff --git a/config/tasktitlevalueformattruncate.md b/config/tasktitlevalueformattruncate.md
index 69a127984..564fe59a9 100644
--- a/config/tasktitlevalueformattruncate.md
+++ b/config/tasktitlevalueformattruncate.md
@@ -1,15 +1,15 @@
---
-title: taskTitleValueFormatTruncate | Config
+title: taskTitleValueFormatTruncate | 配置
outline: deep
---
# taskTitleValueFormatTruncate {#tasktitlevalueformattruncate}
-
-- **Type** `number`
-- **Default:** `40`
-Sets the length limit for formatted values interpolated into generated task titles.
+- **类型:** `number`
+- **默认值:** `40`
-This affects values inserted by APIs like `test.each` and `test.for`, including both `$value` and `%` placeholder formatting.
+设置插入生成任务标题的格式化值的长度限制。
-Set it to `0` to disable truncation.
+此设置会影响通过 `test.each` 和 `test.for` 等 API 插入的值,包括 `$value` 和 `%` 占位符格式化。
+
+将其设置为 `0` 可禁用截断功能。
diff --git a/config/ui.md b/config/ui.md
index 00fd3130c..f07128921 100644
--- a/config/ui.md
+++ b/config/ui.md
@@ -16,5 +16,5 @@ outline: deep
:::
::: danger 安全警告
-请确保您的 UI 模式的服务不暴露在公共网络中。自 Vitest 4.1 起,出于安全考虑,若将 [`api.host`](/config/api) 设置为非 `localhost` 地址,将自动禁用代码保存和测试运行按钮,使 UI 模式变为只读模式。
+请确保你的 UI 模式的服务不暴露在公共网络中。自 Vitest 4.1 起,出于安全考虑,若将 [`api.host`](/config/api) 设置为非 `localhost` 地址,将自动禁用代码保存和测试运行按钮,使 UI 模式变为只读模式。
:::
diff --git a/config/update.md b/config/update.md
index 3b46f2cd2..c0c1cb434 100644
--- a/config/update.md
+++ b/config/update.md
@@ -9,13 +9,13 @@ outline: deep
- **默认值:** `false`
- **命令行终端:** `-u`, `--update`, `--update=false`, `--update=new`, `--update=none`
-Define snapshot update behavior.
+定义快照更新行为:
-- `true` or `'all'`: updates all changed snapshots and deletes obsolete ones
-- `new`: generates new snapshots without changing or deleting obsolete ones
-- `none`: does not write snapshots and fails on snapshot mismatches, missing snapshots, and obsolete snapshots
+- `true` 或 `'all'`:更新所有变更的快照并删除已废弃的快照
+- `'new'`:生成新快照但不修改或删除已废弃的快照
+- `'none'`:不写入快照,并在快照不匹配、快照缺失或存在废弃快照时使测试失败
-When `update` is `false` (the default), Vitest resolves snapshot update mode by environment:
+当 `update` 为 `false`(默认值)时,Vitest 根据运行环境自动决定更新模式:
-- Local runs (non-CI): works same as `new`
-- CI runs (`process.env.CI` is truthy): works same as `none`
+- 本地运行(非 CI 环境):等同于 `'new'` 模式
+- CI 运行(`process.env.CI` 为 true 时):等同于 `'none'` 模式
diff --git a/eslint.config.js b/eslint.config.js
index 518685de2..fd94fb39d 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -17,6 +17,7 @@ export default antfu(
'advanced/api/import-example.md',
'api/advanced/import-example.md',
'guide/examples/*.md',
+ 'api/advanced/reporters-life-cycle.md',
],
},
{
diff --git a/guide/advanced/tests.md b/guide/advanced/tests.md
index 1f6e24533..3e70c0dc0 100644
--- a/guide/advanced/tests.md
+++ b/guide/advanced/tests.md
@@ -1,7 +1,7 @@
# 运行测试 advanced {#running-tests}
::: warning 注意
-本指南介绍如何使用高级 API 通过 Node.js 脚本运行测试。如果您只想[运行测试](/guide/),则可能不需要这个。它主要被库的作者使用。
+本指南介绍如何使用高级 API 通过 Node.js 脚本运行测试。如果你只想 [运行测试](/guide/),则可能不需要这个。它主要被库的作者使用。
破坏性变更可能不会遵循 SemVer,请在使用实验性 API 时固定 Vitest 的版本。
:::
diff --git a/guide/browser/index.md b/guide/browser/index.md
index b49bbcf07..c6b0ec069 100644
--- a/guide/browser/index.md
+++ b/guide/browser/index.md
@@ -323,8 +323,8 @@ npx vitest --browser.headless
:::
Vitest 默认会在开发模式下自动打开浏览器界面,测试会在页面中央的 iframe 中执行。你可以通过选择界面中的预设尺寸、在测试中调用 `page.viewport` 方法,或者在 [配置文件](/config/browser/viewport) 中设置默认值来调整视口大小。
-
-For an alternative debugging model that captures DOM snapshots for every test instead of showing a live iframe, see [Trace View](/guide/browser/trace-view).
+
+如需采用捕获每个测试的 DOM 快照,而非实时显示 iframe的替代调试方案,请参阅 [追踪视图](/guide/browser/trace-view)。
## 无头模式 {#headless}
diff --git a/guide/browser/retry-ability.md b/guide/browser/retry-ability.md
index f64b34f6d..8c971235e 100644
--- a/guide/browser/retry-ability.md
+++ b/guide/browser/retry-ability.md
@@ -1,8 +1,8 @@
---
-title: Retry-ability | 浏览器模式
+title: 重试机制 | 浏览器模式
---
-# Retry-ability
+# 重试机制 {#retry-ability}
浏览器中的测试由于其异步特性,可能会不一致地失败。因此,即使条件延迟(如超时、网络请求或动画),也必须有办法保证断言成功。为此,Vitest 通过 [`expect.poll`](/api/expect#poll)和 `expect.element` API 提供了可重试的断言:
@@ -13,14 +13,14 @@ import { expect, test } from 'vitest'
test('error banner is rendered', async () => {
triggerError()
- // @testing-library provides queries with built-in retry-ability
- // It will try to find the banner until it's rendered
+ // @testing-library 提供具备内置重试能力的查询方法
+ // 将持续尝试查找 banner 直到其渲染完成
const banner = await screen.findByRole('alert', {
name: /error/i,
})
- // Vitest provides `expect.element` with built-in retry-ability
- // It will check `element.textContent` until it's equal to "Error!"
+ // Vitest 提供具备内置重试能力的 `expect.element`
+ // 将持续检查 `element.textContent` 直到其等于 "Error!"
await expect.element(banner).toHaveTextContent('Error!')
})
```
@@ -31,7 +31,7 @@ test('error banner is rendered', async () => {
`toHaveTextContent` 和所有其他 [`@testing-library/jest-dom`](https://github.com/testing-library/jest-dom)断言在没有内置重试机制的常规`expect`中仍然可用:
```ts
-// will fail immediately if .textContent is not `'Error!'`
+// 如果 .textContent 不是 `'Error!'` 将立即失败
expect(banner).toHaveTextContent('Error!')
```
:::
diff --git a/guide/cli-generated.md b/guide/cli-generated.md
index f6b86c13d..9c05409fe 100644
--- a/guide/cli-generated.md
+++ b/guide/cli-generated.md
@@ -252,7 +252,7 @@ Coverage reporters to use. Visit [`coverage.reporter`](/config/coverage#coverage
- **命令行终端:** `--coverage.customProviderModule `
- **配置:** [coverage.customProviderModule](/config/coverage#coverage-customprovidermodule)
-Specifies the module name or path for the custom coverage provider module. Visit [Custom Coverage Provider](/guide/coverage#custom-coverage-provider) for more information. This option is only available for custom providers
+指定自定义覆盖率提供者模块的模块名称或路径。详情请参阅 [自定义覆盖率提供者](/guide/coverage#custom-coverage-provider) 了解更多信息。此选项仅适用于自定义提供者。
### coverage.watermarks.statements
@@ -280,24 +280,24 @@ Specifies the module name or path for the custom coverage provider module. Visit
### coverage.changed
-- **CLI:** `--coverage.changed `
-- **Config:** [coverage.changed](/config/coverage#coverage-changed)
+- **命令行终端:** `--coverage.changed `
+- **配置:** [coverage.changed](/config/coverage#coverage-changed)
-Collect coverage only for files changed since a specified commit or branch (e.g., `origin/main` or `HEAD~1`). Inherits value from `--changed` by default.
+仅收集指定提交或分支(例如 `origin/main` 或 `HEAD~1`)以来更改的文件的覆盖率。默认继承自 `--changed` 的值。
### coverage.excludeAfterRemap
-- **CLI:** `--coverage.excludeAfterRemap`
-- **Config:** [coverage.excludeAfterRemap](/config/coverage#coverage-excludeafterremap)
+- **命令行终端:** `--coverage.excludeAfterRemap`
+- **配置:** [coverage.excludeAfterRemap](/config/coverage#coverage-excludeafterremap)
-Apply exclusions again after coverage has been remapped to original sources. (default: false)
+在覆盖率数据重新映射回源代码后再次应用排除规则。(默认值:false)
### coverage.htmlDir
-- **CLI:** `--coverage.htmlDir `
-- **Config:** [coverage.htmlDir](/config/coverage#coverage-htmldir)
+- **命令行终端:** `--coverage.htmlDir `
+- **配置:** [coverage.htmlDir](/config/coverage#coverage-htmldir)
-Directory of HTML coverage output to be served in UI mode and HTML reporter.
+UI 模式和 HTML 报告器中提供的 HTML 覆盖率输出目录。
### mode
@@ -428,55 +428,55 @@ Directory of HTML coverage output to be served in UI mode and HTML reporter.
- **配置:** [browser.trace](/config/browser/trace)
启用追踪视图模式。 可选项: "on", "off", "on-first-retry", "on-all-retries", "retain-on-failure"
-
+
### browser.traceView.enabled
-- **CLI:** `--browser.traceView.enabled`
-- **Config:** [browser.traceView.enabled](/config/browser/traceview#traceview-enabled)
+- **命令行终端:** `--browser.traceView.enabled`
+- **配置:** [browser.traceView.enabled](/config/browser/traceview#traceview-enabled)
-Enable Vitest trace-view collection for browser tests (default: `false`)
+启用浏览器测试 Vitest 追踪视图收集功能(默认值:`false`)
### browser.traceView.recordCanvas
-- **CLI:** `--browser.traceView.recordCanvas`
-- **Config:** [browser.traceView.recordCanvas](/config/browser/traceview#traceview-recordcanvas)
+- **命令行终端:** `--browser.traceView.recordCanvas`
+- **配置:** [browser.traceView.recordCanvas](/config/browser/traceview#traceview-recordcanvas)
-Capture canvas pixels in trace-view snapshots (default: `false`)
+在追踪视图快照中捕获 Canvas 像素(默认:`false`)
### browser.traceView.inlineImages
-- **CLI:** `--browser.traceView.inlineImages`
-- **Config:** [browser.traceView.inlineImages](/config/browser/traceview#traceview-inlineimages)
+- **命令行终端:** `--browser.traceView.inlineImages`
+- **配置:** [browser.traceView.inlineImages](/config/browser/traceview#traceview-inlineimages)
-Inline loaded image pixels in trace-view snapshots (default: `false`)
+在追踪视图快照中内联加载的图像像素(默认值:`false`)
### browser.locators.exact
-- **CLI:** `--browser.locators.exact`
-- **Config:** [browser.locators.exact](/config/browser/locators#locators-exact)
+- **命令行终端:** `--browser.locators.exact`
+- **配置:** [browser.locators.exact](/config/browser/locators#locators-exact)
-Should locators match the text exactly by default (default: `false`)
+定位器是否默认需完全匹配文本内容(默认值:`false`)
### pool
- **命令行终端:** `--pool `
- **配置:** [pool](/config/pool)
-如果未在浏览器中运行,则指定 pool (默认值: `threads`)
+如果未在浏览器中运行,则指定 pool (默认值: `threads`)。
### execArgv
- **命令行终端:** `--execArgv