diff --git a/.vitepress/config.ts b/.vitepress/config.ts index 507100c4..b6316a59 100644 --- a/.vitepress/config.ts +++ b/.vitepress/config.ts @@ -262,11 +262,11 @@ export default ({ mode }: { mode: string }) => { sidebar: { '/config': [ { - text: 'Config Reference', + text: '配置索引', collapsed: false, items: [ { - text: '配置文件', + text: '配置 Vitest', link: '/config/', }, { diff --git a/api/expect.md b/api/expect.md index 1ec7ba5b..418fee79 100644 --- a/api/expect.md +++ b/api/expect.md @@ -861,9 +861,9 @@ test('throws non-Error values', () => { }) ``` ::: - -:::warning Unhandled Rejections with Fake Timers -When using fake timers, an async function that rejects _during_ a `vi.advanceTimersByTimeAsync` call will trigger an [unhandled rejection](https://nodejs.org/api/process.html#event-unhandledrejection) — even if you later assert it with `.rejects.toThrow()`. This happens because the error is thrown before the `expect` chain has a chance to catch it. + +:::warning 使用假定时器时的未处理拒绝 +当使用假定时器时,在 `vi.advanceTimersByTimeAsync` 调用期间被拒绝的异步函数会触发 [未处理的拒绝](https://nodejs.org/api/process.html#event-unhandledrejection),即使你稍后使用 `.rejects.toThrow()` 进行断言。这是因为错误在 `expect` 链有机会捕获之前就被抛出了。 ```ts async function foo() { @@ -876,12 +876,12 @@ test('rejects', async () => { await vi.advanceTimersByTimeAsync(100) - // The assertion passes, but the error was already "unhandled" during advanceTimersByTimeAsync + // 断言虽然通过,但在 advanceTimersByTimeAsync 期间错误已经是 “未处理” 状态 await expect(result).rejects.toThrow() }) ``` -To avoid this, prefer [`vi.setTimerTickMode('nextTimerAsync')`](/api/vi#vi-settimertickmode) so that timers tick automatically as promises settle, without needing a manual advance: +为避免这种情况,推荐使用 [`vi.setTimerTickMode('nextTimerAsync')`](/api/vi#vi-settimertickmode),这样定时器会在 Promise 解决时自动触发,无需手动调用: ```ts beforeEach(() => { @@ -890,12 +890,12 @@ beforeEach(() => { }) test('rejects', async () => { - // No advanceTimersByTimeAsync needed — the error is caught by rejects.toThrow() + // 不需要 advanceTimersByTimeAsync,错误会被 rejects.toThrow() 捕获 await expect(foo()).rejects.toThrow('boom') }) ``` -Alternatively, set up the `.rejects.toThrow()` assertion _before_ advancing timers so the rejection is handled immediately: +或者,也可以在推进计时器 _之前_ 设置 `.rejects.toThrow()` 断言,这样就能立即处理失败情况: ```ts test('rejects', async () => { @@ -1606,10 +1606,10 @@ test('spy nth called with', () => { ``` ## returned 4.1.0 {#returned} - -- **Type:** `(value: any) => void` -Chai-style assertion that checks if a spy returned a specific value at least once. This is equivalent to `toHaveReturnedWith(value)`. +- **类型:**`(value: any) => void` + +Chai 风格断言,用于检查 spy 函数是否至少返回过一次指定的值。等价于 `toHaveReturnedWith(value)`。 ```ts import { expect, test, vi } from 'vitest' diff --git a/api/mock.md b/api/mock.md index 9ee2da82..916485a5 100644 --- a/api/mock.md +++ b/api/mock.md @@ -20,8 +20,8 @@ getApplesSpy.mock.calls.length === 1 要验证 mock 的行为,请通过 [`expect`](/api/expect) 调用类似 [`toHaveBeenCalled`](/api/expect#tohavebeencalled) 的断言方法;以下 API 参考汇总了所有可用来操控 mock 的属性和方法。 -::: warning IMPORTANT -Vitest spies inherit implementation's [`length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) property when initialized, but it doesn't override it if the implementation was changed later: +::: warning 重要说明 +Vitest 的 spy 函数在初始化时会继承被监听函数的 [`length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) 属性,但后续如果修改被监听函数,则不会覆盖该属性值。 ::: code-group ```ts [vi.fn] @@ -50,10 +50,8 @@ fn.length // == 2 以下类型中的自定义函数实现使用泛型 `` 进行标记。 ::: - - -::: warning Class Support {#class-support} -Shorthand methods like `mockReturnValue`, `mockReturnValueOnce`, `mockResolvedValue` and others cannot be used on a mocked class. Class constructors have [unintuitive behaviour](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) regarding the return value: +::: warning 类支持 {#class-support} +像 `mockReturnValue`、`mockReturnValueOnce`、`mockResolvedValue` 这样的简写方法不能用于模拟类。类构造函数在返回值方面具有[反直觉的行为](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor): ```ts {2,7} const CorrectDogClass = vi.fn(class { @@ -73,16 +71,16 @@ Marti instanceof CorrectDogClass // ✅ true Newt instanceof IncorrectDogClass // ❌ false! ``` -Even though the shapes are the same, the _return value_ from the constructor is assigned to `Newt`, which is a plain object, not an instance of a mock. Vitest guards you against this behaviour in shorthand methods (but not in `mockImplementation`!) and throws an error instead. +尽管接口规范相同,但构造函数的 _返回值_ 被赋给了 `Newt`,这是一个普通对象,而非模拟类的实例。Vitest 会在简写方法中(但不会在 `mockImplementation` 中!)防止这种行为,转而抛出错误。 -If you need to mock constructed instance of a class, consider using the `class` syntax with `mockImplementation` instead: +如果需要模拟类的构造实例,考虑改用 `class` 语法配合 `mockImplementation`: ```ts mock.mockReturnValue({ hello: () => 'world' }) // [!code --] mock.mockImplementation(class { hello = () => 'world' }) // [!code ++] ``` -If you need to test the behaviour where this is a valid use case, you can use `mockImplementation` with a `constructor`: +如果需要测试这种有效用例的行为,可以使用带有 `constructor` 的 `mockImplementation`: ```ts mock.mockImplementation(class { @@ -425,19 +423,18 @@ const myMockFn = vi // 'first call', 'second call', 'default', 'default' console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()) ``` - ## mockThrow 4.1.0 {#mockthrow} ```ts function mockThrow(value: unknown): Mock ``` -Accepts a value that will be thrown whenever the mock function is called. +接收一个值,该值会在每次调用模拟函数时被抛出。 ```ts const myMockFn = vi.fn() myMockFn.mockThrow(new Error('error message')) -myMockFn() // throws Error<'error message'> +myMockFn() // 抛出 <'error message'> 错误 ``` ## mockThrowOnce 4.1.0 {#mockthrowonce} @@ -446,7 +443,7 @@ myMockFn() // throws Error<'error message'> function mockThrowOnce(value: unknown): Mock ``` -Accepts a value that will be thrown during the next function call. If chained, every consecutive call will throw the specified value. +接收一个值,该值会在下一次函数调用时被抛出。如果链式调用,每次连续调用都会抛出指定的值。 ```ts const myMockFn = vi @@ -476,8 +473,8 @@ fn('arg3') fn.mock.calls === [ - ['arg1', 'arg2'], // first call - ['arg3'], // second call + ['arg1', 'arg2'], // 首次调用 + ['arg3'], // 第二次调用 ] ``` diff --git a/api/vi.md b/api/vi.md index 2a77fcea..13f78fbc 100644 --- a/api/vi.md +++ b/api/vi.md @@ -1071,7 +1071,7 @@ function useFakeTimers(config?: FakeTimerInstallOpts): Vitest ### vi.setTimerTickMode 4.1.0 {#vi-settimertickmode} -- **Type:** `(mode: 'manual' | 'nextTimerAsync') => Vitest | (mode: 'interval', interval?: number) => Vitest` +- **类型:**`(mode: 'manual' | 'nextTimerAsync') => Vitest | (mode: 'interval', interval?: number) => Vitest` Controls how fake timers are advanced. @@ -1125,9 +1125,9 @@ function useRealTimers(): Vitest 当定时器用完后,我们可以调用此方法将模拟的计时器返回到其原始实现。之前调度的计时器都将被丢弃。 -## 辅助函数{#miscellaneous} +## 工具函数{#miscellaneous} -Vitest 提供的一组有用的辅助函数。 +Vitest 提供的一组有用的工具函数。 ### vi.waitFor {#vi-waitfor} @@ -1342,17 +1342,15 @@ function resetConfig(): void 如果之前调用过 [`vi.setConfig`](#vi-setconfig) ,则会将配置重置为原始状态。 - - ### vi.defineHelper 4.1.0 {#vi-defineHelper} ```ts function defineHelper any>(fn: F): F ``` -Wraps a function to create an assertion helper. When an assertion fails inside the helper, the error stack trace will point to where the helper was called, not inside the helper itself. This makes it easier to identify the source of test failures when using custom assertion functions. +封装函数以创建断言工具函数。当功能函数内断言失败时,错误堆栈会指向调用工具函数的位置,而非工具函数内部。这使得使用自定义断言函数时能更轻松定位测试失败根源。 -Works with both synchronous and asynchronous functions, and supports `expect.soft()`. +同时支持同步和异步函数,并兼容 `expect.soft()` 用法。 ```ts import { expect, vi } from 'vitest' @@ -1362,11 +1360,11 @@ const assertPair = vi.defineHelper((a, b) => { }) test('example', () => { - assertPair('left', 'right') // Error points to this line + assertPair('left', 'right') // 错误将指向此行 }) ``` -Example output: +示例输出: ```js diff --git a/config/alias.md b/config/alias.md index b2974c96..65db8b43 100644 --- a/config/alias.md +++ b/config/alias.md @@ -1,18 +1,18 @@ --- -title: alias | Config +title: alias | 配置 outline: deep --- # alias -- **Type:** `Record | Array<{ find: string | RegExp, replacement: string, customResolver?: ResolverFunction | ResolverObject }>` +- **类型:** `Record | Array<{ find: string | RegExp, replacement: string, customResolver?: ResolverFunction | ResolverObject }>` -Define custom aliases when running inside tests. They will be merged with aliases from `resolve.alias`. +在测试环境中定义自定义别名。这些别名将与 `resolve.alias` 中的配置合并使用。 ::: warning -Vitest uses Vite SSR primitives to run tests which has [certain pitfalls](https://vitejs.dev/guide/ssr.html#ssr-externals). +Vitest 基于 Vite 的 SSR 底层机制运行测试,可能存在 [潜在的缺陷](https://cn.vitejs.dev/guide/ssr.html#ssr-externals)。 -1. Aliases affect only modules imported directly with an `import` keyword by an [inlined](/config/server#server-deps-inline) module (all source code is inlined by default). -2. Vitest does not support aliasing `require` calls. -3. If you are aliasing an external dependency (e.g., `react` -> `preact`), you may want to alias the actual `node_modules` packages instead to make it work for externalized dependencies. Both [Yarn](https://classic.yarnpkg.com/en/docs/cli/add/#toc-yarn-add-alias) and [pnpm](https://pnpm.io/aliases/) support aliasing via the `npm:` prefix. +1. 别名仅影响由 [内联模块](/config/server#server-deps-inline) 通过 `import` 关键字直接导入的模块 (默认情况下所有源代码均被内联)。 +2. Vitest 不支持对 `require` 调用进行别名配置。 +3. 如果我们要为外部依赖项设置别名(例如,`react` -> `preact`),建议直接对 `node_modules` 中的实际包进行别名配置,以确保该方案在外部化依赖场景下同样生效。[Yarn](https://classic.yarnpkg.com/en/docs/cli/add/#toc-yarn-add-alias) 和 [pnpm](https://pnpm.io/aliases/) 均支持通过 `npm:` 前缀实现别名功能。 ::: diff --git a/config/allowonly.md b/config/allowonly.md index 44ff47bf..7e932f0e 100644 --- a/config/allowonly.md +++ b/config/allowonly.md @@ -1,23 +1,21 @@ --- -title: allowOnly | Config +title: allowOnly | 配置 outline: deep --- - - # allowOnly -- **Type**: `boolean` -- **Default**: `!process.env.CI` -- **CLI:** `--allowOnly`, `--allowOnly=false` +- **类型:**: `boolean` +- **默认值:**: `!process.env.CI` +- **命令行终端:** `--allowOnly`, `--allowOnly=false` -By default, Vitest does not permit tests marked with the [`only`](/api/test#test-only) flag in Continuous Integration (CI) environments. Conversely, in local development environments, Vitest allows these tests to run. +默认情况下,Vitest 不允许在持续集成(CI)环境中运行带有 [`only`](/api/test#test-only) 标记的测试。相反,在本地开发环境中,Vitest 允许运行这些测试。 ::: info -Vitest uses [`std-env`](https://npmx.dev/package/std-env) package to detect the environment. +Vitest 使用 [`std-env`](https://npmx.dev/package/std-env) 包来检测环境。 ::: -You can customize this behavior by explicitly setting the `allowOnly` option to either `true` or `false`. +你可以通过显式设置 `allowOnly` 选项为 `true` 或 `false` 来自定义此行为。 ::: code-group ```js [vitest.config.js] @@ -34,6 +32,6 @@ vitest --allowOnly ``` ::: -When enabled, Vitest will not fail the test suite if tests marked with [`only`](/api/test#test-only) are detected, including in CI environments. +启用时,即使检测到带有 [`only`](/api/test#test-only) 标记的测试,Vitest 也不会导致测试套件失败,包括在 CI 环境中。 -When disabled, Vitest will fail the test suite if tests marked with [`only`](/api/test#test-only) are detected, including in local development environments. +禁用时时,如果检测到带有 [`only`](/api/test#test-only) 标记的测试,Vitest 将导致测试套件失败,包括在本地开发环境中。 diff --git a/config/api.md b/config/api.md index b20c5408..ee784dd6 100644 --- a/config/api.md +++ b/config/api.md @@ -1,34 +1,32 @@ --- -title: api | Config +title: api | 配置 outline: deep --- - - # api -- **Type:** `boolean | number | object` -- **Default:** `false` -- **CLI:** `--api`, `--api.port`, `--api.host`, `--api.strictPort` +- **类型:** `boolean | number | object` +- **默认值:** `false` +- **命令行终端:** `--api`, `--api.port`, `--api.host`, `--api.strictPort` -Listen to port and serve API for [the UI](/guide/ui) or [browser server](/guide/browser/). When set to `true`, the default port is `51204`. +监听端口并提供 API 服务,用于 [UI 模式](/guide/ui) 或 [浏览器服务](/guide/browser/)。设为 `true` 时,默认端口为 `51204`。 ## api.allowWrite 4.1.0 {#api-allowwrite} -- **Type:** `boolean` -- **Default:** `true` if not exposed to the network, `false` otherwise +- **类型:** `boolean` +- **默认值:** `true` 表示未暴露在公共网络中,`false` 则表示已暴露 -Vitest server can save test files or snapshot files via the API. This allows anyone who can connect to the API the ability to run any arbitrary code on your machine. +Vitest 服务器可以通过 API 保存测试文件或快照文件。这意味着任何能连接到 API 的人都可以在你的机器上运行任意代码。 -::: danger SECURITY ADVICE -Vitest does not expose the API to the internet by default and only listens on `localhost`. However if `host` is manually exposed to the network, anyone who connects to it can run arbitrary code on your machine, unless `api.allowWrite` and `api.allowExec` are set to `false`. +::: danger 安全警告 +Vitest 默认不会将 API 暴露到互联网,仅在 `localhost` 上监听。但如果 `host` 被手动暴露到网络,任何连接到它的人都可以在你的机器上运行任意代码,除非将 `api.allowWrite` 和 `api.allowExec` 设置为`false`。 -If the host is set to anything other than `localhost` or `127.0.0.1`, Vitest will set `api.allowWrite` and `api.allowExec` to `false` by default. This means that any write operations (like changing the code in the UI) will not work. However, if you understand the security implications, you can override them. +如果 host 设置为 `localhost` 或 `127.0.0.1` 以外的任何值,Vitest 会默认将 `api.allowWrite` 和 `api.allowExec` 设置为 `false`。这意味着任何写入操作(例如 在 UI 模式中修改代码)将不起作用。如果你了解安全风险,可以覆盖这些设置。 ::: ## api.allowExec 4.1.0 {#api-allowexec} -- **Type:** `boolean` -- **Default:** `true` if not exposed to the network, `false` otherwise +- **类型:** `boolean` +- **默认值:** `true` 表示未暴露在公共网络中,`false` 则表示已暴露 -Allows running any test file via the API. See the security advice in [`api.allowWrite`](#api-allowwrite). +允许通过 API 运行任何测试文件。详细安全建议请参阅 [`api.allowWrite`](#api-allowwrite)。 diff --git a/config/attachmentsdir.md b/config/attachmentsdir.md index 993fa9f8..8887d331 100644 --- a/config/attachmentsdir.md +++ b/config/attachmentsdir.md @@ -1,11 +1,11 @@ --- -title: attachmentsDir | Config +title: attachmentsDir | 配置 outline: deep --- # attachmentsDir -- **Type:** `string` -- **Default:** `'.vitest-attachments'` +- **类型:** `string` +- **默认值:** `'.vitest-attachments'` -Directory path for storing attachments created by [`context.annotate`](/guide/test-context#annotate) relative to the project root. +用于存储 [`context.annotate`](/guide/test-context#annotate) 所创建附件的目录路径(相对于项目根目录)。 diff --git a/config/bail.md b/config/bail.md index 27018e56..855d23d0 100644 --- a/config/bail.md +++ b/config/bail.md @@ -1,14 +1,14 @@ --- -title: bail | Config +title: bail | 配置 outline: deep --- # bail -- **Type:** `number` -- **Default:** `0` -- **CLI**: `--bail=` +- **类型:** `number` +- **默认值:** `0` +- **命令行终端:** `--bail=` -Stop test execution when given number of tests have failed. +当指定数量的测试用例失败时立即终止测试执行。 -By default Vitest will run all of your test cases even if some of them fail. This may not be desired for CI builds where you are only interested in 100% successful builds and would like to stop test execution as early as possible when test failures occur. The `bail` option can be used to speed up CI runs by preventing it from running more tests when failures have occurred. +默认情况下,即使部分测试失败,Vitest 仍会继续运行所有测试用例。对于仅关注 100% 成功构建的 CI 环境而言,这种行为可能不符合需求——您可能希望在测试出现失败时尽早终止执行。通过配置 `bail` 选项,可在发生失败时阻止后续测试运行,从而加速 CI 流程。 diff --git a/config/benchmark.md b/config/benchmark.md index 052c6025..755dfa0e 100644 --- a/config/benchmark.md +++ b/config/benchmark.md @@ -1,5 +1,5 @@ --- -title: benchmark | Config +title: benchmark | 配置 outline: deep --- diff --git a/config/browser/api.md b/config/browser/api.md index a792e338..75d62938 100644 --- a/config/browser/api.md +++ b/config/browser/api.md @@ -1,30 +1,28 @@ --- -title: browser.api | Config +title: browser.api | 配置 outline: deep --- - - # browser.api -- **Type:** `number | object` -- **Default:** `63315` -- **CLI:** `--browser.api=63315`, `--browser.api.port=1234, --browser.api.host=example.com` +- **类型:** `number | object` +- **默认值:** `63315` +- **命令行终端:** `--browser.api=63315`, `--browser.api.port=1234, --browser.api.host=example.com` -Configure options for Vite server that serves code in the browser. Does not affect [`test.api`](/config/api) option. By default, Vitest assigns port `63315` to avoid conflicts with the development server, allowing you to run both in parallel. +配置用于在浏览器中提供代码的 Vite 服务器选项。不影响 [`test.api`](/config/api) 配置。默认情况下,Vitest 会分配 `63315` 端口以避免与开发服务器冲突,从而实现两者并行运行。 ## api.allowWrite 4.1.0 {#api-allowwrite} -- **Type:** `boolean` -- **Default:** `true` if not exposed to the network, `false` otherwise +- **类型:** `boolean` +- **默认值:** 未暴露公网时默认为 `true`,否则为 `false` -Vitest saves [annotation attachments](/guide/test-annotations), [artifacts](/api/advanced/artifacts) and [snapshots](/guide/snapshot) by receiving a WebSocket connection from the browser. This allows anyone who can connect to the API write any arbitrary code on your machine within the root of your project (configured by [`fs.allow`](https://vite.dev/config/server-options#server-fs-allow)). +Vitest 通过接收来自浏览器的 WebSocket 连接来保存 [测试注解](/guide/test-annotations)、[测试产物](/api/advanced/artifacts) 和 [快照](/guide/snapshot)。这意味着任何能连接到该 API 的人都可在你机器的项目根目录(由 [`fs.allow`](https://cn.vite.dev/config/server-options#server-fs-allow) 配置)内执行任意代码。 -If browser server is not exposed to the internet (the host is `localhost`), this should not be a problem, so the default value in that case is `true`. If you override the host, Vitest will set `allowWrite` to `false` by default to prevent potentially harmful writes. +当浏览器服务器未暴露至互联网(主机为 `localhost`)时,默认值设为 `true` 不会构成安全隐患。若你修改了主机配置,Vitest 将默认将 `allowWrite` 设为 `false` 以防止潜在的恶意写入风险。 ## api.allowExec 4.1.0 {#api-allowexec} -- **Type:** `boolean` -- **Default:** `true` if not exposed to the network, `false` otherwise +- **类型:** `boolean` +- **默认值:** 未暴露至公网时默认为 `true`,否则为 `false` -Allows running any test file via the UI. This only applies to the interactive elements (and the server code behind them) in the [UI](/guide/ui) that can run the code. If UI is disabled, this has no effect. See [`api.allowExec`](/config/api#api-allowexec) for more information. +允许通过 [UI 模式](/guide/ui) 运行任意测试文件。此配置仅作用于界面交互元素(及其背后的服务端代码)的可执行权限。如果 UI 模式被禁用,则该配置不生效。更多信息请参阅 [`api.allowExec`](/config/api#api-allowexec)。 diff --git a/config/browser/commands.md b/config/browser/commands.md index b933f093..69362fbc 100644 --- a/config/browser/commands.md +++ b/config/browser/commands.md @@ -1,11 +1,11 @@ --- -title: browser.commands | Config +title: browser.commands | 配置 outline: deep --- # browser.commands -- **Type:** `Record` -- **Default:** `{ readFile, writeFile, ... }` +- **类型:** `Record` +- **默认值:** `{ readFile, writeFile, ... }` -Custom [commands](/api/browser/commands) that can be imported during browser tests from `vitest/browser`. +可在浏览器测试中通过 `vitest/browser` 导入 [自定义命令](/api/browser/commands)。 diff --git a/config/browser/connecttimeout.md b/config/browser/connecttimeout.md index 275b39b5..32340dad 100644 --- a/config/browser/connecttimeout.md +++ b/config/browser/connecttimeout.md @@ -1,15 +1,15 @@ --- -title: browser.connectTimeout | Config +title: browser.connectTimeout | 配置 outline: deep --- # browser.connectTimeout -- **Type:** `number` -- **Default:** `60_000` +- **类型:** `number` +- **默认值:** `60_000` -The timeout in milliseconds. If connection to the browser takes longer, the test suite will fail. +连接超时时间(毫秒)。如果浏览器连接耗时超过此阈值,测试套件将判定为运行失败。 ::: info -This is the time it should take for the browser to establish the WebSocket connection with the Vitest server. In normal circumstances, this timeout should never be reached. +此超时设置针对浏览器与 Vitest 服务器建立 WebSocket 连接的耗时。正常情况下,不会触发此超时限制。 ::: diff --git a/config/browser/detailspanelposition.md b/config/browser/detailspanelposition.md index e71ca3fa..cb92b3ff 100644 --- a/config/browser/detailspanelposition.md +++ b/config/browser/detailspanelposition.md @@ -1,20 +1,18 @@ --- -title: browser.detailsPanelPosition | Config +title: browser.detailsPanelPosition | 配置 outline: deep --- - - # browser.detailsPanelPosition -- **Type:** `'right' | 'bottom'` -- **Default:** `'right'` -- **CLI:** `--browser.detailsPanelPosition=bottom`, `--browser.detailsPanelPosition=right` +- **类型:** `'right' | 'bottom'` +- **默认值:** `'right'` +- **命令行终端:** `--browser.detailsPanelPosition=bottom`, `--browser.detailsPanelPosition=right` -Controls the default position of the details panel in the Vitest UI when running browser tests. +控制运行浏览器测试时 UI 模式中详情面板的默认位置。 -- `'right'` - Shows the details panel on the right side with a horizontal split between the browser viewport and the details panel. -- `'bottom'` - Shows the details panel at the bottom with a vertical split between the browser viewport and the details panel. +- `'right'` - 在右侧显示详情面板,采用浏览器视窗与详情面板的水平分割布局。 +- `'bottom'` - 在底部显示详情面板,采用浏览器视窗与详情面板的垂直分割布局。 ```ts [vitest.config.ts] import { defineConfig } from 'vitest/config' @@ -23,13 +21,13 @@ export default defineConfig({ test: { browser: { enabled: true, - detailsPanelPosition: 'bottom', // or 'right' + detailsPanelPosition: 'bottom', // 或 'right' }, }, }) ``` -## Example +## 示例 {#example} ::: tabs == bottom diff --git a/config/browser/enabled.md b/config/browser/enabled.md index 766e85ba..d51beb76 100644 --- a/config/browser/enabled.md +++ b/config/browser/enabled.md @@ -1,28 +1,28 @@ --- -title: browser.enabled | Config +title: browser.enabled | 配置 --- # browser.enabled -- **Type:** `boolean` -- **Default:** `false` -- **CLI:** `--browser`, `--browser.enabled=false` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--browser`, `--browser.enabled=false` -Enabling this flag makes Vitest run all tests in a [browser](/guide/browser/) by default. If you are configuring other browser options via the CLI, you can use `--browser.enabled` alongside them instead of `--browser`: +启用此参数后,Vitest 默认会在 [浏览器](/guide/browser/) 中运行所有测试。如哦需通过命令行配置其他浏览器选项,可使用 `--browser.enabled` 参数替代 `--browser` 与其他选项搭配使用。 ```sh vitest --browser.enabled --browser.headless ``` ::: warning -To enable [Browser Mode](/guide/browser/), you must also specify the [`provider`](/config/browser/provider) and at least one [`instance`](/config/browser/instances). Available providers: +要启用 [浏览器模式](/guide/browser/),必须同时指定 [`provider`](/config/browser/provider) 和至少一个 [`instance`](/config/browser/instances)。可用的提供驱动包括: - [playwright](/config/browser/playwright) - [webdriverio](/config/browser/webdriverio) - [preview](/config/browser/preview) ::: -## Example +## 示例 {#example} ```js{7} [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -41,4 +41,4 @@ export default defineConfig({ }) ``` -If you use TypeScript, the `browser` field in `instances` provides autocompletion based on your provider. +如果使用 TypeScript,`instances` 中的 `browser` 字段会根据你选择的提供程序自动提供代码补全功能。 diff --git a/config/browser/expect.md b/config/browser/expect.md index dff6d64b..94f4d4a1 100644 --- a/config/browser/expect.md +++ b/config/browser/expect.md @@ -1,22 +1,18 @@ --- -title: browser.expect | Config +title: browser.expect | 配置 outline: deep --- # browser.expect -- **Type:** `ExpectOptions` +- **类型:** `ExpectOptions` ## browser.expect.toMatchScreenshot -Default options for the -[`toMatchScreenshot` assertion](/api/browser/assertions.html#tomatchscreenshot). -These options will be applied to all screenshot assertions. +[`toMatchScreenshot` 断言](/api/browser/assertions.html#tomatchscreenshot) 的默认选项。这些配置将应用于所有截图断言。 -::: tip -Setting global defaults for screenshot assertions helps maintain consistency -across your test suite and reduces repetition in individual tests. You can still -override these defaults at the assertion level when needed for specific test cases. +::: tip 提示 +为截图断言设置全局默认值有助于在测试套件中保持一致性,并减少单个测试中的重复。在需要特定测试用例时,仍可在断言级别覆盖这些默认值。 ::: ```ts @@ -42,24 +38,20 @@ export default defineConfig({ }) ``` -[All options available in the `toMatchScreenshot` assertion](/api/browser/assertions#options) -can be configured here. Additionally, two path resolution functions are -available: `resolveScreenshotPath` and `resolveDiffPath`. +[`toMatchScreenshot` 断言中所有可用选项](/api/browser/assertions#options) 均可在此配置。此外还提供两个路径解析函数:`resolveScreenshotPath` 和 `resolveDiffPath`。 ## browser.expect.toMatchScreenshot.resolveScreenshotPath -- **Type:** `(data: PathResolveData) => string` -- **Default output:** `` `${root}/${testFileDirectory}/${screenshotDirectory}/${testFileName}/${arg}-${browserName}-${platform}${ext}` `` +- **类型:** `(data: PathResolveData) => string` +- **默认输出:** `` `${root}/${testFileDirectory}/${screenshotDirectory}/${testFileName}/${arg}-${browserName}-${platform}${ext}` `` -A function to customize where reference screenshots are stored. The function -receives an object with the following properties: +用于自定义参考截图存储路径的函数。该函数接收包含以下属性的对象: - `arg: string` - Path **without** extension, sanitized and relative to the test file. + 经过标准化处理的相对路径,**不含** 扩展名,相对于测试文件路径。 - This comes from the arguments passed to `toMatchScreenshot`; if called - without arguments this will be the auto-generated name. + 该路径源自传递给 `toMatchScreenshot` 的参数;如果调用时未传参数,则使用自动生成的名称。 ```ts test('calls `onClick`', () => { @@ -76,49 +68,43 @@ receives an object with the following properties: - `ext: string` - Screenshot extension, with leading dot. + 截图扩展名(需携带 . 符号)。 - This can be set through the arguments passed to `toMatchScreenshot`, but - the value will fall back to `'.png'` if an unsupported extension is used. + 可通过 `toMatchScreenshot` 的参数设置,如果使用不支持的扩展名则默认回退为 `'.png'`。 - `browserName: string` - The instance's browser name. + 当前实例的浏览器名称。 - `platform: NodeJS.Platform` - The value of - [`process.platform`](https://nodejs.org/docs/v22.16.0/api/process.html#processplatform). + 该值为 [`process.platform`](https://nodejs.org/docs/v22.16.0/api/process.html#processplatform). - `screenshotDirectory: string` - The value provided to - [`browser.screenshotDirectory`](/config/browser/screenshotdirectory), - if none is provided, its default value. + [`browser.screenshotDirectory`](/config/browser/screenshotdirectory) 配置项提供的值,如果未配置则使用其默认值。 - `root: string` - Absolute path to the project's [`root`](/config/root). + 项目 [`root`](/config/root) 的绝对路径。 - `testFileDirectory: string` - Path to the test file, relative to the project's [`root`](/config/root). + 测试文件相对于项目 [`root`](/config/root) 的相对路径。 - `testFileName: string` - The test's filename. + 测试文件的文件名。 - `testName: string` - The [`test`](/api/test)'s name, including parent - [`describe`](/api/describe), sanitized. + 经过标准化处理的 [`test`](/api/test) 名称(包含父级 [`describe`](/api/describe) 信息)。 - `attachmentsDir: string` - The value provided to [`attachmentsDir`](/config/attachmentsdir), if none is - provided, its default value. + [`attachmentsDir`](/config/attachmentsdir) 配置项提供的值,如果未配置则使用其默认值。 -For example, to group screenshots by browser: +例如,以下示例按浏览器分组存储截图: ```ts resolveScreenshotPath: ({ arg, browserName, ext, root, testFileName }) => @@ -127,14 +113,12 @@ resolveScreenshotPath: ({ arg, browserName, ext, root, testFileName }) => ## browser.expect.toMatchScreenshot.resolveDiffPath -- **Type:** `(data: PathResolveData) => string` -- **Default output:** `` `${root}/${attachmentsDir}/${testFileDirectory}/${testFileName}/${arg}-${browserName}-${platform}${ext}` `` +- **类型:** `(data: PathResolveData) => string` +- **默认输出:** `` `${root}/${attachmentsDir}/${testFileDirectory}/${testFileName}/${arg}-${browserName}-${platform}${ext}` `` -A function to customize where diff images are stored when screenshot comparisons -fail. Receives the same data object as -[`resolveScreenshotPath`](#browser-expect-tomatchscreenshot-resolvescreenshotpath). +用于自定义截图比对失败时差异图片存储位置的函数。接收与 [`resolveScreenshotPath`](#browser-expect-tomatchscreenshot-resolvescreenshotpath) 相同的数据对象。 -For example, to store diffs in a subdirectory of attachments: +例如,以下示例将差异图片存储在附件子目录中: ```ts resolveDiffPath: ({ arg, attachmentsDir, browserName, ext, root, testFileName }) => @@ -143,16 +127,16 @@ resolveDiffPath: ({ arg, attachmentsDir, browserName, ext, root, testFileName }) ## browser.expect.toMatchScreenshot.comparators -- **Type:** `Record` +- **类型:** `Record` -Register custom screenshot comparison algorithms, like [SSIM](https://en.wikipedia.org/wiki/Structural_similarity_index_measure) or other perceptual similarity metrics. +注册自定义的截图比对算法,如 [SSIM](https://en.wikipedia.org/wiki/Structural_similarity_index_measure) 或其他感知相似度指标。 -To create a custom comparator, you need to register it in your config. If using TypeScript, declare its options in the `ScreenshotComparatorRegistry` interface. +创建自定义比较器时,需在配置中注册。如果使用 TypeScript,需在 `ScreenshotComparatorRegistry` 接口中声明其选项。 ```ts import { defineConfig } from 'vitest/config' -// 1. Declare the comparator's options type +// 1. 声明比较器的选项类型 declare module 'vitest/browser' { interface ScreenshotComparatorRegistry { myCustomComparator: { @@ -162,7 +146,7 @@ declare module 'vitest/browser' { } } -// 2. Implement the comparator +// 2. 实现比较器 export default defineConfig({ test: { browser: { @@ -173,12 +157,12 @@ export default defineConfig({ reference, actual, { - createDiff, // always provided by Vitest + createDiff, // 始终由 Vitest 提供 sensitivity = 0.01, ignoreColors = false, } ) => { - // ...algorithm implementation + // 算法实现... return { pass, diff, message } }, }, @@ -189,7 +173,7 @@ export default defineConfig({ }) ``` -Then use it in your tests: +然后在测试中使用该比较器: ```ts await expect(locator).toMatchScreenshot({ @@ -201,7 +185,7 @@ await expect(locator).toMatchScreenshot({ }) ``` -**Comparator Function Signature:** +**比较器函数签名:** ```ts type Comparator = ( @@ -227,21 +211,20 @@ type Comparator = ( } ``` -The `reference` and `actual` images are decoded using the appropriate codec (currently only PNG). The `data` property is a flat `TypedArray` (`Buffer`, `Uint8Array`, or `Uint8ClampedArray`) containing pixel data in RGBA format: +`reference` 和 `actual` 图像会通过相应编解码器解码(当前仅支持 PNG)。`data` 属性是存储 RGBA 格式像素数据的扁平 `TypedArray`(`Buffer`、`Uint8Array` 或 `Uint8ClampedArray`): -- **4 bytes per pixel**: red, green, blue, alpha (from `0` to `255` each) -- **Row-major order**: pixels are stored left-to-right, top-to-bottom -- **Total length**: `width × height × 4` bytes -- **Alpha channel**: always present. Images without transparency have alpha values set to `255` (fully opaque) +- **每像素 4 字节**:红、绿、蓝、alpha(每个通道值范围 `0` 至 `255`) +- **行优先顺序**:像素按从左到右、从上到下顺序排列 +- **总长度**:`width × height × 4` 字节 +- **Alpha 通道**:始终存在。无透明度的图像其 alpha 值固定为 `255`(完全不透明) -::: tip Performance Considerations -The `createDiff` option indicates whether a diff image is needed. During [stable screenshot detection](/guide/browser/visual-regression-testing#how-visual-tests-work), Vitest calls comparators with `createDiff: false` to avoid unnecessary work. +::: tip 性能注意事项 +`createDiff` 选项表示是否需要生成差异图像。在 [稳定截图检测](/guide/browser/visual-regression-testing#how-visual-tests-work) 过程中,Vitest 会以 `createDiff: false` 调用比较器以避免不必要的计算。 -**Respect this flag to keep your tests fast**. -::: +**请遵守此标志以保持测试速度**。 -::: warning Handle Missing Options -The `options` parameter in `toMatchScreenshot()` is optional, so users might not provide all your comparator options. Always make them optional with default values: +::: warning 处理缺失参数 +`toMatchScreenshot()` 中的 `options` 参数是可选的,因此用户可能不会提供所有比较器选项。务必使用默认值使它们成为可选的: ```ts myCustomComparator: ( @@ -249,7 +232,7 @@ myCustomComparator: ( actual, { createDiff, threshold = 0.1, maxDiff = 100 }, ) => { - // ...comparison logic + // 对比逻辑... } ``` ::: diff --git a/config/browser/headless.md b/config/browser/headless.md index f0bd1614..74fbcd29 100644 --- a/config/browser/headless.md +++ b/config/browser/headless.md @@ -1,12 +1,12 @@ --- -title: browser.headless | Config +title: browser.headless | 配置 outline: deep --- # browser.headless -- **Type:** `boolean` -- **Default:** `process.env.CI` -- **CLI:** `--browser.headless`, `--browser.headless=false` +- **类型:** `boolean` +- **默认值:** `process.env.CI` +- **命令行终端:** `--browser.headless`, `--browser.headless=false` -Run the browser in a `headless` mode. If you are running Vitest in CI, it will be enabled by default. +以 `无头模式` 运行浏览器。如果在 CI 环境中执行 Vitest,该模式将默认启用。 diff --git a/config/browser/instances.md b/config/browser/instances.md index 446545ea..890432ea 100644 --- a/config/browser/instances.md +++ b/config/browser/instances.md @@ -1,19 +1,19 @@ --- -title: browser.instances | Config +title: browser.instances | 配置 outline: deep --- # browser.instances -- **Type:** `BrowserConfig` -- **Default:** `[]` +- **类型:** `BrowserConfig` +- **默认值:** `[]` -Defines multiple browser setups. Every config has to have at least a `browser` field. +定义多个浏览器配置。每个配置必须至少包含一个 `browser` 字段。 -You can specify most of the [project options](/config/) (not marked with a icon) and some of the `browser` options like `browser.testerHtmlPath`. +你可以指定大多数 [项目选项](/config/)(未标记图标的)以及部分 `browser` 选项,如 `browser.testerHtmlPath`。 ::: warning -Every browser config inherits options from the root config: +每个浏览器配置都会继承根配置的选项: ```ts{3,9} [vitest.config.ts] export default defineConfig({ @@ -24,9 +24,9 @@ export default defineConfig({ testerHtmlPath: './custom-path.html', instances: [ { - // will have both setup files: "root" and "browser" + // 将同时包含 "root" 和 "browser" 两个全局初始化文件 setupFile: ['./browser-setup-file.js'], - // implicitly has "testerHtmlPath" from the root config // [!code warning] + // 隐式继承根配置的"testerHtmlPath" // [!code warning] // testerHtmlPath: './custom-path.html', // [!code warning] }, ], @@ -35,12 +35,12 @@ export default defineConfig({ }) ``` -For more examples, refer to the ["Multiple Setups" guide](/guide/browser/multiple-setups). +更多示例请参阅 [“多环境配置” 指南](/guide/browser/multiple-setups)。 ::: -List of available `browser` options: +可用的 `browser` 选项列表: -- `browser` (the name of the browser) +- `browser` (浏览器名称) - [`headless`](/config/browser/headless) - [`locators`](/config/browser/locators) - [`viewport`](/config/browser/viewport) @@ -49,4 +49,4 @@ List of available `browser` options: - [`screenshotFailures`](/config/browser/screenshotfailures) - [`provider`](/config/browser/provider) -Under the hood, Vitest transforms these instances into separate [test projects](/api/advanced/test-project) sharing a single Vite server for better caching performance. +Vitest 在底层将这些实例转换为独立的 [测试项目](/api/advanced/test-project),共享同一个 Vite 服务器以提升缓存性能。 diff --git a/config/browser/isolate.md b/config/browser/isolate.md index 5e610cdf..471374b7 100644 --- a/config/browser/isolate.md +++ b/config/browser/isolate.md @@ -1,16 +1,16 @@ --- -title: browser.isolate | Config +title: browser.isolate | 配置 outline: deep --- # browser.isolate -- **Type:** `boolean` -- **Default:** the same as [`--isolate`](/config/isolate) -- **CLI:** `--browser.isolate`, `--browser.isolate=false` +- **类型:** `boolean` +- **默认值:** the same as [`--isolate`](/config/isolate) +- **命令行终端:** `--browser.isolate`, `--browser.isolate=false` -Run every test in a separate iframe. +在每个独立 iframe 中运行测试用例。 -::: danger DEPRECATED -This option is deprecated. Use [`isolate`](/config/isolate) instead. +::: danger 已弃用 +此选项已废弃,请改用 [`isolate`](/config/isolate) 配置项。 ::: diff --git a/config/browser/locators.md b/config/browser/locators.md index a8c05c80..0513db7e 100644 --- a/config/browser/locators.md +++ b/config/browser/locators.md @@ -1,5 +1,5 @@ --- -title: browser.locators | Config +title: browser.locators | 配置 outline: deep --- @@ -13,17 +13,17 @@ outline: deep - **默认值:** `data-testid` 用于通过 `getByTestId` 定位器查找元素的属性。 - + ## browser.locators.exact 4.1.3 {#browser-locators-exact} -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -When set to `true`, [locators](/api/browser/locators) will match text exactly by default, requiring a full, case-sensitive match. Individual locator calls can override this default via their own `exact` option. +当设置为 `true` 时,[定位器](/api/browser/locators) 默认会执行精确文本匹配,要求完全且区分大小写的匹配。单个定位器调用可通过自身的 `exact` 选项覆盖此默认行为。 ```ts -// With exact: false (default), this matches "Hello, World!", "Say Hello, World", etc. -// With exact: true, this only matches the string "Hello, World" exactly. +// 当 exact: false(默认值)时,会匹配 "Hello, World!"、"Say Hello, World" 等文本 +// 当 exact: true 时,仅精确匹配字符串 "Hello, World" const locator = page.getByText('Hello, World', { exact: true }) await locator.click() ``` diff --git a/config/browser/orchestratorscripts.md b/config/browser/orchestratorscripts.md index 7a430429..e91ba733 100644 --- a/config/browser/orchestratorscripts.md +++ b/config/browser/orchestratorscripts.md @@ -1,42 +1,42 @@ --- -title: browser.orchestratorScripts | Config +title: browser.orchestratorScripts | 配置 outline: deep --- # browser.orchestratorScripts -- **Type:** `BrowserScript[]` -- **Default:** `[]` +- **类型:** `BrowserScript[]` +- **默认值:** `[]` -Custom scripts that should be injected into the orchestrator HTML before test iframes are initiated. This HTML document only sets up iframes and doesn't actually import your code. +在测试 iframe 初始化前,需注入到编排器 HTML 中的自定义脚本。该 HTML 文档仅用于设置 iframe 框架,并不实际导入你的代码。 -The script `src` and `content` will be processed by Vite plugins. Script should be provided in the following shape: +脚本的 `src` 路径和 `content` 内容会经过 Vite 插件处理。脚本需符合以下接口规范: ```ts export interface BrowserScript { /** - * If "content" is provided and type is "module", this will be its identifier. + * 当提供 "content" 且类型为 "module" 时,将作为其标识符 * - * If you are using TypeScript, you can add `.ts` extension here for example. + * 如果使用 TypeScript,可在此处添加 `.ts` 扩展名 * @default `injected-${index}.js` */ id?: string /** - * JavaScript content to be injected. This string is processed by Vite plugins if type is "module". + * 待注入的 JavaScript 内容。当类型为 "module" 时,该字符串会经过 Vite 插件处理 * - * You can use `id` to give Vite a hint about the file extension. + * 可通过 `id` 为 Vite 提供文件扩展名提示 */ content?: string /** - * Path to the script. This value is resolved by Vite so it can be a node module or a file path. + *脚本路径。该值由 Vite 进行解析,因此可以是 node 模块或文件路径 */ src?: string /** - * If the script should be loaded asynchronously. + * 是否异步加载脚本 */ async?: boolean /** - * Script type. + * 脚本类型 * @default 'module' */ type?: string diff --git a/config/browser/playwright.md b/config/browser/playwright.md index e8bd19f2..8de45262 100644 --- a/config/browser/playwright.md +++ b/config/browser/playwright.md @@ -67,10 +67,10 @@ Vitest 将忽略 `launch.headless` 选项。请改用 [`test.browser.headless`]( 请注意,如果启用了 [`--inspect`](/guide/cli#inspect),Vitest 会将调试标志推送到 `launch.args`。 ::: -::: tip Enabling new Chromium headless mode -Playwright supports a [new headless mode](https://playwright.dev/docs/browsers#chromium-new-headless-mode) for Chromium that uses the real Chrome browser instead of the dedicated headless shell. This provides more authentic, reliable test execution and removes the need to install a separate headless Chromium build. +::: tip 启用新版 Chromium 无头模式 +Playwright 支持 Chromium 的 [新版无头模式](https://playwright.dev/docs/browsers#chromium-new-headless-mode),该模式使用真实的 Chrome 浏览器而非专用的无头 shell。这能提供更真实可靠的测试执行,且无需安装单独的无头 Chromium 构建版本。 -To opt in, set `channel` to `'chromium'` in `launchOptions`: +启用方式:在 `launchOptions` 中设置 `channel` 为 `'chromium'`: ```ts [vitest.config.ts] import { playwright } from '@vitest/browser-playwright' @@ -95,19 +95,19 @@ export default defineConfig({ ## connectOptions 这些选项直接传递给 `playwright[browser].connect` 命令。你可以在 [Playwright 文档](https://playwright.dev/docs/api/class-browsertype#browser-type-connect) 中了解更多关于该命令和可用参数的信息。 - -Use `connectOptions.wsEndpoint` to connect to an existing Playwright server instead of launching browsers locally. This is useful for running browsers in Docker, in CI, or on a remote machine. + +通过 `connectOptions.wsEndpoint` 可连接现有 Playwright 服务器,而无需在本地启动浏览器。此功能适用于在 Docker、CI 或远程机器中运行浏览器场景。 ::: warning -Vitest forwards `launchOptions` to Playwright server via the `x-playwright-launch-options` header. This works only if the remote Playwright server supports this header, for example when using the `playwright run-server` CLI. +Vitest 会通过 `x-playwright-launch-options` 请求头将 `launchOptions` 转发至 Playwright 服务器。仅当远程 Playwright 服务器支持该请求头时此功能才生效,例如使用 `playwright run-server` CLI 时。 ::: -::: details Example: Running a Playwright Server in Docker -To run browsers in a Docker container (see [Playwright Docker guide](https://playwright.dev/docs/docker#remote-connection)): +::: details 示例:在 Docker 中运行 Playwright 服务器 +要在 Docker 容器中运行浏览器(参见 [Playwright Docker 指南](https://playwright.dev/docs/docker#remote-connection)): -Start a Playwright server using Docker Compose: +使用 Docker Compose 启动 Playwright 服务器: ```yaml [docker-compose.yml] services: @@ -125,7 +125,7 @@ services: docker compose up -d ``` -Then configure Vitest to connect to it. The [`exposeNetwork`](https://playwright.dev/docs/api/class-browsertype#browser-type-connect-option-expose-network) option lets the containerized browser reach Vitest's dev server on the host: +然后配置 Vitest 连接到该服务器。[`exposeNetwork`](https://playwright.dev/docs/api/class-browsertype#browser-type-connect-option-expose-network) 选项允许容器化浏览器访问主机上的 Vitest 开发服务器: ```ts [vitest.config.ts] import { playwright } from '@vitest/browser-playwright' @@ -181,21 +181,19 @@ await userEvent.click(page.getByRole('button'), { }) ``` - - ## `persistentContext` 4.1.0 {#persistentcontext} -- **Type:** `boolean | string` -- **Default:** `false` +- **类型:** `boolean | string` +- **默认值:** `false` -When enabled, Vitest uses Playwright's [persistent context](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context) instead of a regular browser context. This allows browser state (cookies, localStorage, DevTools settings, etc.) to persist between test runs. +启用后,Vitest 将使用 Playwright 的 [持久化上下文](https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context) 替代常规浏览器上下文。这使得浏览器状态(如 cookies、localStorage、DevTools 设置等)能在测试运行间保留。 ::: warning -This option is ignored when running tests in parallel (e.g. when headless with [`fileParallelism`](/config/fileparallelism) enabled) since persistent context cannot be shared across parallel sessions. +该选项在并行运行测试时会被忽略(例如启用 [`fileParallelism`](/config/fileparallelism) 的无头模式场景),因为持久化上下文无法跨并行会话共享。 ::: -- When set to `true`, the user data is stored in `./node_modules/.cache/vitest-playwright-user-data` -- When set to a string, the value is used as the path to the user data directory +- 设为 `true` 时,用户数据存储在 `./node_modules/.cache/vitest-playwright-user-data` +- 设为字符串时,该值将作为用户数据目录路径 ```ts [vitest.config.js] import { playwright } from '@vitest/browser-playwright' @@ -206,7 +204,7 @@ export default defineConfig({ browser: { provider: playwright({ persistentContext: true, - // or specify a custom directory: + // 或指定自定义目录: // persistentContext: './my-browser-data', }), instances: [{ browser: 'chromium' }], diff --git a/config/browser/provider.md b/config/browser/provider.md index c5995fbf..06f9c0f7 100644 --- a/config/browser/provider.md +++ b/config/browser/provider.md @@ -1,13 +1,13 @@ --- -title: browser.provider | Config +title: browser.provider | 配置 outline: deep --- # browser.provider {#browser-provider} -- **Type:** `BrowserProviderOption` +- **类型:** `BrowserProviderOption` -The return value of the provider factory. You can import the factory from `@vitest/browser-` or make your own provider: +provider 工厂的返回值。你急可以从 `@vitest/browser-` 导入工厂函数,或创建自定义 provider: ```ts{8-10} import { playwright } from '@vitest/browser-playwright' @@ -25,7 +25,7 @@ export default defineConfig({ }) ``` -To configure how provider initializes the browser, you can pass down options to the factory function: +要配置 provider 如何初始化浏览器,你可以将选项传递给工厂函数: ```ts{7-13,20-26} import { playwright } from '@vitest/browser-playwright' @@ -33,7 +33,7 @@ import { playwright } from '@vitest/browser-playwright' export default defineConfig({ test: { browser: { - // shared provider options between all instances + // 所有实例共享的 provider 配置项 provider: playwright({ launchOptions: { slowMo: 50, @@ -45,8 +45,8 @@ export default defineConfig({ { browser: 'chromium' }, { browser: 'firefox', - // overriding options only for a single instance - // this will NOT merge options with the parent one + // 仅针对单个实例的覆盖配置 + // 不会与父级配置项合并 provider: playwright({ launchOptions: { firefoxUserPrefs: { @@ -61,10 +61,10 @@ export default defineConfig({ }) ``` -## Custom Provider advanced +## 自定义 Provider advanced {#custom-provider} -::: danger ADVANCED API -The custom provider API is highly experimental and can change between patches. If you just need to run tests in a browser, use the [`browser.instances`](/config/browser/instances) option instead. +::: danger 高级 API +自定义 provider API 处于高度实验阶段,可能会在小版本之间发生变化。如果你只需要在浏览器中运行测试,请使用 [`browser.instances`](/config/browser/instances) 选项替代。 ::: ```ts @@ -73,7 +73,7 @@ export interface BrowserProvider { mocker?: BrowserModuleMocker readonly initScripts?: string[] /** - * @experimental opt-in into file parallelisation + * @experimental 启用文件级并行化 */ supportsParallelism: boolean getCommandsContext: (sessionId: string) => Record diff --git a/config/browser/screenshotdirectory.md b/config/browser/screenshotdirectory.md index 879e724d..c70fb9c2 100644 --- a/config/browser/screenshotdirectory.md +++ b/config/browser/screenshotdirectory.md @@ -1,5 +1,5 @@ --- -title: browser.screenshotDirectory | Config +title: browser.screenshotDirectory | 配置 outline: deep --- diff --git a/config/browser/screenshotfailures.md b/config/browser/screenshotfailures.md index 4c787c5c..698ace1c 100644 --- a/config/browser/screenshotfailures.md +++ b/config/browser/screenshotfailures.md @@ -1,11 +1,11 @@ --- -title: browser.screenshotFailures | Config +title: browser.screenshotFailures | 配置 outline: deep --- # browser.screenshotFailures -- **Type:** `boolean` -- **Default:** `!browser.ui` +- **类型:** `boolean` +- **默认值:** `!browser.ui` -Should Vitest take screenshots if the test fails. +是否在测试失败时自动截屏。 diff --git a/config/browser/testerhtmlpath.md b/config/browser/testerhtmlpath.md index 7042e204..0e88fe42 100644 --- a/config/browser/testerhtmlpath.md +++ b/config/browser/testerhtmlpath.md @@ -1,10 +1,10 @@ --- -title: browser.testerHtmlPath | Config +title: browser.testerHtmlPath | 配置 outline: deep --- # browser.testerHtmlPath -- **Type:** `string` +- **类型:** `string` -A path to the HTML entry point. Can be relative to the root of the project. This file will be processed with [`transformIndexHtml`](https://vite.dev/guide/api-plugin#transformindexhtml) hook. +指定相对于项目根目录 HTML 入口文件的路径。该文件将通过 [`transformIndexHtml`](https://cn.vite.dev/guide/api-plugin#transformindexhtml) 钩子进行处理。 diff --git a/config/browser/trace.md b/config/browser/trace.md index 51b62eba..61e9efb7 100644 --- a/config/browser/trace.md +++ b/config/browser/trace.md @@ -1,48 +1,48 @@ --- -title: browser.trace | Config +title: browser.trace | 配置 outline: deep --- # browser.trace -- **Type:** `'on' | 'off' | 'on-first-retry' | 'on-all-retries' | 'retain-on-failure' | object` -- **CLI:** `--browser.trace=on`, `--browser.trace=retain-on-failure` -- **Default:** `'off'` +- **类型:** `'on' | 'off' | 'on-first-retry' | 'on-all-retries' | 'retain-on-failure' | object` +- **命令行终端:** `--browser.trace=on`, `--browser.trace=retain-on-failure` +- **默认值:** `'off'` -Capture a trace of your browser test runs. You can preview traces with [Playwright Trace Viewer](https://trace.playwright.dev/). +捕获浏览器测试运行的追踪记录。你可以通过 [Playwright Trace Viewer](https://trace.playwright.dev/) 预览追踪文件。 -This options supports the following values: +该选项支持以下取值: -- `'on'` - capture trace for all tests. (not recommended as it's performance heavy) -- `'off'` - do not capture traces. -- `'on-first-retry'` - capture trace only when retrying the test for the first time. -- `'on-all-retries'` - capture trace on every retry of the test. -- `'retain-on-failure'` - capture trace only for tests that fail. This will automatically delete traces for tests that pass. -- `object` - an object with the following shape: +- `'on'` - 为所有测试捕获追踪记录(不推荐,因性能消耗较大) +- `'off'` - 不捕获追踪记录 +- `'on-first-retry'` - 仅在首次重试测试时捕获追踪记录 +- `'on-all-retries'` - 在每次测试重试时都捕获追踪记录 +- `'retain-on-failure'` - 仅捕获失败测试的追踪记录,并自动删除通过测试的追踪文件 +- `object` - 符合以下接口规范的对象: ```ts interface TraceOptions { mode: 'on' | 'off' | 'on-first-retry' | 'on-all-retries' | 'retain-on-failure' /** - * The directory where all traces will be stored. By default, Vitest - * stores all traces in `__traces__` folder close to the test file. + * 所有追踪记录的存储目录。默认情况下, + * Vitest 会将所有追踪记录保存在测试文件附近的 `__traces__` 文件夹中 */ tracesDir?: string /** - * Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview. + * 是否在追踪过程中捕获屏幕截图。截图将用于构建时间轴预览 * @default true */ screenshots?: boolean /** - * If this option is true tracing will - * - capture DOM snapshot on every action - * - record network activity + * 如果启用此选项,追踪过程将: + * - 捕获每个操作时 DOM 快照 + * - 记录网络活动 * @default true */ snapshots?: boolean } ``` -::: danger WARNING -This option is supported only by the [**playwright**](/config/browser/playwright) provider. +::: danger 警告 +此选项仅支持使用 [**playwright**](/config/browser/playwright) 驱动。 ::: diff --git a/config/browser/trackunhandlederrors.md b/config/browser/trackunhandlederrors.md index 8b25e109..0da88465 100644 --- a/config/browser/trackunhandlederrors.md +++ b/config/browser/trackunhandlederrors.md @@ -1,15 +1,15 @@ --- -title: browser.trackUnhandledErrors | Config +title: browser.trackUnhandledErrors | 配置 outline: deep --- # browser.trackUnhandledErrors -- **Type:** `boolean` -- **Default:** `true` +- **类型:** `boolean` +- **默认值:** `true` -Enables tracking uncaught errors and exceptions so they can be reported by Vitest. +启用未捕获错误和异常的追踪功能,以便 Vitest 能够报告这些错误。 -If you need to hide certain errors, it is recommended to use [`onUnhandledError`](/config/onunhandlederror) option instead. +如果需隐藏特定错误,建议改用 [`onUnhandledError`](/config/onunhandlederror) 配置项。 -Disabling this will completely remove all Vitest error handlers, which can help debugging with the "Pause on exceptions" checkbox turned on. +禁用此功能将完全移除所有 Vitest 错误处理器,有助于在调试选项开 “异常时暂停” 时进行问题排查。 diff --git a/config/browser/ui.md b/config/browser/ui.md index 4b437c96..af1fc3d7 100644 --- a/config/browser/ui.md +++ b/config/browser/ui.md @@ -1,12 +1,12 @@ --- -title: browser.ui | Config +title: browser.ui | 配置 outline: deep --- # browser.ui -- **Type:** `boolean` -- **Default:** `!isCI` -- **CLI:** `--browser.ui=false` +- **类型:** `boolean` +- **默认值:** `!isCI` +- **命令行终端:** `--browser.ui=false` -Should Vitest UI be injected into the page. By default, injects UI iframe during development. +是否注入 UI 模式界面。默认情况下,在开发阶段会注入 UI iframe。 diff --git a/config/browser/viewport.md b/config/browser/viewport.md index 98f6a93e..e0cd3a11 100644 --- a/config/browser/viewport.md +++ b/config/browser/viewport.md @@ -1,5 +1,5 @@ --- -title: browser.viewport | Config +title: browser.viewport | 配置 outline: deep --- diff --git a/config/cache.md b/config/cache.md index a480f628..8eddc27f 100644 --- a/config/cache.md +++ b/config/cache.md @@ -1,16 +1,16 @@ --- -title: cache | Config +title: cache | 配置 outline: deep --- # cache -- **Type**: `false` -- **CLI**: `--no-cache`, `--cache=false` +- **类型:** `false` +- **命令行终端:** `--no-cache`, `--cache=false` -Use this option if you want to disable the cache feature. At the moment Vitest stores cache for test results to run the longer and failed tests first. +使用此选项可禁用缓存功能。当前 Vitest 会缓存测试结果,以便优先运行耗时较长和失败的测试。 -The cache directory is controlled by the Vite's [`cacheDir`](https://vitejs.dev/config/shared-options.html#cachedir) option: +缓存目录由 Vite 的 [`cacheDir`](https://vitejs.dev/config/shared-options.html#cachedir) 选项控制: ```ts import { defineConfig } from 'vitest/config' @@ -20,7 +20,7 @@ export default defineConfig({ }) ``` -You can limit the directory only for Vitest by using `process.env.VITEST`: +可通过 `process.env.VITEST` 将目录限制为仅 Vitest 使用: ```ts import { defineConfig } from 'vitest/config' diff --git a/config/chaiconfig.md b/config/chaiconfig.md index 24cf085a..f6edf81a 100644 --- a/config/chaiconfig.md +++ b/config/chaiconfig.md @@ -1,34 +1,34 @@ --- -title: chaiConfig | Config +title: chaiConfig | 配置 outline: deep --- # chaiConfig -- **Type:** `{ includeStack?, showDiff?, truncateThreshold? }` -- **Default:** `{ includeStack: false, showDiff: true, truncateThreshold: 40 }` +- **类型:** `{ includeStack?, showDiff?, truncateThreshold? }` +- **默认值:** `{ includeStack: false, showDiff: true, truncateThreshold: 40 }` -Equivalent to [Chai config](https://github.com/chaijs/chai/blob/4.x.x/lib/chai/config.js). +等同于 [Chai 配置](https://github.com/chaijs/chai/blob/4.x.x/lib/chai/config.js)。 ## chaiConfig.includeStack -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Influences whether stack trace is included in Assertion error message. Default of false suppresses stack trace in the error message. +控制断言错误信息中是否包含堆栈跟踪。默认值 false 将抑制错误信息中的堆栈跟踪显示。 ## chaiConfig.showDiff -- **Type:** `boolean` -- **Default:** `true` +- **类型:** `boolean` +- **默认值:** `true` -Influences whether or not the `showDiff` flag should be included in the thrown AssertionErrors. `false` will always be `false`; `true` will be true when the assertion has requested a diff to be shown. +控制是否在抛出的 AssertionError 中包含 `showDiff` 标志。设为 `false` 将始终禁用差异显示;设为 `true` 则当断言请求显示差异时才会启用。 ## chaiConfig.truncateThreshold -- **Type:** `number` -- **Default:** `40` +- **类型:** `number` +- **默认值:** `40` -Sets length threshold for actual and expected values in assertion errors. If this threshold is exceeded, for example for large data structures, the value is replaced with something like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. Set it to `0` if you want to disable truncating altogether. +设置断言错误中实际值与期望值的长度阈值。当超过该阈值时(例如处理大型数据结构),值将被截断显示为类似 `[ Array(3) ]` 或 `{ Object (prop1, prop2) }` 的形式。若需完全禁用截断功能,请将该值设为 `0`。 -This config option affects truncating values in `test.each` titles and inside the assertion error message. +此配置项会影响 `test.each` 标题及断言错误信息内部值的截断显示。 diff --git a/config/clearmocks.md b/config/clearmocks.md index c2bde0b8..1e381e38 100644 --- a/config/clearmocks.md +++ b/config/clearmocks.md @@ -1,16 +1,16 @@ --- -title: clearMocks | Config +title: clearMocks | 配置 outline: deep --- # clearMocks -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Should Vitest automatically call [`vi.clearAllMocks()`](/api/vi#vi-clearallmocks) before each test. +是否应在每个测试前自动调用 [`vi.clearAllMocks()`](/api/vi#vi-clearallmocks)。 -This will clear mock history without affecting mock implementations. +此操作会清空 mock 调用记录,但不会影响 mock 的实现逻辑。 ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -23,5 +23,5 @@ export default defineConfig({ ``` ::: warning -Be aware that this option may cause problems with async [concurrent tests](/api/test#test-concurrent). If enabled, the completion of one test will clear the mock history for all mocks, including those currently being used by other tests in progress. +需要注意的是此选项可能会影响异步 [并发测试](/api/test#test-concurrent) 的正常运行。启用后,当某个测试执行完成时,会清除所有模拟函数的调用历史记录,包括其他并发测试正在使用的模拟函数。 ::: diff --git a/config/coverage.md b/config/coverage.md index 79b546b0..a2714553 100644 --- a/config/coverage.md +++ b/config/coverage.md @@ -1,108 +1,108 @@ --- -title: coverage | Config +title: coverage | 配置 outline: deep --- - + # coverage {#coverage} -You can use [`v8`](/guide/coverage.html#v8-provider), [`istanbul`](/guide/coverage.html#istanbul-provider) or [a custom coverage solution](/guide/coverage#custom-coverage-provider) for coverage collection. +你可以选择 [`v8`](/guide/coverage.html#v8-provider)、[`istanbul`](/guide/coverage.html#istanbul-provider) 或 [自定义代码覆盖率工具](/guide/coverage#custom-coverage-provider) 来进行代码覆盖率统计。 -You can provide coverage options to CLI with dot notation: +你可以通过点符号向 CLI 提供覆盖率选项: ```sh npx vitest --coverage.enabled --coverage.provider=istanbul ``` ::: warning -If you are using coverage options with dot notation, don't forget to specify `--coverage.enabled`. Do not provide a single `--coverage` option in that case. +如果你使用点符号配置覆盖率选项,别忘了指定 `--coverage.enabled`。在这种情况下,不要只提供单个 `--coverage` 选项。 ::: ## coverage.provider -- **Type:** `'v8' | 'istanbul' | 'custom'` -- **Default:** `'v8'` -- **CLI:** `--coverage.provider=` +- **类型:** `'v8' | 'istanbul' | 'custom'` +- **默认值:** `'v8'` +- **命令行终端:** `--coverage.provider=` -Use `provider` to select the tool for coverage collection. +使用 `provider` 选择收集测试覆盖率的工具。 ## coverage.enabled -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.enabled`, `--coverage.enabled=false` +- **类型:** `boolean` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.enabled`, `--coverage.enabled=false` -Enables coverage collection. Can be overridden using `--coverage` CLI option. +是否启用收集测试覆盖率。可以使用 `--coverage` 覆盖 CLI 选项。 ## coverage.include -- **Type:** `string[]` -- **Default:** Files that were imported during test run -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.include=`, `--coverage.include= --coverage.include=` +- **类型:** `string[]` +- **默认值:** 在执行测试过程中所引入的文件 +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.include=`, `--coverage.include= --coverage.include=` -List of files included in coverage as glob patterns. By default only files covered by tests are included. +以 glob 模式指定需要统计覆盖率的文件列表。默认情况下,仅包含被测试覆盖的文件。 -It is recommended to pass file extensions in the pattern. +建议在匹配规则中传递文件扩展名。 -See [Including and excluding files from coverage report](/guide/coverage.html#including-and-excluding-files-from-coverage-report) for examples. +更多示例请参阅 [在覆盖率报告中包含和排除文件](/guide/coverage.html#including-and-excluding-files-from-coverage-report) ## coverage.exclude -- **Type:** `string[]` -- **Default:** : `[]` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.exclude=`, `--coverage.exclude= --coverage.exclude=` +- **类型:** `string[]` +- **默认值:** : `[]` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.exclude=`, `--coverage.exclude= --coverage.exclude=` -List of files excluded from coverage as glob patterns. +以 glob 模式指定从代码覆盖率中排除的文件列表。 -See [Including and excluding files from coverage report](/guide/coverage.html#including-and-excluding-files-from-coverage-report) for examples. +更多示例请参阅 [在覆盖率报告中包含和排除文件](/guide/coverage.html#including-and-excluding-files-from-coverage-report)。 ## coverage.clean -- **Type:** `boolean` -- **Default:** `true` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.clean`, `--coverage.clean=false` +- **类型:** `boolean` +- **默认值:** `true` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.clean`, `--coverage.clean=false` -Clean coverage results before running tests +运行测试前清除代码覆盖率结果。 ## coverage.cleanOnRerun -- **Type:** `boolean` -- **Default:** `true` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.cleanOnRerun`, `--coverage.cleanOnRerun=false` +- **类型:** `boolean` +- **默认值:** `true` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.cleanOnRerun`, `--coverage.cleanOnRerun=false` -Clean coverage report on watch rerun. Set to `false` to preserve coverage results from previous run in watch mode. +在 watch 模式重新运行时清除代码覆盖率报告。设为 `false` 可在 watch 模式下保留上一次运行的代码覆盖率结果。 ## coverage.reportsDirectory -- **Type:** `string` -- **Default:** `'./coverage'` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.reportsDirectory=` +- **类型:** `string` +- **默认值:** `'./coverage'` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.reportsDirectory=` ::: warning -Vitest will delete this directory before running tests if `coverage.clean` is enabled (default value). +如果启用了(默认值) `coverage.clean`,Vitest 会在运行测试前删除此目录。 ::: -Directory to write coverage report to. +用于写入代码覆盖率报告的目录。 ## coverage.reporter -- **Type:** `string | string[] | [string, {}][]` -- **Default:** `['text', 'html', 'clover', 'json']` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.reporter=`, `--coverage.reporter= --coverage.reporter=` +- **类型:** `string | string[] | [string, {}][]` +- **默认值:** `['text', 'html', 'clover', 'json']` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.reporter=`, `--coverage.reporter= --coverage.reporter=` -Coverage reporters to use. See [istanbul documentation](https://istanbul.js.org/docs/advanced/alternative-reporters/) for detailed list of all reporters. See [`@types/istanbul-reports`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/276d95e4304b3670eaf6e8e5a7ea9e265a14e338/types/istanbul-reports/index.d.ts) for details about reporter specific options. +要使用的代码覆盖率报告器。所有报告器的详细列表请参阅 [istanbul 文档](https://istanbul.js.org/docs/advanced/alternative-reporters/)。关于报告器特定选项的详细信息请参阅 [`@types/istanbul-reports`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/276d95e4304b3670eaf6e8e5a7ea9e265a14e338/types/istanbul-reports/index.d.ts)。 -The reporter has three different types: +报告器有三种不同的类型: -- A single reporter: `{ reporter: 'html' }` -- Multiple reporters without options: `{ reporter: ['html', 'json'] }` -- A single or multiple reporters with reporter options: +- 单个报告器:`{ reporter: 'html' }` +- 不带选项的多个报告器:`{ reporter: ['html', 'json'] }` +- 带有报告器选项的单个或多个报告器: ```ts { @@ -114,81 +114,81 @@ The reporter has three different types: } ``` -You can also pass custom coverage reporters. See [Guide - Custom Coverage Reporter](/guide/coverage#custom-coverage-reporter) for more information. +你也可以传递自定义代码覆盖率报告器。更多信息请参阅 [指南 | 自定义代码覆盖率报告器](/guide/coverage#custom-coverage-reporter)。 ```ts { reporter: [ - // Specify reporter using name of the NPM package + // 使用 NPM 包名指定报告器 '@vitest/custom-coverage-reporter', ['@vitest/custom-coverage-reporter', { someOption: true }], - // Specify reporter using local path + // 使用本地路径指定报告器 '/absolute/path/to/custom-reporter.cjs', ['/absolute/path/to/custom-reporter.cjs', { someOption: true }], ] } ``` -You can check your coverage report in Vitest UI: check [Vitest UI Coverage](/guide/coverage#vitest-ui) for more details. +你可以在 Vitest UI 模式中查看代码覆盖率报告。更多详情请参阅 [Vitest UI Coverage](/guide/coverage#vitest-ui)。 ## coverage.reportOnFailure {#coverage-reportonfailure} -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.reportOnFailure`, `--coverage.reportOnFailure=false` +- **类型:** `boolean` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.reportOnFailure`, `--coverage.reportOnFailure=false` -Generate coverage report even when tests fail. +即使测试失败也生成代码覆盖率报告。 ## coverage.allowExternal -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.allowExternal`, `--coverage.allowExternal=false` +- **类型:** `boolean` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.allowExternal`, `--coverage.allowExternal=false` -Collect coverage of files outside the [project `root`](/config/root). +收集 [项目根路径](/config/root) 以外文件的代码覆盖率。 ## coverage.excludeAfterRemap -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.excludeAfterRemap`, `--coverage.excludeAfterRemap=false` +- **类型:** `boolean` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.excludeAfterRemap`, `--coverage.excludeAfterRemap=false` -Apply exclusions again after coverage has been remapped to original sources. -This is useful when your source files are transpiled and may contain source maps of non-source files. +在覆盖率数据已重新映射回原始源代码后,再次应用排除规则。 +适用于源文件经过转译且可能包含非源文件的 source map 的情况。 -Use this option when you are seeing files that show up in report even if they match your `coverage.exclude` patterns. +当发现某些文件即使匹配了 `coverage.exclude` 模式仍出现在报告中时,请使用此选项。 ## coverage.skipFull -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.skipFull`, `--coverage.skipFull=false` +- **类型:** `boolean` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.skipFull`, `--coverage.skipFull=false` -Do not show files with 100% statement, branch, and function coverage. +是否显示语句、分支和函数覆盖率达到 100% 的文件。 ## coverage.thresholds -Options for coverage thresholds. +覆盖率阈值选项。 -If a threshold is set to a positive number, it will be interpreted as the minimum percentage of coverage required. For example, setting the lines threshold to `90` means that 90% of lines must be covered. +如果阈值设置为正数,将被解释为要求的最低代码覆盖率百分比。例如,将行阈值设置为 `90` 意味着必须覆盖 90% 的行。 -If a threshold is set to a negative number, it will be treated as the maximum number of uncovered items allowed. For example, setting the lines threshold to `-10` means that no more than 10 lines may be uncovered. +如果阈值设置为负数,将被视为允许的最大未覆盖项目数。例如,将行阈值设置为 `-10` 意味着未覆盖的行数不得超过 10 行。 ```ts { coverage: { thresholds: { - // Requires 90% function coverage + // 要求函数覆盖率达到 90% functions: 90, - // Require that no more than 10 lines are uncovered + // 要求未覆盖代码行数不超过 10 行 lines: -10, } } @@ -197,63 +197,63 @@ If a threshold is set to a negative number, it will be treated as the maximum nu ### coverage.thresholds.lines -- **Type:** `number` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.lines=` +- **类型:** `number` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.thresholds.lines=` -Global threshold for lines. +行数(lines)全局阈值。 ### coverage.thresholds.functions -- **Type:** `number` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.functions=` +- **类型:** `number` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.thresholds.functions=` -Global threshold for functions. +函数(functions)全局阈值。 ### coverage.thresholds.branches -- **Type:** `number` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.branches=` +- **类型:** `number` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.thresholds.branches=` -Global threshold for branches. +分支(branches)全局阈值。 ### coverage.thresholds.statements -- **Type:** `number` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.statements=` +- **类型:** `number` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.thresholds.statements=` -Global threshold for statements. +语句(statements)全局阈值。 ### coverage.thresholds.perFile -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.perFile`, `--coverage.thresholds.perFile=false` +- **类型:** `boolean` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.thresholds.perFile`, `--coverage.thresholds.perFile=false` -Check thresholds per file. +按文件检查覆盖率阈值。 ### coverage.thresholds.autoUpdate -- **Type:** `boolean | function` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.autoUpdate=` +- **类型:** `boolean | function` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.thresholds.autoUpdate=` -Update all threshold values `lines`, `functions`, `branches` and `statements` to configuration file when current coverage is better than the configured thresholds. -This option helps to maintain thresholds when coverage is improved. +当实际覆盖率超过配置阈值时,自动将 `lines`、`functions`、`branches` 和 `statements` 的阈值更新到配置文件中。 +此选项适用于覆盖率提高时保持阈值不变。 -You can also pass a function for formatting the updated threshold values: +你也可以通过传入函数自定义阈值更新值的格式: ```ts { coverage: { thresholds: { - // Update thresholds without decimals + // 更新阈值为整数 autoUpdate: (newThreshold) => Math.floor(newThreshold), // 95.85 -> 95 @@ -265,25 +265,25 @@ You can also pass a function for formatting the updated threshold values: ### coverage.thresholds.100 -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.100`, `--coverage.thresholds.100=false` +- **类型:** `boolean` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.thresholds.100`, `--coverage.thresholds.100=false` -Sets global thresholds to 100. -Shortcut for `--coverage.thresholds.lines 100 --coverage.thresholds.functions 100 --coverage.thresholds.branches 100 --coverage.thresholds.statements 100`. +将全局阈值设置为 100。 +这是 `--coverage.thresholds.lines 100 --coverage.thresholds.functions 100 --coverage.thresholds.branches 100 --coverage.thresholds.statements 100` 的快捷方式。 ### coverage.thresholds[glob-pattern] -- **Type:** `{ statements?: number functions?: number branches?: number lines?: number }` -- **Default:** `undefined` -- **Available for providers:** `'v8' | 'istanbul'` +- **类型:** `{ statements?: number functions?: number branches?: number lines?: number }` +- **默认值:** `undefined` +- **可用的测试提供者:** `'v8' | 'istanbul'` -Sets thresholds for files matching the glob pattern. +设置与 glob 模式匹配的文件的阈值。 -::: tip NOTE -Vitest counts all files, including those covered by glob-patterns, into the global coverage thresholds. -This is different from Jest behavior. +::: tip 注意 +Vitest 会将所有文件(包括匹配 glob 模式的文件)计入全局覆盖率阈值计算。 +此做法与 Jest 不同。 ::: @@ -291,11 +291,11 @@ This is different from Jest behavior. { coverage: { thresholds: { - // Thresholds for all files + // 所有文件的阈值 functions: 95, branches: 70, - // Thresholds for matching glob pattern + // 对匹配 glob 模式的文件设置独立阈值 'src/utils/**.ts': { statements: 95, functions: 90, @@ -303,8 +303,8 @@ This is different from Jest behavior. lines: 80, }, - // Files matching this pattern will only have lines thresholds set. - // Global thresholds are not inherited. + // 匹配此模式的文件仅设置行覆盖率阈值 + // 不继承全局阈值 '**/math.ts': { lines: 100, } @@ -315,22 +315,22 @@ This is different from Jest behavior. ### coverage.thresholds[glob-pattern].100 -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` +- **类型:** `boolean` +- **默认值:** `false` +- **可用的测试提供者:** `'v8' | 'istanbul'` -Sets thresholds to 100 for files matching the glob pattern. +为匹配 glob 模式的文件设置 100% 覆盖率阈值。 ```ts { coverage: { thresholds: { - // Thresholds for all files + // 所有文件的阈值 functions: 95, branches: 70, - // Thresholds for matching glob pattern + // 全局模式匹配阈值 'src/utils/**.ts': { 100: true }, '**/math.ts': { 100: true } } @@ -340,17 +340,17 @@ Sets thresholds to 100 for files matching the glob pattern. ## coverage.ignoreClassMethods -- **Type:** `string[]` -- **Default:** `[]` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.ignoreClassMethods=` +- **类型:** `string[]` +- **默认值:** `[]` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.ignoreClassMethods=` -Set to array of class method names to ignore for coverage. -See [istanbul documentation](https://github.com/istanbuljs/nyc#ignoring-methods) for more information. +设置为要忽略覆盖率的类方法名称数组。 +更多信息请参阅 [istanbul 文档](https://github.com/istanbuljs/nyc#ignoring-methods)。 ## coverage.watermarks -- **Type:** +- **类型:** ```ts { @@ -361,7 +361,7 @@ See [istanbul documentation](https://github.com/istanbuljs/nyc#ignoring-methods) } ``` -- **Default:** +- **默认值:** ```ts { @@ -372,45 +372,45 @@ See [istanbul documentation](https://github.com/istanbuljs/nyc#ignoring-methods) } ``` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.watermarks.statements=50,80`, `--coverage.watermarks.branches=50,80` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.watermarks.statements=50,80`, `--coverage.watermarks.branches=50,80` -Watermarks for statements, lines, branches and functions. See [istanbul documentation](https://github.com/istanbuljs/nyc#high-and-low-watermarks) for more information. +语句、行、分支和函数的阈值标记。更多信息请参阅 [istanbul 文档](https://github.com/istanbuljs/nyc#high-and-low-watermarks)。 ## coverage.processingConcurrency -- **Type:** `boolean` -- **Default:** `Math.min(20, os.availableParallelism?.() ?? os.cpus().length)` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.processingConcurrency=` +- **类型:** `boolean` +- **默认值:** `Math.min(20, os.availableParallelism?.() ?? os.cpus().length)` +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.processingConcurrency=` -Concurrency limit used when processing the coverage results. +处理代码覆盖率结果时使用的并发限制。 ## coverage.customProviderModule -- **Type:** `string` -- **Available for providers:** `'custom'` -- **CLI:** `--coverage.customProviderModule=` +- **类型:** `string` +- **可用的测试提供者:** `'custom'` +- **命令行终端:** `--coverage.customProviderModule=` -Specifies the module name or path for the custom coverage provider module. See [Guide - Custom Coverage Provider](/guide/coverage#custom-coverage-provider) for more information. +指定自定义代码覆盖率驱动模块的模块名或路径。更多信息请参阅 [指南 - 自定义覆盖率提供者](/guide/coverage#custom-coverage-provider)。 ## coverage.htmlDir -- **Type:** `string` -- **Default:** Automatically inferred from `html`, `html-spa`, or `lcov` coverage reporters -- **CLI:** `--coverage.htmlDir=` +- **类型:** `string` +- **默认值:** 从 `html`、`html-spa` 或 `lcov` 代码覆盖率报告器自动推断 +- **命令行终端:** `--coverage.htmlDir=` -Directory of HTML coverage output to be served in [Vitest UI](/guide/ui) and [HTML reporter](/guide/reporters.html#html-reporter). +要在 [UI 模式](/guide/ui) 和 [HTML 报告器](/guide/reporters.html#html-reporter) 中提供的 HTML 代码覆盖率输出目录。 -This is automatically configured when using builtin coverage reporters that produce HTML output (`html`, `html-spa`, and `lcov`). Use this option to override with a custom coverage reporting location when using custom coverage reporters. +使用内置代码覆盖率报告器生成 HTML 输出(`html`、`html-spa` 和`lcov`)时会自动配置此项。使用自定义代码覆盖率报告器时,使用此选项可覆盖为自定义代码覆盖率报告位置。 -Note that setting this option does not change where coverage HTML report is generated. Configure the `coverage.reporter` option to change the directory instead. +注意,设置此选项不会更改代码覆盖率 HTML 报告的生成位置。要更改目录,请配置 `coverage.reporter` 选项。 ## coverage.changed -- **Type:** `boolean | string` -- **Default:** `false` (inherits from `test.changed`) -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.changed`, `--coverage.changed=` +- **类型:** `boolean | string` +- **默认值:** `false` (inherits from `test.changed`) +- **可用的测试提供者:** `'v8' | 'istanbul'` +- **命令行终端:** `--coverage.changed`, `--coverage.changed=` -Collect coverage only for files changed since a specified commit or branch. When set to `true`, it uses staged and unstaged changes. +仅收集自指定提交或分支以来更改的文件的代码覆盖率。设置为 `true` 时,使用已暂存和未暂存的更改。 diff --git a/config/css.md b/config/css.md index eb096d16..05806a87 100644 --- a/config/css.md +++ b/config/css.md @@ -1,52 +1,52 @@ --- -title: css | Config +title: css | 配置 outline: deep --- # css -- **Type**: `boolean | { include?, exclude?, modules? }` +- **类型:** `boolean | { include?, exclude?, modules? }` -Configure if CSS should be processed. When excluded, CSS files will be replaced with empty strings to bypass the subsequent processing. CSS Modules will return a proxy to not affect runtime. +配置是否应处理 CSS。当被排除时,CSS 文件将被替换为空字符串以绕过后续处理。CSS 模块将返回代理对象以不影响运行时。 ::: warning -This option is not applied to [browser tests](/guide/browser/). +此选项不适用于 [浏览器测试](/guide/browser/)。 ::: ## css.include -- **Type**: `RegExp | RegExp[]` -- **Default**: `[]` +- **类型:** `RegExp | RegExp[]` +- **默认值:** `[]` -RegExp pattern for files that should return actual CSS and will be processed by Vite pipeline. +使用 RegExp 模式进行匹配,指定哪些 CSS 文件应返回实际内容并通过 Vite 处理。 :::tip -To process all CSS files, use `/.+/`. +要处理所有 CSS 文件,请使用 `/.+/`。 ::: ## css.exclude -- **Type**: `RegExp | RegExp[]` -- **Default**: `[]` +- **类型:** `RegExp | RegExp[]` +- **默认值:** `[]` -RegExp pattern for files that will return an empty CSS file. +使用 RegExp 模式指定哪些 CSS 文件应返回空内容。 ## css.modules -- **Type**: `{ classNameStrategy? }` -- **Default**: `{}` +- **类型:** `{ classNameStrategy? }` +- **默认值:** `{}` ### css.modules.classNameStrategy -- **Type**: `'stable' | 'scoped' | 'non-scoped'` -- **Default**: `'stable'` +- **类型:** `'stable' | 'scoped' | 'non-scoped'` +- **默认值:** `'stable'` -If you decide to process CSS files, you can configure if class names inside CSS modules should be scoped. You can choose one of the options: +如果您决定处理 CSS 文件,可以配置 CSS modules 中的类名是否应限定作用域。您可以选择以下选项之一: -- `stable`: class names will be generated as `_${name}_${hashedFilename}`, which means that generated class will stay the same, if CSS content is changed, but will change, if the name of the file is modified, or file is moved to another folder. This setting is useful, if you use snapshot feature. -- `scoped`: class names will be generated as usual, respecting `css.modules.generateScopedName` method, if you have one and CSS processing is enabled. By default, filename will be generated as `_${name}_${hash}`, where hash includes filename and content of the file. -- `non-scoped`: class names will not be hashed. +- `stable`: 类名将生成为 `_${name}_${hashedFilename}`,这意味着如果 CSS 内容发生变化,生成的类将保持不变,但如果文件名被修改或文件移动到另一个文件夹,则会更改。适用于使用快照功能。 +- `scoped`: 类名将照常生成,如果你有 `css.modules.generateScopedName` 方法并且已启用 CSS 处理,则会尊重该方法。默认情况下,文件名将生成为 `_${name}_${hash}`,其中 hash 包含文件名和文件内容。 +- `non-scoped`: 类名将不会被哈希。 ::: warning -By default, Vitest exports a proxy, bypassing CSS Modules processing. If you rely on CSS properties on your classes, you have to enable CSS processing using `include` option. +默认情况下,Vitest 导出一个代理,绕过 CSS 模块处理。如果您依赖类上的 CSS 属性,则必须使用 `include` 选项启用 CSS 处理。 ::: diff --git a/config/dangerouslyignoreunhandlederrors.md b/config/dangerouslyignoreunhandlederrors.md index 54536f19..67cd7a5e 100644 --- a/config/dangerouslyignoreunhandlederrors.md +++ b/config/dangerouslyignoreunhandlederrors.md @@ -1,21 +1,21 @@ --- -title: dangerouslyIgnoreUnhandledErrors | Config +title: dangerouslyIgnoreUnhandledErrors | 配置 outline: deep --- # dangerouslyIgnoreUnhandledErrors -- **Type**: `boolean` -- **Default**: `false` -- **CLI:** +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** - `--dangerouslyIgnoreUnhandledErrors` - `--dangerouslyIgnoreUnhandledErrors=false` -If this option is set to `true`, Vitest will not fail the test run if there are unhandled errors. Note that built-in reporters will still report them. +如果将此选项设为 `true`,即使存在未处理错误,Vitest 也不会导致测试运行失败。注意:内置报告器仍会显示这些错误。 -If you want to filter out certain errors conditionally, use [`onUnhandledError`](/config/onunhandlederror) callback instead. +如需按条件过滤特定错误,请改用 [`onUnhandledError`](/config/onunhandlederror) 回调函数。 -## Example +## 示例 {#example} ```js [vitest.config.js] import { defineConfig } from 'vitest/config' diff --git a/config/deps.md b/config/deps.md index 579544e9..d6dc33ae 100644 --- a/config/deps.md +++ b/config/deps.md @@ -1,96 +1,97 @@ --- -title: deps | Config +title: deps | 配置 outline: deep --- # deps -- **Type:** `{ optimizer?, ... }` +- **类型:** `{ optimizer?, ... }` -Handling for dependencies resolution. +依赖项解析处理配置。 ## deps.optimizer {#deps-optimizer} -- **Type:** `{ ssr?, client? }` -- **See also:** [Dep Optimization Options](https://vitejs.dev/config/dep-optimization-options.html) +- **类型:** `{ ssr?, client? }` +- **参考:** [依赖优化选项](https://cn.vitejs.dev/config/dep-optimization-options.html) -Enable dependency optimization. If you have a lot of tests, this might improve their performance. +启用依赖优化。如果你有很多测试,这可能会提高它们的性能。 -When Vitest encounters the external library listed in `include`, it will be bundled into a single file using esbuild and imported as a whole module. This is good for several reasons: +当 Vitest 检测到 `include` 列表中指定的外部库时,会通过 esbuild 将其打包为单一文件,并作为整个模块导入。此机制具有以下优势: -- Importing packages with a lot of imports is expensive. By bundling them into one file we can save a lot of time -- Importing UI libraries is expensive because they are not meant to run inside Node.js -- Your `alias` configuration is now respected inside bundled packages -- Code in your tests is running closer to how it's running in the browser +- 导入包含大量子依赖的包时开销较大,打包为单一文件可显著节省时间 +- 导入 UI 库时开销较大,因其它们并非为 Node.js 环境设计 +- 打包后的依赖包内部现在会遵循你的 `alias` 别名配置 +- 测试代码的运行方式更接近浏览器环境的行为 -Be aware that only packages in `deps.optimizer?.[mode].include` option are bundled (some plugins populate this automatically, like Svelte). You can read more about available options in [Vite](https://vitejs.dev/config/dep-optimization-options.html) docs (Vitest doesn't support `disable` and `noDiscovery` options). By default, Vitest uses `optimizer.client` for `jsdom` and `happy-dom` environments, and `optimizer.ssr` for `node` and `edge` environments. +需注意,只有 `deps.optimizer?.[mode].include` 选项中指定的包会被打包(某些插件会自动填充此选项,例如 Svelte)。你可以在 [Vite 文档](https://cn.vitejs.dev/config/dep-optimization-options.html) 中查阅更多可用选项(Vitest 不支持 `disable` 和 `noDiscovery` 选项)。默认情况下,Vitest 对 `jsdom` 和 `happy-dom` 环境使用 `optimizer.client`,对 `node` 和 `edge` 环境使用 `optimizer.ssr`。 + +此选项还会继承你的 `optimizeDeps` 配置(对于 Web 环境,Vitest 会扩展 `optimizeDeps`;对于 SSR 环境则会扩展 `ssr.optimizeDeps`)。如果在 `deps.optimizer` 中重定义 `include`/`exclude` 选项,运行测试时将会扩展你的 `optimizeDeps` 配置。若某选项同时出现在 `include` 和 `exclude` 列表中,Vitest 会自动将其从 `include` 中移除。 -This options also inherits your `optimizeDeps` configuration (for web Vitest will extend `optimizeDeps`, for ssr - `ssr.optimizeDeps`). If you redefine `include`/`exclude` option in `deps.optimizer` it will extend your `optimizeDeps` when running tests. Vitest automatically removes the same options from `include`, if they are listed in `exclude`. ::: tip -You will not be able to edit your `node_modules` code for debugging, since the code is actually located in your `cacheDir` or `test.cache.dir` directory. If you want to debug with `console.log` statements, edit it directly or force rebundling with `deps.optimizer?.[mode].force` option. +你将无法通过编辑 `node_modules` 中的代码进行调试,因为这些代码实际位于 `cacheDir` 或 `test.cache.dir` 目录中。如需使用 `console.log` 语句进行调试,请直接修改对应文件,或通过 `deps.optimizer?.[mode].force` 选项强制重新打包。 ::: ### deps.optimizer.{mode}.enabled -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Enable dependency optimization. +启用依赖项优化。 -## deps.client {#deps-client} +## deps.client -- **Type:** `{ transformAssets?, ... }` +- **类型:** `{ transformAssets?, ... }` -Options that are applied to external files when the environment is set to `client`. By default, `jsdom` and `happy-dom` use `client` environment, while `node` and `edge` environments use `ssr`, so these options will have no affect on files inside those environments. +当环境设置为 `client` 时应用于外部文件的选项。默认情况下,`jsdom` 和 `happy-dom` 使用 `client` 环境,而 `node` 和 `edge` 环境则使用 `ssr`,因此这些选项不会影响这些环境内部的文件。 -Usually, files inside `node_modules` are externalized, but these options also affect files in [`server.deps.external`](/config/server#server-deps-external). +通常情况下 `node_modules` 中的文件会被外部化,但这些选项也会影响 [`server.deps.external`](/config/server#server-deps-external) 中指定的文件。 ### deps.client.transformAssets -- **Type:** `boolean` -- **Default:** `true` +- **类型:** `boolean` +- **默认值:** `true` -Should Vitest process assets (.png, .svg, .jpg, etc) files and resolve them like Vite does in the browser. +是否让 Vitest 像 Vite 在浏览器中那样处理资源文件(.png、.svg、.jpg 等)并解析它们。 -This module will have a default export equal to the path to the asset, if no query is specified. +若未指定查询参数,该模块将默认导出资源文件的路径。 ::: warning -At the moment, this option only works with [`vmThreads`](/config/pool#vmthreads) and [`vmForks`](/config/pool#vmforks) pools. +目前,此选项仅适用于 [`vmThreads`](/config/pool#vmthreads) 和 [`vmForks`](/config/pool#vmforks) 池。 ::: ### deps.client.transformCss -- **Type:** `boolean` -- **Default:** `true` +- **类型:** `boolean` +- **默认值:** `true` -Should Vitest process CSS (.css, .scss, .sass, etc) files and resolve them like Vite does in the browser. +是否让 Vitest 像 Vite 在浏览器中一样处理 CSS 文件(.css、.scss、.sass 等)并解析它们。 -If CSS files are disabled with [`css`](/config/css) options, this option will just silence `ERR_UNKNOWN_FILE_EXTENSION` errors. +如果通过 [`css`](/config/css) 选项禁用了 CSS 文件,此选项仅会屏蔽 `ERR_UNKNOWN_FILE_EXTENSION` 错误。 ::: warning -At the moment, this option only works with [`vmThreads`](/config/pool#vmthreads) and [`vmForks`](/config/pool#vmforks) pools. +当前此选项仅适用于 [`vmThreads`](/config/pool#vmthreads) 和 [`vmForks`](/config/pool#vmforks) 池。 ::: ### deps.client.transformGlobPattern -- **Type:** `RegExp | RegExp[]` -- **Default:** `[]` +- **类型:** `RegExp | RegExp[]` +- **默认值:** `[]` -Regexp pattern to match external files that should be transformed. +正则匹配应转换的外部文件。 -By default, files inside `node_modules` are externalized and not transformed, unless it's CSS or an asset, and corresponding option is not disabled. +默认情况下,`node_modules` 中的文件会被外部化且不进行转换,除非是 CSS 或静态资源且未禁用对应的选项。 ::: warning -At the moment, this option only works with [`vmThreads`](/config/pool#vmthreads) and [`vmForks`](/config/pool#vmforks) pools. +当前此选项仅适用于 [`vmThreads`](/config/pool#vmthreads) 和 [`vmForks`](/config/pool#vmforks) 池。 ::: ## deps.interopDefault -- **Type:** `boolean` -- **Default:** `true` +- **类型:** `boolean` +- **默认值:** `true` -Interpret CJS module's default as named exports. Some dependencies only bundle CJS modules and don't use named exports that Node.js can statically analyze when a package is imported using `import` syntax instead of `require`. When importing such dependencies in Node environment using named exports, you will see this error: +将 CJS 模块的默认值视为命名导出。某些依赖项仅捆绑 CJS 模块,不使用命名导出,Node.js 可以在使用 `import` 语法而不是 `require` 导入包时对其进行静态分析。使用命名导出在 Node 环境中导入此类依赖项时,你将看到以下错误: ``` import { read } from 'fs-jetpack'; @@ -99,25 +100,25 @@ SyntaxError: Named export 'read' not found. The requested module 'fs-jetpack' is CommonJS modules can always be imported via the default export. ``` -Vitest doesn't do static analysis, and cannot fail before your running code, so you will most likely see this error when running tests, if this feature is disabled: +Vitest 不进行静态分析,也无法在代码运行前报错,因此如果禁用此功能,你极有可能在运行测试时遇到以下错误: ``` TypeError: createAsyncThunk is not a function TypeError: default is not a function ``` -By default, Vitest assumes you are using a bundler to bypass this and will not fail, but you can disable this behaviour manually, if your code is not processed. +默认情况下,Vitest 会假定你正在使用打包工具绕过此问题,因此不会报错。但如果你的代码未经处理,可以手动禁用此行为。 ## deps.moduleDirectories -- **Type:** `string[]` -- **Default**: `['node_modules']` +- **类型:** `string[]` +- **默认值:** `['node_modules']` -A list of directories that should be treated as module directories. This config option affects the behavior of [`vi.mock`](/api/vi#vi-mock): when no factory is provided and the path of what you are mocking matches one of the `moduleDirectories` values, Vitest will try to resolve the mock by looking for a `__mocks__` folder in the [root](/config/root) of the project. +配置一个视为模块目录的目录列表。此配置选项会影响 [`vi.mock`](/api/vi#vi-mock) 的行为:当未提供工厂并且你正在模拟的路径与 `moduleDirectories` 值之一匹配时,Vitest 将尝试 通过在项目的 [root](/config/root) 中查找 `__mocks__` 文件夹来解析 mock。 -This option will also affect if a file should be treated as a module when externalizing dependencies. By default, Vitest imports external modules with native Node.js bypassing Vite transformation step. +此选项还将影响在外部化依赖项时是否应将文件视为模块。默认情况下,Vitest 绕过 Vite 转换步骤导入带有原生 Node.js 的外部模块。 -Setting this option will _override_ the default, if you wish to still search `node_modules` for packages include it along with any other options: +设置此选项将 _覆盖_ 默认值,如果你仍希望搜索 `node_modules` 包包括它连同任何其他选项: ```ts import { defineConfig } from 'vitest/config' diff --git a/config/detectasyncleaks.md b/config/detectasyncleaks.md index 4da84f9c..c99888d0 100644 --- a/config/detectasyncleaks.md +++ b/config/detectasyncleaks.md @@ -1,22 +1,22 @@ --- -title: detectAsyncLeaks | Config +title: detectAsyncLeaks | 配置 outline: deep --- - + # detectAsyncLeaks -- **Type:** `boolean` -- **CLI:** `--detectAsyncLeaks`, `--detect-async-leaks` -- **Default:** `false` +- **类型:** `boolean` +- **命令行终端:** `--detectAsyncLeaks`, `--detect-async-leaks` +- **默认值:** `false` ::: warning -Enabling this option will make your tests run much slower. Use only when debugging or developing tests. +启用此选项会显著降低测试运行速度。仅在调试或开发测试时使用。 ::: -Detect asynchronous resources leaking from the test file. -Uses [`node:async_hooks`](https://nodejs.org/api/async_hooks.html) to track creation of async resources. If a resource is not cleaned up, it will be logged after tests have finished. +检测测试文件中泄漏的异步资源。 +该功能使用 [`node:async_hooks`](https://nodejs.org/api/async_hooks.html) 来追踪异步资源的创建。如果资源未被清理,将在测试结束后记录相关日志。 -For example if your code has `setTimeout` calls that execute the callback after tests have finished, you will see following error: +例如,如果代码中存在 `setTimeout` 调用且其回调在测试结束后执行,将看到如下错误: ```sh ⎯⎯⎯⎯⎯⎯⎯⎯ Async Leaks 1 ⎯⎯⎯⎯⎯⎯⎯⎯ @@ -30,7 +30,7 @@ Timeout leaking in test/checkout-screen.test.tsx 30| ``` -To fix this, you'll need to make sure your code cleans the timeout properly: +修复此问题,需确保正确清理定时器: ```js useEffect(() => { diff --git a/config/diff.md b/config/diff.md index 710d66dd..8104285f 100644 --- a/config/diff.md +++ b/config/diff.md @@ -1,18 +1,18 @@ --- -title: diff | Config +title: diff | 配置 outline: deep --- # diff -- **Type:** `string` -- **CLI:** `--diff=` +- **类型:** `string` +- **命令行终端:** `--diff=` -`DiffOptions` object or a path to a module which exports `DiffOptions`. Useful if you want to customize diff display. +`DiffOptions` 对象或导出 `DiffOptions` 的模块路径。适用于想要自定义差异显示的场景。 -Vitest diff rendering uses [`@vitest/pretty-format`](https://npmx.dev/package/@vitest/pretty-format) under the hood and a part of `DiffOptions` is forwarded to the pretty-format configuration, while the rest affects diff rendering itself. +Vitest 差异渲染底层使用 [`@vitest/pretty-format`](https://npmx.dev/package/@vitest/pretty-format),其中部分 `DiffOptions` 会透传给 pretty-format 配置,其余参数则直接影响差异渲染行为。 -For example, as a config object: +例如,作为配置对象: ```ts import { defineConfig } from 'vitest/config' @@ -29,7 +29,7 @@ export default defineConfig({ }) ``` -Or as a module: +或者作为模块: :::code-group ```ts [vitest.config.js] @@ -56,46 +56,45 @@ export default { ## diff.expand -- **Type**: `boolean` -- **Default**: `true` -- **CLI:** `--diff.expand=false` +- **类型:** `boolean` +- **默认值:** `true` +- **命令行终端:** `--diff.expand=false` -Expand all common lines. +展开所有公共行。 ## diff.truncateThreshold -- **Type**: `number` -- **Default**: `0` -- **CLI:** `--diff.truncateThreshold=` +- **类型:** `number` +- **默认值:** `0` +- **命令行终端:** `--diff.truncateThreshold=` -The maximum length of diff result to be displayed. Diffs above this threshold will be truncated. -Truncation won't take effect with default value 0. +差异结果的最大显示长度。超过此阈值的差异将被截断。默认值 0 表示不截断。 ## diff.truncateAnnotation -- **Type**: `string` -- **Default**: `'... Diff result is truncated'` -- **CLI:** `--diff.truncateAnnotation=` +- **类型:** `string` +- **默认值:** `'... Diff result is truncated'` +- **命令行终端:** `--diff.truncateAnnotation=` -Annotation that is output at the end of diff result if it's truncated. +如果差异结果被截断,在末尾输出的注释。 ## diff.truncateAnnotationColor -- **Type**: `DiffOptionsColor = (arg: string) => string` -- **Default**: `noColor = (string: string): string => string` +- **类型:** `DiffOptionsColor = (arg: string) => string` +- **默认值:** `noColor = (string: string): string => string` -Color of truncate annotation, default is output with no color. +截断注释的颜色,默认无颜色输出。 ## diff.printBasicPrototype -- **Type**: `boolean` -- **Default**: `false` +- **类型:** `boolean` +- **默认值:** `false` -Print basic prototype `Object` and `Array` in diff output +在差异输出中打印基本原型 `Object` 和 `Array`。 ## diff.maxDepth -- **Type**: `number` -- **Default**: `20` (or `8` when comparing different types) +- **类型:** `number` +- **默认值:** `20` (或比较不同类型时为 `8`) -Limit the depth to recurse when printing nested objects +打印嵌套对象时递归的最大深度。 diff --git a/config/dir.md b/config/dir.md index 4fa15aea..db2c8092 100644 --- a/config/dir.md +++ b/config/dir.md @@ -1,12 +1,12 @@ --- -title: dir | Config +title: dir | 配置 outline: deep --- # dir -- **Type:** `string` -- **CLI:** `--dir=` -- **Default:** same as `root` +- **类型:** `string` +- **命令行终端:** `--dir=` +- **默认值:** 与 `root` 相同 -Base directory to scan for the test files. You can specify this option to speed up test discovery if your root covers the whole project +用于扫描测试文件的基础目录。如果你的根目录覆盖整个项目,可以指定此选项来加快测试发现速度。 diff --git a/config/disableconsoleintercept.md b/config/disableconsoleintercept.md index 40c04f5f..54f5040a 100644 --- a/config/disableconsoleintercept.md +++ b/config/disableconsoleintercept.md @@ -1,20 +1,20 @@ --- -title: disableConsoleIntercept | Config +title: disableConsoleIntercept | 配置 outline: deep --- # disableConsoleIntercept -- **Type:** `boolean` -- **CLI:** `--disableConsoleIntercept` -- **Default:** `false` +- **类型:** `boolean` +- **命令行终端:** `--disableConsoleIntercept` +- **默认值:** `false` -By default, Vitest automatically intercepts console logging during tests for extra formatting of test file, test title, etc. +默认情况下,Vitest 会在测试期间自动拦截控制台日志,以便为测试文件、测试标题等添加额外格式。 -This is also required for console log preview on Vitest UI. +该功能也是 UI 模式控制台日志预览的必要条件。 -However, disabling such interception might help when you want to debug a code with normal synchronous terminal console logging. +不过,当你想要使用正常的同步终端控制台日志来调试代码时,禁用这种拦截可能会有帮助。 ::: warning -This option has no effect on [browser tests](/guide/browser/) since Vitest preserves original logging in browser devtools. +此选项对 [浏览器测试](/guide/browser/) 无效,因为 Vitest 会保留浏览器开发者工具中的原始日志记录。 ::: diff --git a/config/env.md b/config/env.md index eaf3ee13..6af8d0c7 100644 --- a/config/env.md +++ b/config/env.md @@ -1,10 +1,10 @@ --- -title: env | Config +title: env | 配置 outline: deep --- # env -- **Type:** `Partial` +- **类型:** `Partial` -Environment variables available on `process.env` and `import.meta.env` during tests. These variables will not be available in the main process (in `globalSetup`, for example). +测试期间在 `process.env` 和 `import.meta.env` 中可用的环境变量。这些变量在主进程中不可用(例如在 `globalSetup` 中)。 diff --git a/config/environment.md b/config/environment.md index 66c6b80f..9a445dbe 100644 --- a/config/environment.md +++ b/config/environment.md @@ -1,29 +1,27 @@ --- -title: environment | Config +title: environment | 配置 --- # environment -- **Type:** `'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string` -- **Default:** `'node'` -- **CLI:** `--environment=` +- **类型:** `'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string` +- **默认值:** `'node'` +- **命令行终端:** `--environment=` -The environment that will be used for testing. The default environment in Vitest -is a Node.js environment. If you are building a web application, you can use -browser-like environment through either [`jsdom`](https://github.com/jsdom/jsdom) -or [`happy-dom`](https://github.com/capricorn86/happy-dom) instead. -If you are building edge functions, you can use [`edge-runtime`](https://edge-runtime.vercel.app/packages/vm) environment +测试时将使用的运行环境。Vitest 中的默认测试环境是一个 Node.js 环境。 +如果你正在构建 Web 端应用,可选用 [`jsdom`](https://github.com/jsdom/jsdom) +或 [`happy-dom`](https://github.com/capricorn86/happy-dom) 这种类似浏览器(browser-like)的环境来替代 Node.js。 +如果你正在构建边缘计算函数,可选用 [`edge-runtime`](https://edge-runtime.vercel.app/packages/vm) 环境。 ::: tip -You can also use [Browser Mode](/guide/browser/) to run integration or unit tests in the browser without mocking the environment. +你还可以使用 [浏览器模式](/guide/browser/) 在浏览器中运行集成或单元测试,而无需模拟环境。 ::: -To define custom options for your environment, use [`environmentOptions`](/config/environmentoptions). +要为环境配置自定义选项,请使用 [`environmentOptions`](/config/environmentoptions)。 -By adding a `@vitest-environment` docblock or comment at the top of the file, -you can specify another environment to be used for all tests in that file: +通过在文件顶部添加 `@vitest-environment` 文档注释或普通注释,你可以为该文件中的所有测试指定其他运行环境: -Docblock style: +文档注释: ```js /** @@ -36,7 +34,7 @@ test('use jsdom in this test file', () => { }) ``` -Comment style: +普通注释: ```js // @vitest-environment happy-dom @@ -47,7 +45,7 @@ test('use happy-dom in this test file', () => { }) ``` -For compatibility with Jest, there is also a `@jest-environment`: +为了与 Jest 兼容,还存在一个 `@jest-environment`: ```js /** @@ -60,9 +58,9 @@ test('use jsdom in this test file', () => { }) ``` -You can also define a custom environment. When non-builtin environment is used, Vitest will try to load the file if it's relative or absolute, or a package `vitest-environment-${name}`, if the name is a bare specifier. +你还可以定义自定义环境。使用非内置环境时,Vitest 会根据你提供的内容加载对应的文件或包:如果是文件路径则加载文件,如果是包名则加载 `vitest-environment-${name}` 的包 -The custom environment file should export an object with the shape of `Environment`: +该包应导出一个具有 `Environment` 属性的对象: ```ts [environment.js] import type { Environment } from 'vitest' @@ -71,10 +69,10 @@ export default { name: 'custom', viteEnvironment: 'ssr', setup() { - // custom setup + // 自定义初始化 return { teardown() { - // called after all tests with this env have been run + // 在所有使用此环境的测试运行完毕后调用 } } } @@ -82,13 +80,13 @@ export default { ``` ::: tip -The `viteEnvironment` field corresponds to the environment defined by the [Vite Environment API](https://vite.dev/guide/api-environment#environment-api). By default, Vite exposes `client` (for the browser) and `ssr` (for the server) environments. +`viteEnvironment` 字段对应于 [Vite 环境 API](https://cn.vite.dev/guide/api-environment#environment-api)。默认情况下,Vite 公开 `client`(用于浏览器)和 `ssr`(用于服务器)环境。 ::: -Vitest also exposes `builtinEnvironments` through `vitest/environments` entry, in case you just want to extend it. You can read more about extending environments in [our guide](/guide/environment). +为了直接扩展使用Vitest 还从 `vitest/environments` 包导出 `builtinEnvironments`。关于扩展测试环境的更多信息,请参阅 [测试环境](/guide/environment)。 ::: tip -jsdom environment exposes `jsdom` global variable equal to the current [JSDOM](https://github.com/jsdom/jsdom) instance. If you want TypeScript to recognize it, you can add `vitest/jsdom` to your `tsconfig.json` when you use this environment: +jsdom 测试环境会暴露一个等同于当前 [JSDOM](https://github.com/jsdom/jsdom) 实例的全局变量 `jsdom`。如果你想让 TypeScript 识别它,在使用此环境时可将 `vitest/jsdom` 添加到你的 `tsconfig.json` 中: ```json [tsconfig.json] { diff --git a/config/environmentoptions.md b/config/environmentoptions.md index 0a8e478c..f45b223e 100644 --- a/config/environmentoptions.md +++ b/config/environmentoptions.md @@ -1,15 +1,15 @@ --- -title: environmentOptions | Config +title: environmentOptions | 配置 --- # environmentOptions -- **Type:** `Record<'jsdom' | 'happyDOM' | string, unknown>` -- **Default:** `{}` +- **类型:** `Record<'jsdom' | 'happyDOM' | string, unknown>` +- **默认值:** `{}` -These options are passed to the setup method of the current [environment](/config/environment). By default, you can configure options only for `jsdom` and `happyDOM` when you use them as your test environment. +这些选项会被传递到当前 [环境](/config/environment) 的初始化方法中。默认情况下,只能为 `jsdom` 或 `happyDOM` 这两个测试环境配置选项。 -## Example +## 示例 {#example} ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -30,5 +30,5 @@ export default defineConfig({ ``` ::: warning -Options are scoped to their environment. For example, put jsdom options under the `jsdom` key and happy-dom options under the `happyDOM` key. This lets you mix multiple environments within the same project. +选项被限定在各自的环境范围内。例如,将 jsdom 选项放在 `jsdom` 键下,happy-dom 选项放在 `happyDOM` 键下。这使你能够在同一项目中同时使用多个环境。 ::: diff --git a/config/exclude.md b/config/exclude.md index 7e44ee52..e60fb82a 100644 --- a/config/exclude.md +++ b/config/exclude.md @@ -1,24 +1,24 @@ --- -title: exclude | Config +title: exclude | 配置 --- # exclude -- **Type:** `string[]` -- **Default:** `['**/node_modules/**', '**/.git/**']` -- **CLI:** `vitest --exclude "**/excluded-file" --exclude "*/other-files/*.js"` +- **类型:** `string[]` +- **默认值:** `['**/node_modules/**', '**/.git/**']` +- **命令行终端:** `vitest --exclude "**/excluded-file" --exclude "*/other-files/*.js"` -A list of [glob patterns](https://superchupu.dev/tinyglobby/comparison) that should be excluded from your test files. These patterns are resolved relative to the [`root`](/config/root) ([`process.cwd()`](https://nodejs.org/api/process.html#processcwd) by default). +匹配排除测试文件的 [glob 规则](https://superchupu.dev/tinyglobby/comparison)。该规则相对于 [`root`](/config/root) 进行解析(默认为 [`process.cwd()`](https://nodejs.org/api/process.html#processcwd))。 -Vitest uses the [`tinyglobby`](https://npmx.dev/package/tinyglobby) package to resolve the globs. +Vitest 使用 [`tinyglobby`](https://npmx.dev/package/tinyglobby) 包来解析 glob 规则。 ::: warning -This option does not affect coverage. If you need to remove certain files from the coverage report, use [`coverage.exclude`](/config/coverage#exclude). +该配置项不影响代码覆盖率。如需从覆盖率报告中排除特定文件,请使用 [`coverage.exclude`](/config/coverage#exclude)。 -This is the only option that doesn't override your configuration if you provide it with a CLI flag. All glob patterns added via `--exclude` flag will be added to the config's `exclude`. +如果使用命令行参数,这是唯一一个不会被覆盖配置项。通过 `--exclude` 标志添加的所有 glob 规则都将追加到 `exclude` 中。 ::: -## Example +## 示例 {#example} ```js import { defineConfig } from 'vitest/config' @@ -35,7 +35,7 @@ export default defineConfig({ ``` ::: tip -Although the CLI `exclude` option is additive, manually setting `exclude` in your config will replace the default value. To extend the default `exclude` patterns, use `configDefaults` from `vitest/config`: +虽然使用命令行 `exclude` 配置项是累加的,但在配置中手动设置 `exclude` 会替换默认值。要扩展默认的 `exclude` 配置项,请使用 `vitest/config` 中的 `configDefaults`: ```js{6} import { configDefaults, defineConfig } from 'vitest/config' diff --git a/config/execargv.md b/config/execargv.md index 3022dad3..ae321acd 100644 --- a/config/execargv.md +++ b/config/execargv.md @@ -1,5 +1,5 @@ --- -title: execArgv | Config +title: execArgv | 配置 outline: deep --- diff --git a/config/expandsnapshotdiff.md b/config/expandsnapshotdiff.md index 47dc59b2..34ad1606 100644 --- a/config/expandsnapshotdiff.md +++ b/config/expandsnapshotdiff.md @@ -1,12 +1,12 @@ --- -title: expandSnapshotDiff | Config +title: expandSnapshotDiff | 配置 outline: deep --- # expandSnapshotDiff -- **Type:** `boolean` -- **CLI:** `--expandSnapshotDiff`, `--expand-snapshot-diff` -- **Default:** `false` +- **类型:** `boolean` +- **命令行终端:** `--expandSnapshotDiff`, `--expand-snapshot-diff` +- **默认值:** `false` -Show full diff when snapshot fails instead of a patch. +当快照测试失败时显示完整差异(而非补丁对比)。 diff --git a/config/expect.md b/config/expect.md index 1090f171..c212694c 100644 --- a/config/expect.md +++ b/config/expect.md @@ -1,43 +1,43 @@ --- -title: expect | Config +title: expect | 配置 outline: deep --- # expect -- **Type:** `ExpectOptions` +- **类型:** `ExpectOptions` ## expect.requireAssertions -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -The same as calling [`expect.hasAssertions()`](/api/expect#expect-hasassertions) at the start of every test. This makes sure that no test will pass accidentally. +与每次测试开始时调用 [`expect.hasAssertions()`](/api/expect#expect-hasassertions) 相同。这可确保不会意外通过任何测试。 ::: tip -This only works with Vitest's `expect`. If you use `assert` or `.should` assertions, they will not count, and your test will fail due to the lack of expect assertions. +这仅适用于 Vitest 的`expect`。如果我们使用`assert`或`.should`断言,它们将不计算在内,并且我们的测试将因缺少 expect 断言而失败。 -You can change the value of this by calling `vi.setConfig({ expect: { requireAssertions: false } })`. The config will be applied to every subsequent `expect` call until the `vi.resetConfig` is called manually. +我们可以通过调用 `vi.setConfig({ expect: { requireAssertions: false } })` 来更改此值。该配置将应用于每个后续 `expect` 调用,直到手动调用 `vi.resetConfig`。 ::: ::: warning -When you run tests with `sequence.concurrent` and `expect.requireAssertions` set to `true`, you should use [local expect](/guide/test-context.html#expect) instead of the global one. Otherwise, this may cause false negatives in [some situations (#8469)](https://github.com/vitest-dev/vitest/issues/8469). +当使用 `sequence.concurrent` 和将 `expect.requireAssertions` 设为 `true` 运行测试时,应当使用 [本地 expect](/guide/test-context.html#expect) 而非全局 expect。否则在 [某些情况下](https://github.com/vitest-dev/vitest/issues/8469) 出现误判为失败的情况。 ::: ## expect.poll -Global configuration options for [`expect.poll`](/api/expect#poll). These are the same options you can pass down to `expect.poll(condition, options)`. +[`expect.poll`](/api/expect#poll) 的全局配置选项。这些选项与我们可以传递给 `expect.poll(condition, options)` 的选项相同。 ### expect.poll.interval -- **Type:** `number` -- **Default:** `50` +- **类型:** `number` +- **默认值:** `50` -Polling interval in milliseconds +轮询间隔(以毫秒为单位)。 ### expect.poll.timeout -- **Type:** `number` -- **Default:** `1000` +- **类型:** `number` +- **默认值:** `1000` -Polling timeout in milliseconds +轮询超时时间(以毫秒为单位)。 diff --git a/config/experimental.md b/config/experimental.md index ed1df35c..ad4de8ed 100644 --- a/config/experimental.md +++ b/config/experimental.md @@ -1,5 +1,5 @@ --- -title: 实验性 | Config +title: 实验性 | 配置 outline: deep --- @@ -177,50 +177,48 @@ export default defineConfig({ ## experimental.importDurations 4.1.0 {#experimental-importdurations} - - ::: tip 功能反馈 请将关于此功能反馈提交至 [GitHub Discussion](https://github.com/vitest-dev/vitest/discussions/9224)。 ::: -- **Type:** +- **类型:** ```ts interface ImportDurationsOptions { /** - * When to print import breakdown to CLI terminal. - * - false: Never print (default) - * - true: Always print - * - 'on-warn': Print only when any import exceeds warn threshold + * 何时在 CLI 终端打印导入耗时明细 + * - false: 从不打印(默认值) + * - true: 总是打印 + * - 'on-warn': 仅当有导入超过警告阈值时打印 */ print?: boolean | 'on-warn' /** - * Fail the test run if any import exceeds the danger threshold. - * When enabled and threshold exceeded, breakdown is always printed. + * 当任何导入超过危险阈值时使测试运行失败 + * 启用后若超过阈值,将始终打印明细 * @default false */ failOnDanger?: boolean /** - * Maximum number of imports to collect and display. + * 收集并显示的最大导入数量 */ limit?: number /** - * Duration thresholds in milliseconds for coloring and warnings. + * 持续时间阈值(毫秒),用于控制着色显示和警告触发。 */ thresholds?: { - /** Threshold for yellow/warning color. @default 100 */ + /** 黄色/警告颜色的阈值 @default 100 */ warn?: number - /** Threshold for red/danger color and failOnDanger. @default 500 */ + /** 红色/危险颜色及触发 failOnDanger 的阈值 @default 500 */ danger?: number } } ``` -- **Default:** `{ print: false, failOnDanger: false, limit: 0, thresholds: { warn: 100, danger: 500 } }` (`limit` is 10 if `print` or UI is enabled) +- **默认值:** `{ print: false, failOnDanger: false, limit: 0, thresholds: { warn: 100, danger: 500 } }` (`limit` is 10 if `print` or UI is enabled) -Configure import duration collection and display. +配置导入耗时收集与显示功能。 -The `print` option controls CLI terminal output. The `limit` option controls how many imports to collect and display. [Vitest UI](/guide/ui#import-breakdown) can always toggle the breakdown display regardless of the `print` setting. +`print` 选项控制 CLI 终端的输出行为,`limit` 选项控制收集和显示的导入数量上限。[UI 模式](/guide/ui#import-breakdown) 始终可切换明细显示视图(不受 `print` 设置影响)。 - Self:模块导入耗时,不包括静态导入; - Total:模块导入耗时,包括静态导入。请注意,这不包括当前模块的 `transform` 时间。 @@ -232,23 +230,23 @@ The `print` option controls CLI terminal output. The `limit` option controls how ### experimental.importDurations.print {#experimental-importdurationsprint} -- **Type:** `boolean | 'on-warn'` -- **Default:** `false` +- **类型:** `boolean | 'on-warn'` +- **默认值:** `false` -Controls when to print import breakdown to CLI terminal after tests finish. This only works with [`default`](/guide/reporters#default), [`verbose`](/guide/reporters#verbose), or [`tree`](/guide/reporters#tree) reporters. +控制测试结束后何时在 CLI 打印导入耗时分析。该功能仅适用于 [`default`](/guide/reporters#default)、[`verbose`](/guide/reporters#verbose) 或 [`tree`](/guide/reporters#tree) 报告器。 -- `false`: Never print breakdown -- `true`: Always print breakdown -- `'on-warn'`: Print only when any import exceeds the `thresholds.warn` value +- `false`: 从不打印分析结果 +- `true`: 总是打印分析结果 +- `'on-warn'`: 仅当任何导入耗时超过 `thresholds.warn` 阈值时打印 ### experimental.importDurations.failOnDanger {#experimental-importdurationsfailondanger} -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Fail the test run if any import exceeds the `thresholds.danger` value. When enabled and the threshold is exceeded, the breakdown is always printed regardless of the `print` setting. +当任何导入操作耗时超过 `thresholds.danger` 阈值时,测试将会运行失败。启用该选项且超过阈值时,无论 `print` 如何设置,始终会打印性能分析报告。 -This is useful for enforcing import performance budgets in CI: +该功能适用于在 CI 环境中确保导入操作符合性能预期: ```bash vitest --experimental.importDurations.failOnDanger @@ -256,93 +254,91 @@ vitest --experimental.importDurations.failOnDanger ### experimental.importDurations.limit {#experimental-importdurationslimit} -- **Type:** `number` -- **Default:** `0` (or `10` if `print`, `failOnDanger`, or UI is enabled) +- **类型:** `number` +- **默认值:** `0`(如果启用 `print`、`failOnDanger` 或 UI 模式时默认为`10`) -Maximum number of imports to collect and display in CLI output, [Vitest UI](/guide/ui#import-breakdown), and third-party reporters. +在 CLI 输出、[UI 模式](/guide/ui#import-breakdown) 及第三方报告器中收集和显示的导入操作最大数量限制。 ### experimental.importDurations.thresholds {#experimental-importdurationsthresholds} -- **Type:** `{ warn?: number; danger?: number }` -- **Default:** `{ warn: 100, danger: 500 }` +- **类型:** `{ warn?: number; danger?: number }` +- **默认值:** `{ warn: 100, danger: 500 }` -Duration thresholds in milliseconds for coloring and warnings: +用于着色和警告的耗时阈值(单位:毫秒): -- `warn`: Threshold for yellow/warning color (default: 100ms) -- `danger`: Threshold for red/danger color and `failOnDanger` (default: 500ms) +- `warn`:触发黄色/警告颜色的阈值(默认值:100毫秒) +- `danger`:触发红色/危险颜色及 `failOnDanger` 的阈值(默认值:500毫秒) ::: info -[Vitest UI](/guide/ui#import-breakdown) 会在至少一个文件的加载时间超过 `danger` 阈值时,自动显示导入耗时分析。 +[UI 模式](/guide/ui#import-breakdown) 会在至少一个文件的加载时间超过 `danger` 阈值时,自动显示导入耗时分析。 ::: - - ## experimental.viteModuleRunner 4.1.0 {#experimental-vitemodulerunner} -::: tip FEEDBACK -Please leave feedback regarding this feature in a [GitHub Discussion](https://github.com/vitest-dev/vitest/discussions/9501). +::: tip 反馈 +通过 [GitHub 讨论区](https://github.com/vitest-dev/vitest/discussions/9501) 提交关于此功能的反馈。 ::: -- **Type:** `boolean` -- **Default:** `true` +- **类型:** `boolean` +- **默认值:** `true` -Controls whether Vitest uses Vite's [module runner](https://vite.dev/guide/api-environment-runtimes#modulerunner) to run the code or fallback to the native `import`. +控制 Vitest 是否使用 Vite 的 [模块运行器](https://cn.vite.dev/guide/api-environment-runtimes#modulerunner) 执行代码,或回退至原生 `import` 方式。 -If this option is defined in the root config, all [projects](/guide/projects) will inherit it automatically. +如果在根配置中定义此选项,所有 [项目](/guide/projects) 将自动继承该设置。 -Consider disabling the module runner if you are running tests in the same environment as your code (server backend or simple scripts, for example). However, we still recommend running `jsdom`/`happy-dom` tests with Vite's module runner or in [the browser](/guide/browser/) since it doesn't require any additional configuration. +当测试运行环境与代码执行环境相同时(例如服务端后端或简单脚本),可考虑禁用模块运行器。但对于 `jsdom`/`happy-dom` 测试,我们仍建议使用 Vite 模块运行器或在 [浏览器模式](/guide/browser/) 中运行,因为这样无需添加额外的配置。 -Disabling this flag will disable _all_ file transforms: +禁用此选项将导致 _所有_ 文件转换失效: -- test files and your source code are not processed by Vite -- your global setup files are not processed -- your custom runner/pool/environment files are not processed -- your config file is still processed by Vite (this happens before Vitest knows the `viteModuleRunner` flag) +- 测试文件及源码不会经过 Vite 处理 +- 全局初始化文件不会被处理 +- 自定义运行器 / 池 / 环境文件不会被处理 +- 配置文件仍由 Vite 处理(该过程发生在 Vitest 获知 `viteModuleRunner` 标志之前执行) ::: warning -At the moment, Vitest still requires Vite for certain functionality like the module graph or watch mode. +当前 Vitest 仍需依赖 Vite 实现某些功能,如模块图或监视模式。 -Also note that this option only works with `forks` or `threads` [pools](/config/pool). +另外请注意,此选项仅适用于`forks`或`threads`[执行池](/config/pool)。 ::: -### Module Runner +### 模块运行器 {#module-runner} -By default, Vitest runs tests in a very permissive module runner sandbox powered by Vite's [Environment API](https://vite.dev/guide/api-environment.html#environment-api). Every file is categorized as either an "inline" module or an "external" module. +Vitest 默认在由 Vite [环境 API](https://cn.vite.dev/guide/api-environment.html#environment-api) 提供非常宽松的模块运行器沙箱中执行测试。所有文件被归类为 "inline" 模块或 "external" 模块。 -Module runner runs all "inlined" modules. It provides `import.meta.env`, `require`, `__dirname`, `__filename`, static `import`, and has its own module resolution mechanism. This makes it very easy to run code when you don't want to configure the environment and just need to test that the bare JavaScript logic you wrote works as intended. +模块运行器负责执行所有 "inline" 模块。它提供 `import.meta.env` 环境变量、`require` 函数、`__dirname` 和 `__filename` 路径变量、静态 `import` 语法,并具备独立的模块解析机制。这使得在不配置环境的情况下运行代码变得非常简单,只需要测试你编写的纯 JavaScript 逻辑是否按预期工作即可。 -All "external" modules run in native mode, meaning they are executed outside of the module runner sandbox. If you are running tests in Node.js, these files are imported with the native `import` keyword and processed by Node.js directly. +所有 "external" 模块均以原生模式运行,这意味着它们会在模块运行器的沙箱环境之外执行。当在 Node.js 环境中运行测试时,这些文件将通过原生 `import` 关键字导入,并由 Node.js 直接处理。 -While running JSDOM/happy-dom tests in a permissive fake environment might be justified, running Node.js tests in a non-Node.js environment can hide and silence potential errors you may encounter in production, especially if your code doesn't require any additional transformations provided by Vite plugins. +虽然在宽松的模拟环境中运行 JSDOM / happy-dom 测试可能具有合理性,但在非 Node.js 环境下运行 Node.js 测试可能会隐藏并抑制你在生产环境中可能遇到的潜在错误,尤其是当你的代码不需要 Vite 插件提供的任何额外转换时。 -### Known Limitations +### 已知限制 {#known-limitations} -Some Vitest features rely on files being transformed. Vitest uses synchronous [Node.js Loaders API](https://nodejs.org/api/module.html#customization-hooks) to transform test files and setup files to support these features: +部分 Vitest 功能依赖于文件转换机制。Vitest 采用同步的 [Node.js Loaders API](https://nodejs.org/api/module.html#customization-hooks) 来转换测试文件和配置文件,以实现以下功能支持: - [`import.meta.vitest`](/guide/in-source) - [`vi.mock`](/api/vi#vi-mock) - [`vi.hoisted`](/api/vi#vi-hoisted) ::: warning -This means that Vitest requires at least Node 22.15 for those features to work. At the moment, they also do not work in Deno or Bun. +这意味着 Vitest 至少需要 Node 22.15 才能使这些功能工作。目前,它们也不适用于 Deno 或 Bun。 -Vitest will only detect `vi.mock` and `vi.hoisted` inside of test files, they will not be hoisted inside imported modules. +Vitest 只会在测试文件中检测 `vi.mock` 和 `vi.hoisted`,它们不会在导入的模块中被提升。 ::: -This could affect performance because Vitest needs to read the file and process it. If you do not use these features, you can disable the transforms by setting `experimental.nodeLoader` to `false`. Vitest only reads test files and setup files while looking for `vi.mock` or `vi.hoisted`. Using these in other files won't hoist them to the top of the file and can lead to unexpected behavior. +这可能会影响性能,因为 Vitest 需要读取文件并处理它。如果你不使用这些功能,可以通过将 `experimental.nodeLoader` 设置为 `false` 来禁用转换。Vitest 只在查找 `vi.mock` 或 `vi.hoisted` 时读取测试文件和全局初始化文件。在其他文件中使用它们不会将它们提升到文件顶部,并可能导致意外行为。 -Some features will not work due to the nature of `viteModuleRunner`, including: +由于 `viteModuleRunner` 的性质,某些功能将不起作用,包括: -- no `import.meta.env`: `import.meta.env` is a Vite feature, use `process.env` instead -- no `plugins`: plugins are not applied because there is no transformation phase, use [customization hooks](https://nodejs.org/api/module.html#customization-hooks) via [`execArgv`](/config/execargv) instead -- no `alias`: aliases are not applied because there is no transformation phase -- `istanbul` coverage provider doesn't work because there is no transformation phase, use `v8` instead +- 不支持 `import.meta.env`:`import.meta.env` 是 Vite 特性,使用 `process.env` 替代 +- 不支持 `plugins`:由于不存在转换阶段,插件不会生效,通过 [`execArgv`](/config/execargv) 使用 [自定义钩子](https://nodejs.org/api/module.html#customization-hooks) 替代 +- 不支持 `alias`:由于不存在转换阶段,路径别名不会生效 +- `istanbul` 覆盖率工具无法工作(因缺少转换阶段),请改用 `v8` 覆盖率工具 -::: warning Coverage Support -At the moment Vitest supports coverage via `v8` provider as long as files can be transformed into JavaScript. To transform TypeScript, Vitest uses [`module.stripTypeScriptTypes`](https://nodejs.org/api/module.html#modulestriptypescripttypescode-options) which is available in Node.js since v22.13. If you are using a custom [module loader](https://nodejs.org/api/module.html#customization-hooks), Vitest is not able to reuse it to transform files for analysis. +::: warning 覆盖率支持 +当前 Vitest 通过 `v8` 提供程序支持覆盖率分析,前提是文件能够被转换为 JavaScript。对于 TypeScript 转换,Vitest 使用 Node.js v22.13 版本起提供的 [`module.stripTypeScriptTypes`](https://nodejs.org/api/module.html#modulestriptypescripttypescode-options) 功能。如果你使用自定义 [模块加载器](https://nodejs.org/api/module.html#customization-hooks),Vitest 将无法复用该加载器进行覆盖率分析所需的文件转换。 ::: -With regards to mocking, it is also important to point out that ES modules do not support property override. This means that code like this won't work anymore: +关于模拟对象功能,需要特别指出的是 ES 模块不支持属性重写。这意味着以下代码将无法正常工作: ```ts import * as fs from 'node:fs' @@ -351,7 +347,7 @@ import { vi } from 'vitest' vi.spyOn(fs, 'readFileSync').mockImplementation(() => '42') // ❌ ``` -However, Vitest supports auto-spying on modules without overriding their implementation. When `vi.mock` is called with a `spy: true` argument, the module is mocked in a way that preserves original implementations, but all exported functions are wrapped in a `vi.fn()` spy: +但 Vitest 支持在不覆盖模块实现的情况下进行自动监听。当调用 `vi.mock` 并传入 `spy: true` 参数时,模块会以保留原始实现的方式被模拟,同时所有导出的函数都会被包裹在 `vi.fn()` 监听器中: ```ts import * as fs from 'node:fs' @@ -362,7 +358,7 @@ vi.mock('node:fs', { spy: true }) fs.readFileSync.mockImplementation(() => '42') // ✅ ``` -Factory mocking is implemented using a top-level await. This means that mocked modules cannot be loaded with `require()` in your source code: +工厂模拟功能通过顶层 await 实现。这意味着在你的源代码中无法使用 `require()` 加载被模拟的模块: ```ts vi.mock('node:fs', async (importOriginal) => { @@ -372,26 +368,26 @@ vi.mock('node:fs', async (importOriginal) => { } }) -const fs = require('node:fs') // throws an error +const fs = require('node:fs') // 报错 ``` -This limitation exists because factories can be asynchronous. This should not be a problem because Vitest doesn't mock builtin modules inside `node_modules`, which is similar to how Vitest works by default. +这种限制源自于工厂函数可以是异步的。不过这不构成问题,因为 Vitest 默认不会模拟 `node_modules` 中的内置模块,这类似于 Vitest 默认的工作方式。 ### TypeScript -If you are using Node.js 22.18/23.6 or higher, TypeScript will be [transformed natively](https://nodejs.org/en/learn/typescript/run-natively) by Node.js. +如果你使用的是 Node.js 22.18/23.6 或更高版本,TypeScript 将由 Node.js [原生支持转换](https://nodejs.org/en/learn/typescript/run-natively)。 -::: warning TypeScript with Node.js 22.6-22.18 -If you are using Node.js version between 22.6 and 22.18, you can also enable native TypeScript support via `--experimental-strip-types` flag: +::: warning 在 Node.js 22.6-22.18 环境中的使用 TypeScript +如果您使用的 Node.js 版本介于 22.6 至 22.18 之间,还可通过 `--experimental-strip-types` 参数启用原生 TypeScript 支持: ```shell NODE_OPTIONS="--experimental-strip-types" vitest ``` -If you are using TypeScript and Node.js version lower than 22.6, then you will need to either: +如果你使用的是 TypeScript 且 Node.js 版本低于 22.6,则需要执行以下任一操作: -- build your test files and source code and run those files directly -- import a [custom loader](https://nodejs.org/api/module.html#customization-hooks) via `execArgv` flag +- 构建测试文件和源代码并直接运行这些文件 +- 通过 `execArgv` 参数导入 [自定义加载器](https://nodejs.org/api/module.html#customization-hooks) ```ts import { defineConfig } from 'vitest/config' @@ -410,12 +406,12 @@ export default defineConfig({ }) ``` -If you are running tests in Deno, TypeScript files are processed by the runtime without any additional configurations. +如果你在 Deno 中运行测试,TypeScript 文件由运行时处理,无需任何额外配置。 ::: ## experimental.vcsProvider 4.1.1 {#experimental-vcsprovider} -- **Type:** `VCSProvider | string` +- **类型:** `VCSProvider | string` ```ts interface VCSProvider { @@ -428,11 +424,11 @@ interface VCSProviderOptions { } ``` -- **Default:** `'git'` +- **默认值:** `'git'` -Custom provider for detecting changed files. Used with the [`--changed`](/guide/cli#changed) flag to determine which files have been modified. +用于检测更改文件的自定义驱动。与 [`--changed`](/guide/cli#changed) 标志配合使用,用于确定哪些文件已被修改。 -By default, Vitest uses Git to detect changed files. You can provide a custom implementation of the `VCSProvider` interface to use a different version control system: +默认情况下,Vitest 使用 Git 检测更改的文件。你可以提供 `VCSProvider` 接口的自定义实现以使用不同的版本控制系统: ```ts [vitest.config.ts] import { defineConfig } from 'vitest/config' @@ -442,7 +438,7 @@ export default defineConfig({ experimental: { vcsProvider: { async findChangedFiles({ root, changedSince }) { - // return paths of changed files + // 返回已变更的文件路径 return [] }, }, @@ -451,7 +447,7 @@ export default defineConfig({ }) ``` -You can also pass a string path to a module with a default export that implements the `VCSProvider` interface: +你也可以传入一个字符串路径,指向包含实现 `VCSProvider` 接口的默认导出模块: ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -468,7 +464,7 @@ export default defineConfig({ ```js [my-vcs-provider.js] export default { async findChangedFiles({ root, changedSince }) { - // return paths of changed files + // 返回已变更的文件路径 return [] }, } @@ -476,9 +472,9 @@ export default { ## experimental.nodeLoader 4.1.0 {#experimental-nodeloader} -- **Type:** `boolean` -- **Default:** `true` +- **类型:** `boolean` +- **默认值:** `true` -If module runner is disabled, Vitest uses a native [Node.js module loader](https://nodejs.org/api/module.html#customization-hooks) to transform files to support `import.meta.vitest`, `vi.mock` and `vi.hoisted`. +如果禁用模块运行器,Vitest 会使用原生 [Node.js 模块加载器](https://nodejs.org/api/module.html#customization-hooks) 来转换文件,以支持 `import.meta.vitest`、`vi.mock` 和 `vi.hoisted` 功能。 -If you don't use these features, you can disable this to improve performance. +如果你不使用这些特性,可禁用此功能以提升性能。 diff --git a/config/faketimers.md b/config/faketimers.md index 68b43e1c..b01c550f 100644 --- a/config/faketimers.md +++ b/config/faketimers.md @@ -1,56 +1,56 @@ --- -title: fakeTimers | Config +title: fakeTimers | 配置 outline: deep --- # fakeTimers -- **Type:** `FakeTimerInstallOpts` +- **类型:** `FakeTimerInstallOpts` -Options that Vitest will pass down to [`@sinon/fake-timers`](https://npmx.dev/package/@sinonjs/fake-timers) when using [`vi.useFakeTimers()`](/api/vi#vi-usefaketimers). +当使用 [`vi.useFakeTimers()`](/api/vi#vi-usefaketimers) 时,Vitest 会将此选项传递给 [`@sinon/fake-timers`](https://npmx.dev/package/@sinonjs/fake-timers)。 ## fakeTimers.now -- **Type:** `number | Date` -- **Default:** `Date.now()` +- **类型:** `number | Date` +- **默认值:** `Date.now()` -Installs fake timers with the specified Unix epoch. +使用指定的 Unix 时间戳安装假计时器。 ## fakeTimers.toFake -- **Type:** `('setTimeout' | 'clearTimeout' | 'setImmediate' | 'clearImmediate' | 'setInterval' | 'clearInterval' | 'Date' | 'nextTick' | 'hrtime' | 'requestAnimationFrame' | 'cancelAnimationFrame' | 'requestIdleCallback' | 'cancelIdleCallback' | 'performance' | 'queueMicrotask')[]` -- **Default:** everything available globally except `nextTick` and `queueMicrotask` +- **类型:** `('setTimeout' | 'clearTimeout' | 'setImmediate' | 'clearImmediate' | 'setInterval' | 'clearInterval' | 'Date' | 'nextTick' | 'hrtime' | 'requestAnimationFrame' | 'cancelAnimationFrame' | 'requestIdleCallback' | 'cancelIdleCallback' | 'performance' | 'queueMicrotask')[]` +- **默认值:** 全局可用的所有方法,除了 `nextTick` 和 `queueMicrotask` -An array with names of global methods and APIs to fake. +需要模拟的全局方法和 API 名称数组。 -To only mock `setTimeout()` and `nextTick()`, specify this property as `['setTimeout', 'nextTick']`. +如果仅需模拟 `setTimeout()` 和 `nextTick()`,可将此属性指定为 `['setTimeout', 'nextTick']`。 -Mocking `nextTick` is not supported when running Vitest inside `node:child_process` by using `--pool=forks`. NodeJS uses `process.nextTick` internally in `node:child_process` and hangs when it is mocked. Mocking `nextTick` is supported when running Vitest with `--pool=threads`. +当使用 `--pool=forks` 在 `node:child_process` 中运行 Vitest 时,不支持模拟 `nextTick`。NodeJS 会在 `node:child_process` 内部使用 `process.nextTick`,模拟后会导致进程挂起。使用 `--pool=threads` 运行 Vitest 时支持模拟 `nextTick`。 ## fakeTimers.loopLimit -- **Type:** `number` -- **Default:** `10_000` +- **类型:** `number` +- **默认值:** `10_000` -The maximum number of timers that will be run when calling [`vi.runAllTimers()`](/api/vi#vi-runalltimers). +调用 [`vi.runAllTimers()`](/api/vi#vi-runalltimers) 时将运行的最大计时器数量。 ## fakeTimers.shouldAdvanceTime -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Tells @sinonjs/fake-timers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change in the real system time). +告诉 @sinonjs/fake-timers 根据真实系统时间的变化自动递增模拟时间(例如,真实系统时间变化 20ms 时,模拟时间也会递增 20ms)。 ## fakeTimers.advanceTimeDelta -- **Type:** `number` -- **Default:** `20` +- **类型:** `number` +- **默认值:** `20` -Relevant only when using with `shouldAdvanceTime: true`. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change in the real system time. +仅在使用 `shouldAdvanceTime: true` 时相关。真实系统时间每变化 advanceTimeDelta 毫秒,模拟时间就会递增 advanceTimeDelta 毫秒。 ## fakeTimers.shouldClearNativeTimers -- **Type:** `boolean` -- **Default:** `true` +- **类型:** `boolean` +- **默认值:** `true` -Tells fake timers to clear "native" (i.e. not fake) timers by delegating to their respective handlers. When disabled, it can lead to potentially unexpected behavior if timers existed prior to starting fake timers session. +指示假计时器通过委托给它们各自的处理函数来清除 “原生”(即非假)计时器。如果禁用此功能,当伪计时器会话启动前已存在计时器时,可能导致意外行为。 diff --git a/config/fileparallelism.md b/config/fileparallelism.md index 8f2b6dac..70d50d60 100644 --- a/config/fileparallelism.md +++ b/config/fileparallelism.md @@ -1,5 +1,5 @@ --- -title: fileParallelism | Config +title: fileParallelism | 配置 outline: deep --- @@ -9,8 +9,8 @@ outline: deep - **默认值:** `true` - **命令行终端:** `--no-file-parallelism`, `--fileParallelism=false` -所有测试文件应该并行运行。 将其设置为 `false` 将覆盖 `maxWorkers` 选项为 `1`。 +是否允许所有测试文件并行运行。若设为 `false`,将强制 `maxWorkers` 选项降为 `1`。 ::: tip -此选项不会影响在同一文件中运行的测试。如果你想并行运行这些程序,使用 `concurrent` 选项 [describe](/api/describe#describe-concurrent) 或通过 [配置](/config/sequence#sequence-concurrent)。 +此选项不会影响同一文件内的测试运行。如需并行执行同一文件内的测试,请在 [describe](/api/describe#describe-concurrent) 块中使用 `concurrent` 选项或通过 [配置文件](/config/sequence#sequence-concurrent) 设置。 ::: diff --git a/config/forcereruntriggers.md b/config/forcereruntriggers.md index 342143e1..7a104366 100644 --- a/config/forcereruntriggers.md +++ b/config/forcereruntriggers.md @@ -1,24 +1,24 @@ --- -title: forceRerunTriggers | Config +title: forceRerunTriggers | 配置 outline: deep --- # forceRerunTriggers -- **Type**: `string[]` -- **Default:** `['**/package.json/**', '**/vitest.config.*/**', '**/vite.config.*/**']` +- **类型:** `string[]` +- **默认值:** `['**/package.json/**', '**/vitest.config.*/**', '**/vite.config.*/**']` -Glob pattern of file paths that will trigger the whole suite rerun. When paired with the `--changed` argument will run the whole test suite if the trigger is found in the git diff. +将触发整个测试套件重新运行的文件路径(glob 模式)。当与 `--changed` 参数配合使用时,如果在 git diff 中发现触发文件,就会运行整个测试套件。 -Useful if you are testing calling CLI commands, because Vite cannot construct a module graph: +因为 Vite 无法构建模块依赖图,所以适用于测试调用 CLI 命令的场景: ```ts -test('execute a script', async () => { - // Vitest cannot rerun this test, if content of `dist/index.js` changes +test('执行一个脚本', async () => { + // 如果 `dist/index.js` 的内容发生变化,Vitest 无法重新运行此测试 await execa('node', ['dist/index.js']) }) ``` ::: tip -Make sure that your files are not excluded by [`server.watch.ignored`](https://vitejs.dev/config/server-options.html#server-watch). +请确保你的文件没有被 [`server.watch.ignored`](https://cn.vitejs.dev/config/server-options.html#server-watch) 配置排除。 ::: diff --git a/config/globals.md b/config/globals.md index 1dcf7ef0..923ad8dc 100644 --- a/config/globals.md +++ b/config/globals.md @@ -1,14 +1,14 @@ --- -title: globals | Config +title: globals | 配置 --- # globals -- **Type:** `boolean` -- **Default:** `false` -- **CLI:** `--globals`, `--no-globals`, `--globals=false` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--globals`, `--no-globals`, `--globals=false` -By default, `vitest` does not provide global APIs for explicitness. If you prefer to use the APIs globally like Jest, you can pass the `--globals` option to CLI or add `globals: true` in the config. +默认情况下,`vitest` 不显式提供全局 API。如果你更倾向于使用类似 jest 中的全局 API,可以通过 CLI 传递 `--globals` 选项,或在配置中添加 `globals: true`。 ```js import { defineConfig } from 'vitest/config' @@ -21,10 +21,10 @@ export default defineConfig({ ``` ::: tip -Note that some libraries, e.g., `@testing-library/react`, rely on globals being present to perform auto cleanup. +注意,某些库(如 `@testing-library/react`)需要依赖全局 API 的存在才能执行自动清理操作 ::: -To get TypeScript working with the global APIs, add `vitest/globals` to the `types` field in your `tsconfig.json`: +为了可以让全局 API 支持 TypeScript,请将 `vitest/globals` 添加到 `tsconfig.json` 中的 `types` 选项中 ```json [tsconfig.json] { @@ -34,7 +34,7 @@ To get TypeScript working with the global APIs, add `vitest/globals` to the `typ } ``` -If you have redefined your [`typeRoots`](https://www.typescriptlang.org/tsconfig/#typeRoots) to include additional types in your compilation, you will need to add back the `node_modules` to make `vitest/globals` discoverable: +如果你重新定义了 [`typeRoots`](https://www.typescriptlang.org/tsconfig/#typeRoots) 以在编译中包含额外的类型,你需要将 `node_modules` 添加回来,使得 `vitest/globals` 可被发现: ```json [tsconfig.json] { diff --git a/config/globalsetup.md b/config/globalsetup.md index 279d3d39..c8d60ad5 100644 --- a/config/globalsetup.md +++ b/config/globalsetup.md @@ -1,15 +1,15 @@ --- -title: globalSetup | Config +title: globalSetup | 配置 outline: deep --- # globalSetup -- **Type:** `string | string[]` +- **类型:** `string | string[]` -Path to global setup files relative to project [root](/config/root). +相对于 [项目根目录](/config/root) 的全局初始化文件路径。 -A global setup file can either export named functions `setup` and `teardown` or a `default` function that returns a teardown function: +全局初始化文件可以导出命名的 `setup` 和 `teardown` 函数,或者导出一个返回 `teardown` 函数的 `default` 函数: ::: code-group ```js [exports] @@ -32,12 +32,12 @@ export default function setup(project) { ``` ::: -Note that the `setup` method and a `default` function receive a [test project](/api/advanced/test-project) as the first argument. The global setup is called before the test workers are created and only if there is at least one test queued, and teardown is called after all test files have finished running. In [watch mode](/config/watch), the teardown is called before the process is exited instead. If you need to reconfigure your setup before the test rerun, you can use [`onTestsRerun`](#handling-test-reruns) hook instead. +注意,`setup` 方法和 `default` 函数接收一个 [测试项目](/api/advanced/test-project) 作为第一个参数。全局初始化在创建测试工作线程之前调用,且仅当至少有一个测试排队时才会调用;清理在所有测试文件运行完成后调用。在 [watch 模式](/config/watch) 中,清理会在进程退出之前调用。如果你需要在测试重新运行前重新配置初始化,可以使用 [`onTestsRerun`](#handling-test-reruns) 钩子。 -Multiple global setup files are possible. `setup` and `teardown` are executed sequentially with teardown in reverse order. +可以存在多个全局初始化文件。`setup` 和 `teardown` 会按顺序执行,清理则以相反顺序执行。 ::: danger -Beware that the global setup is running in a different global scope before test workers are even created, so your tests don't have access to global variables defined here. However, you can pass down serializable data to tests via [`provide`](/config/provide) method and read them in your tests via `inject` imported from `vitest`: +注意,全局初始化在测试工作线程创建之前运行于不同的全局作用域,因此你的测试无法访问在此处定义的全局变量。但你可以通过 [`provide`](/config/provide) 方法将可序列化的数据传递给测试,并在测试中通过从 `vitest` 导入的 `inject` 读取: :::code-group ```ts [example.test.ts] @@ -59,12 +59,12 @@ declare module 'vitest' { } ``` -If you need to execute code in the same process as tests, use [`setupFiles`](/config/setupfiles) instead, but note that it runs before every test file. +如果你需要在与测试相同的线程中执行代码,请使用 [`setupFiles`](/config/setupfiles),但请注意它会在每个测试文件之前运行。 ::: -## Handling Test Reruns +## 处理测试重新运行 {#handling-test-reruns} -You can define a custom callback function to be called when Vitest reruns tests. The test runner will wait for it to complete before executing tests. Note that you cannot destruct the `project` like `{ onTestsRerun }` because it relies on the context. +你可以定义一个自定义回调函数,在 `Vitest` 重新运行测试时调用。测试运行器会等待它完成后再执行测试。注意,你不能解构 `project`,例如 `{ onTestsRerun }`,因为它依赖于上下文。 ```ts [globalSetup.ts] import type { TestProject } from 'vitest/node' diff --git a/config/hideskippedtests.md b/config/hideskippedtests.md index 9f63b0c5..c7f2143f 100644 --- a/config/hideskippedtests.md +++ b/config/hideskippedtests.md @@ -1,12 +1,12 @@ --- -title: hideSkippedTests | Config +title: hideSkippedTests | 配置 outline: deep --- # hideSkippedTests -- **Type:** `boolean` -- **CLI:** `--hideSkippedTests`, `--hide-skipped-tests` -- **Default:** `false` +- **类型:** `boolean` +- **命令行终端:** `--hideSkippedTests`, `--hide-skipped-tests` +- **默认值:** `false` -Hide logs for skipped tests +隐藏跳测试的日志记录。 diff --git a/config/hooktimeout.md b/config/hooktimeout.md index 0f12419f..60b8e38b 100644 --- a/config/hooktimeout.md +++ b/config/hooktimeout.md @@ -1,5 +1,5 @@ --- -title: hookTimeout | Config +title: hookTimeout | 配置 outline: deep --- diff --git a/config/include-source.md b/config/include-source.md index abe287c6..8163cd52 100644 --- a/config/include-source.md +++ b/config/include-source.md @@ -1,23 +1,23 @@ --- -title: includeSource | Config +title: includeSource | 配置 --- # includeSource -- **Type:** `string[]` -- **Default:** `[]` +- **类型:** `string[]` +- **默认值:** `[]` -A list of [glob patterns](https://superchupu.dev/tinyglobby/comparison) that match your [in-source test files](/guide/in-source). These patterns are resolved relative to the [`root`](/config/root) ([`process.cwd()`](https://nodejs.org/api/process.html#processcwd) by default). +匹配包含内联测试文件的 [glob 规则](https://superchupu.dev/tinyglobby/comparison)。该规则相对于 [`root`](/config/root) 进行解析(默认为 [`process.cwd()`](https://nodejs.org/api/process.html#processcwd))。 -When defined, Vitest will run all matched files that have `import.meta.vitest` inside. +当定义时,Vitest 将运行所有包含 `import.meta.vitest` 的匹配文件。 ::: warning -Vitest performs a simple text-based inclusion check on source files. If a file contains `import.meta.vitest`, even in a comment, it will be matched as an in-source test file. +Vitest 对源文件执行基于文本的包含的简单检查。如果文件即使在注释中包含 `import.meta.vitest`,它也会被匹配为源文件内联测试。 ::: -Vitest uses the [`tinyglobby`](https://npmx.dev/package/tinyglobby) package to resolve the globs. +Vitest 使用 [`tinyglobby`](https://npmx.dev/package/tinyglobby) 包来解析 glob。 -## Example +## 示例 {#example} ```js import { defineConfig } from 'vitest/config' @@ -29,14 +29,14 @@ export default defineConfig({ }) ``` -Then you can write tests inside your source files: +然后你可以在源文件中编写测试: ```ts [src/index.ts] export function add(...args: number[]) { return args.reduce((a, b) => a + b, 0) } -// #region in-source test suites +// #region 内联测试套件 if (import.meta.vitest) { const { it, expect } = import.meta.vitest it('add', () => { @@ -48,7 +48,7 @@ if (import.meta.vitest) { // #endregion ``` -For your production build, you need to replace the `import.meta.vitest` with `undefined`, letting the bundler do the dead code elimination. +在生产环境构建时,你需要将 `import.meta.vitest` 替换为 `undefined`,以便打包工具移除未使用的代码。 ::: code-group ```js [vite.config.ts] @@ -80,7 +80,7 @@ export default { 'import.meta.vitest': 'undefined', // [!code ++] }) // [!code ++] ], - // other options + // 其他配置项 } ``` ```js [build.config.js] @@ -90,7 +90,7 @@ export default defineBuildConfig({ replace: { // [!code ++] 'import.meta.vitest': 'undefined', // [!code ++] }, // [!code ++] - // other options + // 其他配置项 }) ``` ```js [webpack.config.js] @@ -107,7 +107,7 @@ module.exports = { ::: ::: tip -To get TypeScript support for `import.meta.vitest`, add `vitest/importMeta` to your `tsconfig.json`: +为了让 `import.meta.vitest` 获得更好的 TypeScript 支持,请在 `tsconfig.json` 中添加 `vitest/importMeta`: ```json [tsconfig.json] { diff --git a/config/include.md b/config/include.md index ac0b8b76..24e87027 100644 --- a/config/include.md +++ b/config/include.md @@ -1,22 +1,22 @@ --- -title: include | Config +title: include | 配置 --- # include -- **Type:** `string[]` -- **Default:** `['**/*.{test,spec}.?(c|m)[jt]s?(x)']` -- **CLI:** `vitest [...include]`, `vitest **/*.test.js` +- **类型:** `string[]` +- **默认值:** `['**/*.{test,spec}.?(c|m)[jt]s?(x)']` +- **命令行终端:** `vitest [...include]`, `vitest **/*.test.js` -A list of [glob patterns](https://superchupu.dev/tinyglobby/comparison) that match your test files. These patterns are resolved relative to the [`root`](/config/root) ([`process.cwd()`](https://nodejs.org/api/process.html#processcwd) by default). +匹配包含测试文件的 [glob 规则](https://superchupu.dev/tinyglobby/comparison)。该规则相对于 [`root`](/config/root) 进行解析(默认为 [`process.cwd()`](https://nodejs.org/api/process.html#processcwd))。 -Vitest uses the [`tinyglobby`](https://npmx.dev/package/tinyglobby) package to resolve the globs. +Vitest 使用 [`tinyglobby`](https://npmx.dev/package/tinyglobby) 包来解析 glob。 -::: tip NOTE -When using coverage, Vitest automatically adds test files `include` patterns to coverage's default `exclude` patterns. See [`coverage.exclude`](/config/coverage#exclude). +::: tip 注意 +运行覆盖率测试时,Vitest 会自动将测试文件的 `include` 模式添加到覆盖率默认的 `exclude` 模式中。请参阅 [`coverage.exclude`](/config/coverage#exclude)。 ::: -## Example +## 示例 {#example} ```js import { defineConfig } from 'vitest/config' @@ -31,7 +31,7 @@ export default defineConfig({ }) ``` -Vitest provides reasonable defaults, so normally you wouldn't override them. A good example of defining `include` is for [test projects](/guide/projects): +Vitest 默认提供了合理的值,通常情况下无需覆盖。`include` 典型使用场景是定义 [测试项目](/guide/projects): ```js{8,12} [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -57,7 +57,7 @@ export default defineConfig({ ``` ::: warning -This option will override Vitest defaults. If you just want to extend them, use `configDefaults` from `vitest/config`: +此选项会覆盖 Vitest 的默认值。如果只想在默认值基础上扩展,请使用 `vitest/config` 中的 `configDefaults`: ```js{6} import { configDefaults, defineConfig } from 'vitest/config' diff --git a/config/includetasklocation.md b/config/includetasklocation.md index e830028c..8ef8b12a 100644 --- a/config/includetasklocation.md +++ b/config/includetasklocation.md @@ -1,22 +1,22 @@ --- -title: includeTaskLocation | Config +title: includeTaskLocation | 配置 outline: deep --- # includeTaskLocation -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Should `location` property be included when Vitest API receives tasks in [reporters](/config/reporters). If you have a lot of tests, this might cause a small performance regression. +当 Vitest API 在 [报告器](/config/reporters) 中接收任务时,是否包含 `location` 属性。如果测试数量较多,此功能可能导致轻微性能下降。 -The `location` property has `column` and `line` values that correspond to the `test` or `describe` position in the original file. +`location` 属性包含对应原始文件中 `test` 或 `describe` 位置的 `column`(列)和 `line`(行)数值。 -This option will be auto-enabled if you don't disable it explicitly, and you are running Vitest with: -- [Vitest UI](/guide/ui) -- or using the [Browser Mode](/guide/browser/) without [headless](/guide/browser/#headless) mode -- or using [HTML Reporter](/guide/reporters#html-reporter) +以下情况将自动启用此选项(除非显式禁用): +- 运行 [UI 模式](/guide/ui) +- 使用 [浏览器模式](/guide/browser/) 且未启用 [无头模式](/guide/browser/#headless) +- 使用 [HTML 报告器](/guide/reporters#html-reporter) ::: tip -This option has no effect if you do not use custom code that relies on this. +如果未编写依赖此属性的自定义代码,该选项不会产生实际影响。 ::: diff --git a/config/isolate.md b/config/isolate.md index a92f055e..eb751bb5 100644 --- a/config/isolate.md +++ b/config/isolate.md @@ -1,18 +1,18 @@ --- -title: isolate | Config +title: isolate | 配置 outline: deep --- # isolate -- **Type:** `boolean` -- **Default:** `true` -- **CLI:** `--no-isolate`, `--isolate=false` +- **类型:** `boolean` +- **默认值:** `true` +- **命令行终端:** `--no-isolate`, `--isolate=false` -Run tests in an isolated environment. This option has no effect on `vmThreads` and `vmForks` pools. +在隔离环境中运行测试。此选项对 `vmThreads` 和 `vmForks` 线程池没有影响。 -Disabling this option might [improve performance](/guide/improving-performance) if your code doesn't rely on side effects (which is usually true for projects with `node` environment). +如果你的代码不依赖副作用(通常适用于 `node` 环境的项目),禁用此选项可能 [提升性能](/guide/improving-performance)。 ::: tip -You can disable isolation for specific test files by using Vitest workspaces and disabling isolation per project. +可通过 Vitest 工作区为特定测试文件禁用隔离,或按项目单独配置隔离设置。 ::: diff --git a/config/logheapusage.md b/config/logheapusage.md index a29f251c..5e6304a5 100644 --- a/config/logheapusage.md +++ b/config/logheapusage.md @@ -1,12 +1,12 @@ --- -title: logHeapUsage | Config +title: logHeapUsage | 配置 outline: deep --- # logHeapUsage -- **Type**: `boolean` -- **Default**: `false` -- **CLI:** `--logHeapUsage`, `--logHeapUsage=false` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--logHeapUsage`, `--logHeapUsage=false` -Show heap usage after each test. Useful for debugging memory leaks. +在每次测试后显示堆使用情况。适用于调试内存泄漏。 diff --git a/config/maxconcurrency.md b/config/maxconcurrency.md index deb88476..8db782db 100644 --- a/config/maxconcurrency.md +++ b/config/maxconcurrency.md @@ -1,14 +1,14 @@ --- -title: maxConcurrency | Config +title: maxConcurrency | 配置 outline: deep --- # maxConcurrency -- **Type**: `number` -- **Default**: `5` -- **CLI**: `--max-concurrency=10`, `--maxConcurrency=10` +- **类型:** `number` +- **默认值:** `5` +- **命令行终端:** `--max-concurrency=10`, `--maxConcurrency=10` -The maximum number of tests and hooks that can run at the same time when using `test.concurrent` or `describe.concurrent`. +使用 `test.concurrent` 或 `describe.concurrent` 时,可以同时运行的测试和钩子的最大并发数量。 -The hook execution order within a single group is also controlled by [`sequence.hooks`](/config/sequence#sequence-hooks). With `sequence.hooks: 'parallel'`, the execution is bounded by the same limit of [`maxConcurrency`](/config/maxconcurrency). +单个组内的钩子执行顺序也由 [`sequence.hooks`](/config/sequence#sequence-hooks) 控制。当 `sequence.hooks: 'parallel'` 时,执行也会受到 [`maxConcurrency`](/config/maxconcurrency) 相同限制的约束。 diff --git a/config/maxworkers.md b/config/maxworkers.md index 4aa63778..8d7fb9d1 100644 --- a/config/maxworkers.md +++ b/config/maxworkers.md @@ -1,23 +1,23 @@ --- -title: maxWorkers | Config +title: maxWorkers | 配置 outline: deep --- # maxWorkers -- **Type:** `number | string` -- **Default:** - - if [`watch`](/config/watch) is disabled, uses all available parallelism - - if [`watch`](/config/watch) is enabled, uses half of all available parallelism +- **类型:** `number | string` +- **默认值:** + - 如果禁用 [`watch`](/config/watch),并发数量为系统全部可用并发数量 + - 如果启用 [`watch`](/config/watch),并发数量为系统全部可用并发数量的一半 -Defines the maximum concurrency for test workers. Accepts either a number or a percentage string. +定义测试工作线程的最大并发数。可接受数值或百分比字符串作为参数: -- Number: spawns up to the specified number of workers. -- Percentage string (e.g., "50%"): computes the worker count as the given percentage of the machine’s available parallelism. +- 数值:最多启动指定数量的工作线程 +- 百分比字符串(例如 "50%"):基于机器剩余可用并发数量,折算指定百分比数量的工作线程 -## Example +## 示例 {#example} -### Number +### 数值 {#number} ::: code-group ```js [vitest.config.js] @@ -34,7 +34,7 @@ vitest --maxWorkers=4 ``` ::: -### Percent +### 百分比 {#percent} ::: code-group ```js [vitest.config.js] @@ -51,4 +51,4 @@ vitest --maxWorkers=50% ``` ::: -Vitest uses [`os.availableParallelism`](https://nodejs.org/api/os.html#osavailableparallelism) to know the maximum amount of parallelism available. +Vitest 通过 [`os.availableParallelism`](https://nodejs.org/api/os.html#osavailableparallelism) 接口获取系统可用的最大并发数量。 diff --git a/config/mockreset.md b/config/mockreset.md index 15259293..aa33dcb8 100644 --- a/config/mockreset.md +++ b/config/mockreset.md @@ -1,16 +1,16 @@ --- -title: mockReset | Config +title: mockReset | 配置 outline: deep --- # mockReset -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Should Vitest automatically call [`vi.resetAllMocks()`](/api/vi#vi-resetallmocks) before each test. +是否在每个测试前自动调用 [`vi.resetAllMocks()`](/api/vi#vi-resetallmocks)。 -This will clear mock history and reset each implementation. +这将清除模拟历史记录,并将每个实现重置为其原始状态。 ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -23,5 +23,5 @@ export default defineConfig({ ``` ::: warning -Be aware that this option may cause problems with async [concurrent tests](/api/test#test-concurrent). If enabled, the completion of one test will clear the mock history and implementation for all mocks, including those currently being used by other tests in progress. +需要注意的是此选项可能会影响异步 [并发测试](/api/test#test-concurrent) 的正常运行。启用后,当某个测试执行完成时,会清除所有模拟函数的调用历史记录,包括其他并发测试正在使用的模拟函数。 ::: diff --git a/config/mode.md b/config/mode.md index 5e45a97e..55a55d56 100644 --- a/config/mode.md +++ b/config/mode.md @@ -1,12 +1,12 @@ --- -title: mode | Config +title: mode | 配置 outline: deep --- # mode -- **Type:** `string` -- **CLI:** `--mode=staging` -- **Default:** `'test'` +- **类型:** `string` +- **命令行终端:** `--mode=staging` +- **默认值:** `'test'` -Overrides Vite mode +覆盖 Vite 模式。 diff --git a/config/name.md b/config/name.md index 26b8c6fa..7007ea70 100644 --- a/config/name.md +++ b/config/name.md @@ -1,10 +1,10 @@ --- -title: name | Config +title: name | 配置 --- # name -- **Type:** +- **类型:** ```ts interface UserConfig { @@ -12,13 +12,13 @@ interface UserConfig { } ``` -Assign a custom name to the test project or Vitest process. The name will be visible in the CLI and UI, and available in the Node.js API via [`project.name`](/api/advanced/test-project#name). + 你可以为测试项目或 Vitest 进程分配一个自定义名称。该名称将显示在命令行页面(CLI)和 UI 模式中,同时也可以通过 Node.js API 中的 project.name [`project.name`](/api/advanced/test-project#name) 访问。 -The color used by the CLI and UI can be changed by providing an object with a `color` property. +通过提供包含 `color` 属性的对象,可以改变命令行页面(CLI) 和 UI 模式使用的颜色。 -## Colors +## 颜色 {#colors} -The displayed colors depend on your terminal’s color scheme. In the UI, colors match their CSS equivalents. +最终显示的颜色取决于你的终端配色方案。在 UI 模式中,颜色与其对应的 CSS 值相同。 - black - red @@ -29,7 +29,7 @@ The displayed colors depend on your terminal’s color scheme. In the UI, colors - cyan - white -## Example +## 示例 {#example} ::: code-group ```js [string] @@ -55,7 +55,7 @@ export default defineConfig({ ``` ::: -This property is mostly useful if you have several projects as it helps distinguish them in your terminal: +当你有多个项目时,这个属性适用于在终端中区分它们: ```js{7,11} [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -77,18 +77,19 @@ export default defineConfig({ ``` ::: tip -Vitest automatically assigns a name when none is provided. Resolution order: +Vitest 在未提供名称时会自动分配一个名称。分配顺序如下: -- If the project is specified by a config file or directory, Vitest uses the package.json's `name` field. -- If there is no `package.json`, Vitest falls back to the project folder's basename. -- If the project is defined inline in the `projects` array (an object), Vitest assigns a numeric name equal to that project's array index (0-based). +- 如果项目对应一个配置文件或目录,Vitest 会使用该项目 package.json 的 `name` 字段。 +- 如果没有 `package.json`,Vitest 会降级到项目文件夹的名称。 +- 如果项目在 `projects` 数组中直接定义为一个对象,Vitest 会为其分配一个数字名称,该数字对应该项目在数组中的位置(从 0 开始)。 ::: ::: warning -Note that projects cannot have the same name. Vitest will throw an error during the config resolution. +需注意,项目不能有相同的名称。Vitest 将在配置解析过程中抛出错误。 ::: -You can also assign different names to different browser [instances](/config/browser/instances): +你也可以为不同的浏览器 [实例](/config/browser/instances) 分配不同的名称: + ```js{10,11} [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -109,7 +110,7 @@ export default defineConfig({ ``` ::: tip -Browser instances inherit their parent project's name with the browser name appended in parentheses. For example, a project named `browser` with a chromium instance will be shown as `browser (chromium)`. +浏览器实例会继承其父项目的名称,并在括号中追加浏览器名称。例如,一个名为 `browser` 的项目,其 chromium 实例会显示为 ` browser (chromium)`。 -If the parent project has no name, or instances are defined at the root level (not inside a named project), the instance name defaults to the browser value (e.g. `chromium`). To override this behavior, set an explicit `name` on the instance. +如果父项目没有名称,或实例定义在根级别而非项目内部,实例名称会默认为浏览器值(例如 `chromium`)。要覆盖当前行为,可以在实例上显式地设置 `name` 属性。 ::: diff --git a/config/onconsolelog.md b/config/onconsolelog.md index bd4d3417..8b71fae5 100644 --- a/config/onconsolelog.md +++ b/config/onconsolelog.md @@ -1,5 +1,5 @@ --- -title: onConsoleLog | Config +title: onConsoleLog | 配置 outline: deep --- @@ -13,9 +13,9 @@ function onConsoleLog( ): boolean | void ``` -Custom handler for `console` methods in tests. If you return `false`, Vitest will not print the log to the console. Note that Vitest ignores all other falsy values. +用于自定义处理测试中调用的 `console` 方法。若返回 `false`,Vitest 将不会将该日志打印到控制台。Vitest 会忽略除 false 之外的其他假值。 -Can be useful for filtering out logs from third-party libraries. +此功能适用于过滤第三方库产生的日志。 ```ts import { defineConfig } from 'vitest/config' diff --git a/config/onstacktrace.md b/config/onstacktrace.md index cdc5a994..08f342d2 100644 --- a/config/onstacktrace.md +++ b/config/onstacktrace.md @@ -1,5 +1,5 @@ --- -title: onStackTrace | Config +title: onStackTrace | 配置 outline: deep --- diff --git a/config/onunhandlederror.md b/config/onunhandlederror.md index ec7b2dbe..9bbf767d 100644 --- a/config/onunhandlederror.md +++ b/config/onunhandlederror.md @@ -1,11 +1,11 @@ --- -title: onUnhandledError | Config +title: onUnhandledError | 配置 outline: deep --- # onUnhandledError 4.0.0 -- **Type:** +- **类型:** ```ts function onUnhandledError( @@ -13,15 +13,15 @@ function onUnhandledError( ): boolean | void ``` -A custom callback for filtering unhandled errors that should not be reported. When an error is filtered out, it no longer affects the result of the test run. +用于过滤不应上报的未处理错误的自定义回调函数。当错误被过滤后,将不再影响测试运行结果。 -To report unhandled errors without affecting the test outcome, use the [`dangerouslyIgnoreUnhandledErrors`](/config/dangerouslyignoreunhandlederrors) option instead. +如需上报未处理错误但不影响测试结果,请改用 [`dangerouslyIgnoreUnhandledErrors`](/config/dangerouslyignoreunhandlederrors) 选项。 ::: tip -This callback is called on the main thread, it doesn't have access to your test context. +此回调函数在主线程调用,无法访问你的测试上下文。 ::: -## Example +## 示例 {#example} ```ts import type { ParsedStack } from 'vitest' @@ -30,7 +30,7 @@ import { defineConfig } from 'vitest/config' export default defineConfig({ test: { onUnhandledError(error): boolean | void { - // Ignore all errors with the name "MySpecialError". + // 忽略所有名称为 "MySpecialError" 的报错 if (error.name === 'MySpecialError') { return false } diff --git a/config/open.md b/config/open.md index 44c2fc40..cd1979c4 100644 --- a/config/open.md +++ b/config/open.md @@ -1,5 +1,5 @@ --- -title: open | Config +title: open | 配置 outline: deep --- diff --git a/config/outputfile.md b/config/outputfile.md index fc87b029..68ab3fb6 100644 --- a/config/outputfile.md +++ b/config/outputfile.md @@ -1,12 +1,11 @@ --- -title: outputFile | Config +title: outputFile | 配置 outline: deep --- # outputFile {#outputfile} -- **Type:** `string | Record` -- **CLI:** `--outputFile=`, `--outputFile.json=./path` +- **类型:** `string | Record` +- **命令行终端:** `--outputFile=`, `--outputFile.json=./path` -Write test results to a file when the `--reporter=json`, `--reporter=html` or `--reporter=junit` option is also specified. -By providing an object instead of a string you can define individual outputs when using multiple reporters. +当指定 `--reporter=json`、`--reporter=html` 或 `--reporter=junit` 时,将测试结果写入文件。通过提供对象而非字符串,你可以在使用多个报告器时定义各自的输出配置。 diff --git a/config/passwithnotests.md b/config/passwithnotests.md index eb4bbe2e..2eac469a 100644 --- a/config/passwithnotests.md +++ b/config/passwithnotests.md @@ -1,12 +1,12 @@ --- -title: passWithNoTests | Config +title: passWithNoTests | 配置 outline: deep --- # passWithNoTests -- **Type**: `boolean` -- **Default**: `false` -- **CLI:** `--passWithNoTests`, `--passWithNoTests=false` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--passWithNoTests`, `--passWithNoTests=false` -Vitest will not fail, if no tests will be found. +如果未发现任何测试,Vitest 不会报错。 diff --git a/config/pool.md b/config/pool.md index c9449818..a46a0473 100644 --- a/config/pool.md +++ b/config/pool.md @@ -1,34 +1,34 @@ --- -title: pool | Config +title: pool | 配置 outline: deep --- # pool -- **Type:** `'threads' | 'forks' | 'vmThreads' | 'vmForks'` -- **Default:** `'forks'` -- **CLI:** `--pool=threads` +- **类型:** `'threads' | 'forks' | 'vmThreads' | 'vmForks'` +- **默认值:** `'forks'` +- **命令行终端:** `--pool=threads` -Pool used to run tests in. +用于运行测试的线程池。 ## 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. +启用多线程。使用 threads 线程池时,你无法使用与进程相关的 API,如 `process.chdir()`。某些用原生语言编写的库(如`Prisma`、`bcrypt` 和 `canvas`)在多线程中运行时存在问题,容易导致段错误。在这些情况下,建议改用 `forks` 线程池。 ## forks -Similar as `threads` pool but uses `child_process` instead of `worker_threads`. Communication between tests and main process is not as fast as with `threads` pool. Process related APIs such as `process.chdir()` are available in `forks` pool. +类似于 `threads` 线程池,但使用 `child_process` 代替 `worker_threads`。测试与主进程之间的通信不如 `threads` 线程池快。在 `forks` 线程池中可以使用与进程相关的 API,如 `process.chdir()`。 ## vmThreads -Run tests using [VM context](https://nodejs.org/api/vm.html) (inside a sandboxed environment) in a `threads` pool. +使用 [VM 上下文](https://nodejs.org/api/vm.html)(在沙箱环境中)在 `threads` 线程池中运行测试。 -This makes tests run faster, but the VM module is unstable when running [ESM code](https://github.com/nodejs/node/issues/37648). Your tests will [leak memory](https://github.com/nodejs/node/issues/33439) - to battle that, consider manually editing [`vmMemoryLimit`](/config/vmmemorylimit) value. +这使得测试运行速度更快,但 VM 模块在运行 [ESM 代码](https://github.com/nodejs/node/issues/37648) 时不稳定。你的测试可能会 [泄漏内存](https://github.com/nodejs/node/issues/33439),为了解决这个问题,考虑手动设置 [`vmMemoryLimit`](/config/vmmemorylimit) 阈值。 ::: warning -Running code in a sandbox has some advantages (faster tests), but also comes with a number of disadvantages. +在沙箱中运行代码有一些优势(测试速度更快),但也存在一些劣势。 -- The globals within native modules, such as (`fs`, `path`, etc), differ from the globals present in your test environment. As a result, any error thrown by these native modules will reference a different Error constructor compared to the one used in your code: +- 原生模块(如 `fs`、`path` 等)内的全局变量与你的测试环境中存在的全局变量不同。因此,这些原生模块抛出的任何错误都会引用一个与你的代码中使用的 Error 构造函数不同的构造函数: ```ts try { @@ -39,12 +39,12 @@ catch (err) { } ``` -- Importing ES modules caches them indefinitely which introduces memory leaks if you have a lot of contexts (test files). There is no API in Node.js that clears that cache. -- Accessing globals [takes longer](https://github.com/nodejs/node/issues/31658) in a sandbox environment. +- 导入 ES 模块会导致其被永久缓存,当存在大量上下文(测试文件)时,将引发内存泄漏问题。Node.js 目前未提供清除该缓存的API接口。 +- 在沙箱环境中访问全局变量 [耗时更长](https://github.com/nodejs/node/issues/31658)。 -Please, be aware of these issues when using this option. Vitest team cannot fix any of the issues on our side. +使用此选项时,需要注意这些问题。Vitest 团队无法解决上诉问题。 ::: ## vmForks -Similar as `vmThreads` pool but uses `child_process` instead of `worker_threads`. Communication between tests and the main process is not as fast as with `vmThreads` pool. Process related APIs such as `process.chdir()` are available in `vmForks` pool. Please be aware that this pool has the same pitfalls listed in `vmThreads`. +类似于 `vmThreads` 线程池,但使用 `child_process` 代替 `worker_threads`。测试与主进程之间的通信不如 `vmThreads` 线程池快。在 `vmForks` 线程池中可以使用与进程相关的 API,如 `process.chdir()`。请注意,此线程池具有 `vmThreads` 中列出的相同缺陷。 diff --git a/config/printconsoletrace.md b/config/printconsoletrace.md index 8552b6cd..d683d156 100644 --- a/config/printconsoletrace.md +++ b/config/printconsoletrace.md @@ -1,11 +1,11 @@ --- -title: printConsoleTrace | Config +title: printConsoleTrace | 配置 outline: deep --- # printConsoleTrace -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` Always print console traces when calling any `console` method. This is useful for debugging. diff --git a/config/projects.md b/config/projects.md index 761861d1..4ecce451 100644 --- a/config/projects.md +++ b/config/projects.md @@ -1,11 +1,11 @@ --- -title: projects | Config +title: projects | 配置 outline: deep --- # projects -- **Type:** `TestProjectConfiguration[]` -- **Default:** `[]` +- **类型:** `TestProjectConfiguration[]` +- **默认值:** `[]` -An array of [projects](/guide/projects). +一个由多个 [项目](/guide/projects) 组成的数组。 diff --git a/config/provide.md b/config/provide.md index 6eb1347b..8972fe63 100644 --- a/config/provide.md +++ b/config/provide.md @@ -1,13 +1,13 @@ --- -title: provide | Config +title: provide | 配置 outline: deep --- # provide -- **Type:** `Partial` +- **类型:** `Partial` -Define values that can be accessed inside your tests using `inject` method. +定义可以使用 `inject` 方法在测试内部访问的值。 :::code-group ```ts [vitest.config.js] @@ -31,11 +31,11 @@ test('api key is defined', () => { ::: ::: warning -Properties have to be strings and values need to be [serializable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types) because this object will be transferred between different processes. +属性须为字符串,且值需为 [可序列化类型](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types),因为该对象将在不同进程间传输。 ::: ::: tip -If you are using TypeScript, you will need to augment `ProvidedContext` type for type safe access: +如果你正在使用 TypeScript,可以扩展 `ProvidedContext` 类型以实现类型安全的访问: ```ts [vitest.shims.d.ts] declare module 'vitest' { @@ -44,7 +44,7 @@ declare module 'vitest' { } } -// mark this file as a module so augmentation works correctly +// 将此文件标记为模块以确保类型正常生效 export {} ``` ::: diff --git a/config/reporters.md b/config/reporters.md index 6c9b3335..f9f8f018 100644 --- a/config/reporters.md +++ b/config/reporters.md @@ -1,10 +1,10 @@ --- -title: reporters | Config +title: reporters | 配置 --- # reporters -- **Type:** +- **类型:** ```ts interface UserConfig { @@ -14,22 +14,22 @@ interface UserConfig { type ConfigReporter = string | Reporter | [string, object?] ``` -- **Default:** [`'default'`](/guide/reporters#default-reporter) (or [['default'](/guide/reporters#default-reporter), ['github-actions'](/guide/reporters#github-actions-reporter)] when `process.env.GITHUB_ACTIONS === 'true'`) -- **CLI:** - - `--reporter=tap` for a single reporter - - `--reporter=verbose --reporter=github-actions` for multiple reporters +- **默认值:** [`'default'`](/guide/reporters#default-reporter)(当 `process.env.GITHUB_ACTIONS === 'true'` 时为 [['default'](/guide/reporters#default-reporter), ['github-actions'](/guide/reporters#github-actions-reporter)]) +- **命令行终端:** + - `--reporter=tap` 用于单个报告器 + - `--reporter=verbose --reporter=github-actions` 用于多个报告器 -This option defines a single reporter or a list of reporters available to Vitest during the test run. +此选项定义在 Vitest 测试运行期间可用的单个报告器或报告器列表。 -Alongside built-in reporters, you can also pass down a custom implementation of a [`Reporter` interface](/api/advanced/reporters), or a path to a module that exports it as a default export (e.g. `'./path/to/reporter.ts'`, `'@scope/reporter'`). +除了内置报告器,你也可以传入 [`Reporter` 接口](/api/advanced/reporters) 的自定义实现,或指向导出该接口默认导出的模块路径(例如:`'./path/to/reporter.ts'`, `'@scope/reporter'`)。 -You can configure a reporter by providing a tuple: `[string, object]`, where the string is a reporter name, and the object is the reporter's options. +你可以通过提供一个元组来配置报告器:`[string, object]`,其中字符串是报告器名称,对象是报告器配置选项。 ::: warning -Note that the [coverage](/guide/coverage) feature uses a different [`coverage.reporter`](/config/coverage#reporter) option instead of this one. +注意 [coverage](/guide/coverage) 功能使用了不同的 [`coverage.reporter`](/config/coverage#reporter) 选项。 ::: -## Built-in Reporters +## 内置报告器 {#built-in-reporters} - [`default`](/guide/reporters#default-reporter) - [`verbose`](/guide/reporters#verbose-reporter) @@ -45,7 +45,7 @@ Note that the [coverage](/guide/coverage) feature uses a different [`coverage.re - [`agent`](/guide/reporters#agent-reporter) - [`blob`](/guide/reporters#blob-reporter) -## Example +## 示例 {#example} ::: code-group ```js [vitest.config.js] @@ -55,10 +55,10 @@ export default defineConfig({ test: { reporters: [ 'default', - // conditional reporter + // 条件报告器 process.env.CI ? 'github-actions' : {}, - // custom reporter from npm package - // options are passed down as a tuple + // 来自 npm 包的自定义报告器 + // 选项将以元组形式向下传递 [ 'vitest-sonar-reporter', { outputFile: 'sonar-report.xml' } diff --git a/config/resolvesnapshotpath.md b/config/resolvesnapshotpath.md index 1baa472f..85f6aaad 100644 --- a/config/resolvesnapshotpath.md +++ b/config/resolvesnapshotpath.md @@ -1,5 +1,5 @@ --- -title: resolveSnapshotPath | Config +title: resolveSnapshotPath | 配置 outline: deep --- @@ -20,7 +20,7 @@ export default defineConfig({ }) ``` -你还可以使用 `context` 参数来访问项目的序列化配置。当你配置了多个 [项目](/guide/projects) 并希望根据项目名称将快照存储在不同位置时,这很有用: +你也可以使用 `context` 参数来访问项目的序列化配置。适用于有多个 [项目](/guide/projects) 并想要根据项目名称在不同位置存储快照的场景: ```ts import { basename, dirname, join } from 'node:path' diff --git a/config/restoremocks.md b/config/restoremocks.md index 818942c1..469c13e8 100644 --- a/config/restoremocks.md +++ b/config/restoremocks.md @@ -1,16 +1,16 @@ --- -title: restoreMocks | Config +title: restoreMocks | 配置 outline: deep --- # restoreMocks -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Should Vitest automatically call [`vi.restoreAllMocks()`](/api/vi#vi-restoreallmocks) before each test. +是否应在每个测试前自动调用 [`vi.restoreAllMocks()`](/api/vi#vi-restoreallmocks)。 -This restores all original implementations on spies created manually with [`vi.spyOn`](/api/vi#vi-spyon). +此操作会恢复所有通过 [`vi.spyOn`](/api/vi#vi-spyon) 手动创建的 spy 函数的原始实现。 ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -23,5 +23,5 @@ export default defineConfig({ ``` ::: warning -Be aware that this option may cause problems with async [concurrent tests](/api/test#test-concurrent). If enabled, the completion of one test will restore the implementation for all spies, including those currently being used by other tests in progress. +需要注意的是此选项可能会影响异步 [并发测试](/api/test#test-concurrent) 的正常运行。启用后,当某个测试执行完成时,会重置所有 spy 函数的实现,包括其他并发测试正在使用的 spy 函数。 ::: diff --git a/config/retry.md b/config/retry.md index 65d928a8..bcca4161 100644 --- a/config/retry.md +++ b/config/retry.md @@ -1,21 +1,19 @@ --- -title: retry | Config +title: retry | 配置 outline: deep --- # retry - +如果测试失败,重试指定次数。 -Retry the test specific number of times if it fails. +- **类型:** `number | { count?: number, delay?: number, condition?: RegExp }` +- **默认值:** `0` +- **命令行终端:** `--retry `, `--retry.count `, `--retry.delay `, `--retry.condition ` -- **Type:** `number | { count?: number, delay?: number, condition?: RegExp }` -- **Default:** `0` -- **CLI:** `--retry `, `--retry.count `, `--retry.delay `, `--retry.condition ` +## 基础用法 {#basic-usage} -## Basic Usage - -Specify a number to retry failed tests: +设置失败测试用例的重试次数。 ```ts export default defineConfig({ @@ -25,29 +23,29 @@ export default defineConfig({ }) ``` -## CLI Usage +## 命令行用法 {#cli-usage} -You can also configure retry options from the command line: +你也可以通过命令行配置重试选项: ```bash -# Simple retry count +# 简单重试次数配置 vitest --retry 3 -# Advanced options using dot notation +# 使用点符号配置高级选项 vitest --retry.count 3 --retry.delay 500 --retry.condition 'ECONNREFUSED|timeout' ``` -## Advanced Options 4.1.0 {#advanced-options} +## 高级选项 4.1.0 {#advanced-options} -Use an object to configure retry behavior: +使用对象来配置重试行为: ```ts export default defineConfig({ test: { retry: { - count: 3, // Number of times to retry - delay: 1000, // Delay in milliseconds between retries - condition: /ECONNREFUSED|timeout/i, // RegExp to match errors that should trigger retry + count: 3, // 重试次数 + delay: 1000, // 重试间隔时间(毫秒) + condition: /ECONNREFUSED|timeout/i, // 触发重试的正则表达式错误匹配规则 }, }, }) @@ -55,7 +53,7 @@ export default defineConfig({ ### count -Number of times to retry a test if it fails. Default is `0`. +如果测试失败,重试的次数。默认值为 `0`。 ```ts export default defineConfig({ @@ -69,14 +67,14 @@ export default defineConfig({ ### delay -Delay in milliseconds between retry attempts. Useful for tests that interact with rate-limited APIs or need time to recover. Default is `0`. +重试间隔时间(毫秒)。适用于需要与限频 API 交互或等待系统恢复的测试场景,默认值为 `0`。 ```ts export default defineConfig({ test: { retry: { count: 3, - delay: 500, // Wait 500ms between retries + delay: 500, // 每次重试间隔 500 毫秒 }, }, }) @@ -84,43 +82,43 @@ export default defineConfig({ ### condition -A RegExp pattern or a function to determine if a test should be retried based on the error. +一个正则表达式模式或函数,用于根据错误判断是否应重试测试。 -- When a **RegExp**, it's tested against the error message -- When a **function**, it receives the error and returns a boolean +- 当使用 **正则表达式** 时,将对错误信息进行匹配测试 +- 当使用 **函数** 时,该函数接收错误对象并返回布尔值 ::: warning -When defining `condition` as a function, it must be done in a test file directly, not in a configuration file (configurations are serialized for worker threads). +如果将 `condition` 定义为函数,必须直接在测试文件中定义,而非配置文件中(配置项会被序列化供工作线程使用)。 ::: -#### RegExp condition (in config file): +#### 正则表达式条件(在配置文件中): {#regexp-condition-in-config-file} ```ts export default defineConfig({ test: { retry: { count: 2, - condition: /ECONNREFUSED|ETIMEDOUT/i, // Retry on connection/timeout errors + condition: /ECONNREFUSED|ETIMEDOUT/i, // 在连接/超时错误时重试 }, }, }) ``` -#### Function condition (in test file): +#### 函数条件(在测试文件中): {#function-condition-in-test-file} ```ts import { describe, test } from 'vitest' describe('tests with advanced retry condition', () => { test('with function condition', { retry: { count: 2, condition: error => error.message.includes('Network') } }, () => { - // test code + // 测试代码 }) }) ``` -## Test File Override +## 测试文件覆盖 {#test-file-override} -You can also define retry options per test or suite in test files: +你也可以在测试文件中为每个测试或测试套件定义重试选项: ```ts import { describe, test } from 'vitest' @@ -132,7 +130,7 @@ describe('flaky tests', { }, }, () => { test('network request', () => { - // test code + // 测试代码 }) }) @@ -142,6 +140,6 @@ test('another test', { condition: error => error.message.includes('timeout'), }, }, () => { - // test code + // 测试代码 }) ``` diff --git a/config/root.md b/config/root.md index 3b4a429c..2dc0e9d9 100644 --- a/config/root.md +++ b/config/root.md @@ -1,11 +1,11 @@ --- -title: root | Config +title: root | 配置 outline: deep --- # root -- **Type:** `string` -- **CLI:** `-r `, `--root=` +- **类型:** `string` +- **命令行终端:** `-r `, `--root=` -Project root +项目的根目录 diff --git a/config/runner.md b/config/runner.md index 931c158d..aacbd269 100644 --- a/config/runner.md +++ b/config/runner.md @@ -1,5 +1,5 @@ --- -title: runner | Config +title: runner | 配置 outline: deep --- diff --git a/config/sequence.md b/config/sequence.md index 51c7276b..58f0fa24 100644 --- a/config/sequence.md +++ b/config/sequence.md @@ -1,15 +1,15 @@ --- -title: sequence | Config +title: sequence | 配置 outline: deep --- # sequence -- **Type**: `{ sequencer?, shuffle?, seed?, hooks?, setupFiles?, groupOrder }` +- **类型:** `{ sequencer?, shuffle?, seed?, hooks?, setupFiles?, groupOrder }` -Options for how tests should be sorted. +控制测试排序方式的选项。 -You can provide sequence options to CLI with dot notation: +你可以通过点符号在 CLI 中提供排序选项: ```sh npx vitest --sequence.shuffle --sequence.seed=1000 @@ -17,31 +17,31 @@ npx vitest --sequence.shuffle --sequence.seed=1000 ## sequence.sequencer -- **Type**: `TestSequencerConstructor` -- **Default**: `BaseSequencer` +- **类型:** `TestSequencerConstructor` +- **默认值:** `BaseSequencer` -A custom class that defines methods for sharding and sorting. You can extend `BaseSequencer` from `vitest/node`, if you only need to redefine one of the `sort` and `shard` methods, but both should exist. +自定义类,用于定义分片和排序方法。如果只需重定义 `sort` 或 `shard` 其中一种方法,可从 `vitest/node` 扩展 `BaseSequencer` 基类,但需确保两个方法同时存在。 -Sharding is happening before sorting, and only if `--shard` option is provided. +分片操作会在排序之前执行,且仅在提供 `--shard` 选项时触发。 -If [`sequence.groupOrder`](#sequence-grouporder) is specified, the sequencer will be called once for each group and pool. +如果指定了 [`sequence.groupOrder`](#sequence-grouporder),该排序器会针对每个测试组和测试池各调用一次。 ## sequence.groupOrder -- **Type:** `number` -- **Default:** `0` +- **类型:** `number` +- **默认值:** `0` -Controls the order in which this project runs its tests when using multiple [projects](/guide/projects). +控制在使用多个 [项目](/guide/projects) 环境时,当前项目的测试执行顺序。 -- Projects with the same group order number will run together, and groups are run from lowest to highest. -- If you don't set this option, all projects run in parallel. -- If several projects use the same group order, they will run at the same time. +- 使用相同组顺序编号的项目,会作为一组一起运行,各组按编号从低到高依次执行。 +- 如果不设置此选项,所有项目并行运行。 +- 如果多个项目使用相同的组顺序编号,它们将同时运行。 -This setting only affects the order in which projects run, not the order of tests within a project. -To control test isolation or the order of tests inside a project, use the [`isolate`](/config/isolate) and [`sequence.sequencer`](/config/sequence#sequence-sequencer) options. +该设置仅影响项目间的执行顺序,不改变项目内部测试的排序。 +如需控制测试隔离性或项目内测试顺序,请使用 [`isolate`](/config/isolate) 和 [`sequence.sequencer`](/config/sequence#sequence-sequencer) 配置项。 -::: details Example -Consider this example: +::: details 示例 +举例来说: ```ts import { defineConfig } from 'vitest/config' @@ -78,86 +78,86 @@ export default defineConfig({ }) ``` -Tests in these projects will run in this order: +这些项目中的测试将按以下顺序运行: ``` 0. slow | - |> running together + |> 同时运行 0. fast | - 1. flaky |> runs after slow and fast alone + 1. flaky |> 在 slow 和 fast 运行完后单独运行 ``` ::: ## sequence.shuffle -- **Type**: `boolean | { files?, tests? }` -- **Default**: `false` -- **CLI**: `--sequence.shuffle`, `--sequence.shuffle=false` +- **类型:** `boolean | { files?, tests? }` +- **默认值:** `false` +- **命令行终端:** `--sequence.shuffle`, `--sequence.shuffle=false` -If you want files and tests to run randomly, you can enable it with this option, or CLI argument [`--sequence.shuffle`](/guide/cli). +如果希望测试文件和测试用例随机执行,可通过此选项或 CLI 参数 [`--sequence.shuffle`](/guide/cli) 启用。 -Vitest usually uses cache to sort tests, so long-running tests start earlier, which makes tests run faster. If your files and tests run in random order, you will lose this performance improvement, but it may be useful to track tests that accidentally depend on another test run previously. +Vitest 通常使用缓存对测试进行排序,使耗时较长的测试优先启动,从而加快测试运行速度。如果文件和测试以随机顺序运行,将失去这一性能提升,但这有助于发现意外依赖于之前测试运行的测试。 ### sequence.shuffle.files {#sequence-shuffle-files} -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--sequence.shuffle.files`, `--sequence.shuffle.files=false` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--sequence.shuffle.files`, `--sequence.shuffle.files=false` -Whether to randomize files, be aware that long running tests will not start earlier if you enable this option. +是否启用文件随机排序,请注意启用此选项后,耗时较长的测试将无法优先启动执行。 ### sequence.shuffle.tests {#sequence-shuffle-tests} -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--sequence.shuffle.tests`, `--sequence.shuffle.tests=false` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--sequence.shuffle.tests`, `--sequence.shuffle.tests=false` Whether to randomize tests. ## sequence.concurrent {#sequence-concurrent} -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--sequence.concurrent`, `--sequence.concurrent=false` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--sequence.concurrent`, `--sequence.concurrent=false` -If you want tests to run in parallel, you can enable it with this option, or CLI argument [`--sequence.concurrent`](/guide/cli). +如果希望测试并行运行,可通过此选项或 CLI 参数 [`--sequence.concurrent`](/guide/cli) 启用。 ::: warning -When you run tests with `sequence.concurrent` and `expect.requireAssertions` set to `true`, you should use [local expect](/guide/test-context.html#expect) instead of the global one. Otherwise, this may cause false negatives in [some situations (#8469)](https://github.com/vitest-dev/vitest/issues/8469). +当同时启用 `sequence.concurrent` 并行测试和 `expect.requireAssertions` 断言检测时,应使用 [本地 expect 对象](/guide/test-context.html#expect) 而非全局对象,否则可能导致 [特定场景下的假阴性问题(#8469)](https://github.com/vitest-dev/vitest/issues/8469)。 ::: ## sequence.seed -- **Type**: `number` -- **Default**: `Date.now()` -- **CLI**: `--sequence.seed=1000` +- **类型:** `number` +- **默认值:** `Date.now()` +- **命令行终端:** `--sequence.seed=1000` -Sets the randomization seed, if tests are running in random order. +设置随机种子,当测试以随机顺序运行时生效。 ## sequence.hooks -- **Type**: `'stack' | 'list' | 'parallel'` -- **Default**: `'stack'` -- **CLI**: `--sequence.hooks=` +- **类型:** `'stack' | 'list' | 'parallel'` +- **默认值:** `'stack'` +- **命令行终端:** `--sequence.hooks=` -Changes the order in which hooks are executed. +调整钩子函数的执行顺序: -- `stack` will order "after" hooks in reverse order, "before" hooks will run in the order they were defined -- `list` will order all hooks in the order they are defined -- `parallel` runs hooks in a single group in parallel (hooks in parent suites still run before the current suite's hooks). The actual number of simultaneously running hooks is limited by [`maxConcurrency`](/config/maxconcurrency). +- `stack`:"after" 类钩子按定义顺序逆序执行,"before" 类钩子保持定义顺序执行 +- `list`:所有钩子严格按定义顺序执行 +- `parallel`:在单个组内并行运行钩子(父套件的钩子仍会在当前套件的钩子之前运行)。实际并发数受[`maxConcurrency`](/config/maxconcurrency) 限制 ::: tip -This option doesn't affect [`onTestFinished`](/api/hooks#ontestfinished). It is always called in reverse order. +此选项不影响 [`onTestFinished`](/api/hooks#ontestfinished) 钩子,该钩子始终采用逆序调用。 ::: ## sequence.setupFiles {#sequence-setupfiles} -- **Type**: `'list' | 'parallel'` -- **Default**: `'parallel'` -- **CLI**: `--sequence.setupFiles=` +- **类型:** `'list' | 'parallel'` +- **默认值:** `'parallel'` +- **命令行终端:** `--sequence.setupFiles=` -Changes the order in which setup files are executed. +调整配置文件的执行顺序: -- `list` will run setup files in the order they are defined -- `parallel` will run setup files in parallel +- `list` 会按定义顺序运行初始化文件 +- `parallel` 会并行运行初始化文件 diff --git a/config/server.md b/config/server.md index e7c3623e..3956947c 100644 --- a/config/server.md +++ b/config/server.md @@ -1,28 +1,28 @@ --- -title: server | Config +title: server | 配置 outline: deep --- # server -Before Vitest 4, this option was used to define the configuration for the `vite-node` server. +在 Vitest 4 之前,此选项用于定义 `vite-node` 服务器的配置。 -At the moment, this option allows you to configure the inlining and externalization mechanisms, along with the module runner debugging configuration. +当前该选项允许你配置模块内联和外置机制,以及模块运行器的调试配置。 ::: warning -These options should be used only as the last resort to improve performance by externalizing auto-inlined dependencies or to fix issues by inlining invalid external dependencies. +这些选项应仅作为最后手段使用:通过外置自动内联的依赖项来提升性能,或通过内联无效的外部依赖项来修复问题。 -Normally, Vitest should do this automatically. +通常,Vitest 应自动完成这些操作。 ::: ## server.deps ### server.deps.external -- **Type:** `(string | RegExp)[]` -- **Default:** files inside [`moduleDirectories`](/config/deps#moduledirectories) +- **类型:** `(string | RegExp)[]` +- **默认值:** [`moduleDirectories`](/config/deps#moduledirectories) 目录内的文件 -Specifies modules that should not be transformed by Vite and should instead be processed directly by the engine. These modules are imported via native dynamic `import` and bypass both transformation and resolution phases. +指定不应由 Vite 转换而应直接由引擎处理的模块。这些模块通过原生动态 `import` 导入,会跳过转换和解析阶段。 ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -38,36 +38,36 @@ export default defineConfig({ }) ``` -External modules and their dependencies are not present in the module graph and will not trigger test restarts when they change. +外置模块及其依赖不存在于模块依赖树中,变更时不会触发测试重启。 -Typically, packages under `node_modules` are externalized. +通常,`node_modules` 下的包会被外置化。 ::: tip -If a string is provided, it is first normalized by prefixing the `/node_modules/` or other [`moduleDirectories`](/config/deps#moduledirectories) segments (for example, `'react'` becomes `/node_modules/react/`), and the resulting string is then matched against the full file path. For example, package `@company/some-name` located inside `packages/some-name` should be specified as `some-name`, and `packages` should be included in `deps.moduleDirectories`. +如果提供字符串参数,系统会先通过添加 `/node_modules/` 或其他 [`moduleDirectories`](/config/deps#moduledirectories) 路径段进行标准化处理(例如 `'react'` 会被转换为 `/node_modules/react/`),随后将生成的字符串与完整文件路径进行匹配。例如,位于 `packages/some-name` 的 `@company/some-name` 包应指定为 `some-name`,且需将 `packages` 包含在 `deps.moduleDirectories` 配置中。 -If a `RegExp` is provided, it is matched against the full file path. +如果提供 `RegExp` 正则表达式参数,则会直接与完整文件路径进行匹配。 ::: ### server.deps.inline -- **Type:** `(string | RegExp)[] | true` -- **Default:** everything that is not externalized +- **类型:** `(string | RegExp)[] | true` +- **默认值:** 所有未被外置的模块 -Specifies modules that should be transformed and resolved by Vite. These modules are run by Vite's [module runner](https://vite.dev/guide/api-environment-runtimes#modulerunner). +指定应由 Vite 进行转换和解析的模块。这些模块由 Vite 的 [模块运行器](https://cn.vite.dev/guide/api-environment-runtimes#modulerunner)执行。 -Typically, your source files are inlined. +通常情况下,源代码文件会被自动内联处理。 ::: tip -If a string is provided, it is first normalized by prefixing the `/node_modules/` or other [`moduleDirectories`](/config/deps#moduledirectories) segments (for example, `'react'` becomes `/node_modules/react/`), and the resulting string is then matched against the full file path. For example, package `@company/some-name` located inside `packages/some-name` should be specified as `some-name`, and `packages` should be included in `deps.moduleDirectories`. +如果提供字符串参数,系统会先通过添加 `/node_modules/` 或其他 [`moduleDirectories`](/config/deps#moduledirectories) 路径段进行标准化处理(例如 `'react'` 会被转换为 `/node_modules/react/`),随后将生成的字符串与完整文件路径进行匹配。例如,位于 `packages/some-name` 的 `@company/some-name` 包应指定为 `some-name`,且需将 `packages` 包含在 `deps.moduleDirectories` 配置中。 -If a `RegExp` is provided, it is matched against the full file path. +如果提供 `RegExp` 正则表达式参数,则会直接与完整文件路径进行匹配。 ::: ### server.deps.fallbackCJS -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -When enabled, Vitest will try to guess a CommonJS build for an ESM entry by checking a few common CJS/UMD file name and folder patterns (like `.mjs`, `.umd.js`, `.cjs.js`, `umd/`, `cjs/`, `lib/`). +启用该选项时,Vitest 会通过检查常见的 CJS/UMD 文件名和目录模式(如 `.mjs`、`.umd.js`、`.cjs.js`、`umd/`、`cjs/`、`lib/` 等),尝试为 ESM 入口推测出对应的 CommonJS 构建版本。 -This is a best-effort heuristic to work around confusing or incorrect ESM/CJS packaging and may not work for all dependencies. +Vitest 会尽力猜测 ESM 入口的 CommonJS 构建,但可能不适用于所有依赖。 diff --git a/config/setupfiles.md b/config/setupfiles.md index e4d7e298..93077069 100644 --- a/config/setupfiles.md +++ b/config/setupfiles.md @@ -1,30 +1,28 @@ --- -title: setupFiles | Config +title: setupFiles | 配置 outline: deep --- - - # setupFiles - **类型:** `string | string[]` -Paths to setup files resolved relative to the [`root`](/config/root). They will run before each _test file_ in the same process. By default, all test files run in parallel, but you can configure it with [`sequence.setupFiles`](/config/sequence#sequence-setupfiles) option. +相对于 [项目根目录](/config/root) 的初始化文件路径。它们会在每个 _测试文件_ 之前的同一进程中运行。默认情况下,所有测试文件并行运行,但你可以通过 [`sequence.setupFiles`](/config/sequence#sequence-setupfiles) 选项进行配置。 -Vitest will ignore any exports from these files. +Vitest 会忽略这些文件的任何导出。 :::warning -Note that setup files are executed in the same process as tests, unlike [`globalSetup`](/config/globalsetup) that runs once in the main thread before any test worker is created. +注意,初始化文件与测试在同一个进程中执行,这与 [`globalSetup`](/config/globalsetup) 不同,后者会在任何测试工作线程创建之前,在主线程中仅执行一次。 ::: :::info 编辑设置文件将自动触发所有测试的重新运行。 ::: -If you have a heavy process running in the background, you can use `process.env.VITEST_POOL_ID` (integer-like string) inside to distinguish between workers and spread the workload. +如果后台运行了高负载进程,可在内部使用 `process.env.VITEST_POOL_ID`(类整数字符串)区分不同工作线程以分配负载。 :::warning -If [isolation](/config/isolate) is disabled, imported modules are cached, but the setup file itself is executed again before each test file, meaning that you are accessing the same global object before each test file. Make sure you are not doing the same thing more than necessary. +如果禁用了 [隔离模式](/config/isolate),导入的模块会被缓存,但初始化文件本身会在每个测试文件之前重新运行,这意味着每次测试前你访问的都是同一个全局对象。请确保不会执行不必要的重复操作。 比如,你可能依赖于一个全局变量: @@ -37,7 +35,7 @@ if (!globalThis.setupInitialized) { globalThis.setupInitialized = true } -// hooks reset before each test file +// 在每个套件之前重置 Hook afterEach(() => { cleanup() }) diff --git a/config/silent.md b/config/silent.md index d7f11fff..9fc987a3 100644 --- a/config/silent.md +++ b/config/silent.md @@ -1,14 +1,14 @@ --- -title: silent | Config +title: silent | 配置 outline: deep --- # silent {#silent} -- **Type:** `boolean | 'passed-only'` -- **Default:** `false` -- **CLI:** `--silent`, `--silent=false` +- **类型:** `boolean | 'passed-only'` +- **默认值:** `false` +- **命令行终端:** `--silent`, `--silent=false` -Silent console output from tests. +测试过程中控制台保持静默状态。 -Use `'passed-only'` to see logs from failing tests only. Logs from failing tests are printed after a test has finished. +使用 `'passed-only'` 仅查看失败测试的日志。失败测试的日志会在测试完成后打印。 diff --git a/config/slowtestthreshold.md b/config/slowtestthreshold.md index 84f9594d..e72488ba 100644 --- a/config/slowtestthreshold.md +++ b/config/slowtestthreshold.md @@ -1,12 +1,12 @@ --- -title: slowTestThreshold | Config +title: slowTestThreshold | 配置 outline: deep --- # slowTestThreshold -- **Type**: `number` -- **Default**: `300` -- **CLI**: `--slow-test-threshold=`, `--slowTestThreshold=` +- **类型:** `number` +- **默认值:** `300` +- **命令行终端:** `--slow-test-threshold=`, `--slowTestThreshold=` -The number of milliseconds after which a test or suite is considered slow and reported as such in the results. +测试或测试套件执行时间超过该毫秒数即被视为缓慢,并在测试结果中予以标注。 diff --git a/config/snapshotenvironment.md b/config/snapshotenvironment.md index b6a550cf..15c8ab33 100644 --- a/config/snapshotenvironment.md +++ b/config/snapshotenvironment.md @@ -1,15 +1,15 @@ --- -title: snapshotEnvironment | Config +title: snapshotEnvironment | 配置 outline: deep --- # snapshotEnvironment -- **Type:** `string` +- **类型:** `string` -Path to a custom snapshot environment implementation. This is useful if you are running your tests in an environment that doesn't support Node.js APIs. This option doesn't have any effect on a browser runner. +自定义快照环境实现的路径。该选项适用于在不支持 Node.js API 的环境中运行测试的场景。该选项在浏览器运行器中无效。 -This object should have the shape of `SnapshotEnvironment` and is used to resolve and read/write snapshot files: +该对象需符合 `SnapshotEnvironment` 接口规范,用于解析和读写快照文件: ```ts export interface SnapshotEnvironment { @@ -23,10 +23,10 @@ export interface SnapshotEnvironment { } ``` -You can extend default `VitestSnapshotEnvironment` from `vitest/snapshot` entry point if you need to overwrite only a part of the API. +如需仅覆盖部分 API,可从 `vitest/snapshot` 入口扩展默认的 `VitestSnapshotEnvironment`。 ::: warning -This is a low-level option and should be used only for advanced cases where you don't have access to default Node.js APIs. +此为底层选项,仅适用于无法访问默认 Node.js API 的高级场景。 -If you just need to configure snapshots feature, use [`snapshotFormat`](/config/snapshotformat) or [`resolveSnapshotPath`](/config/resolvesnapshotpath) options. +如果你只需要配置快照功能,请使用 [`snapshotFormat`](/config/snapshotformat) 或 [`resolveSnapshotPath`](/config/resolvesnapshotpath) 选项。 ::: diff --git a/config/snapshotformat.md b/config/snapshotformat.md index 76721ebc..48d630a3 100644 --- a/config/snapshotformat.md +++ b/config/snapshotformat.md @@ -1,33 +1,33 @@ --- -title: snapshotFormat | Config +title: snapshotFormat | 配置 outline: deep --- # snapshotFormat -- **Type:** `Omit & { compareKeys?: null | undefined }` +- **类型:** `Omit & { compareKeys?: null | undefined }` -Format options for snapshot testing. These options configure the snapshot-specific formatting layer built on top of [`@vitest/pretty-format`](https://npmx.dev/package/@vitest/pretty-format). +快照测试的格式化选项。这些选项用于配置基于 [`@vitest/pretty-format`](https://npmx.dev/package/@vitest/pretty-format) 构建的快照专用格式化层。 -For the full option surface of `PrettyFormatOptions`, see [`@vitest/pretty-format`](https://npmx.dev/package/@vitest/pretty-format). This page focuses on the Vitest snapshot-specific defaults and constraints. +关于 `PrettyFormatOptions` 的完整选项说明,请参阅 [`@vitest/pretty-format`](https://npmx.dev/package/@vitest/pretty-format)。本文档重点介绍 Vitest 快照特有的默认值和限制。 -Vitest snapshots already apply these defaults before your `snapshotFormat` overrides: +Vitest 快照在应用您的 `snapshotFormat` 覆盖前已预设以下默认值: - `printBasicPrototype: false` - `escapeString: false` - `escapeRegex: true` - `printFunctionName: false` -Vitest also supports formatter options such as `printShadowRoot` and `maxOutputLength` in `snapshotFormat`. +Vitest 还支持在 `snapshotFormat` 中使用如 `printShadowRoot` 和 `maxOutputLength` 等格式化选项: -`printShadowRoot` controls whether shadow-root contents are included in DOM snapshots. +`printShadowRoot` 控制是否在 DOM 快照中包含 shadow-root 内容。 -`maxOutputLength` is an approximate per-depth output budget, not a hard cap on the final rendered string. +`maxOutputLength` 是近似按深度划分的输出长度预算值,并非最终渲染字符串的硬性限制。 -By default, snapshot keys are sorted using the formatter's default behavior. Set `compareKeys` to `null` to disable key sorting. Custom compare functions are not supported in `snapshotFormat`. +默认情况下,快照键名会使用格式化器的默认行为排序。设置 `compareKeys: null` 可禁用键名排序。`snapshotFormat` 不支持自定义比较函数。 ::: tip -Beware that `plugins` on this object will be ignored. +该对象中的 `plugins` 配置将被忽略。 -If you need to extend snapshot serialization via pretty-format plugins, use [`expect.addSnapshotSerializer`](/api/expect#expect-addsnapshotserializer) or [`snapshotSerializers`](/config/snapshotserializers) instead. +如需通过 pretty-format 插件扩展快照序列化能力,请改用 [`expect.addSnapshotSerializer`](/api/expect#expect-addsnapshotserializer) 或 [`snapshotSerializers`](/config/snapshotserializers)。 ::: diff --git a/config/snapshotserializers.md b/config/snapshotserializers.md index 0a1ae9a7..3aebc5f0 100644 --- a/config/snapshotserializers.md +++ b/config/snapshotserializers.md @@ -1,11 +1,11 @@ --- -title: snapshotSerializers | Config +title: snapshotSerializers | 配置 outline: deep --- # snapshotSerializers -- **Type:** `string[]` -- **Default:** `[]` +- **类型:** `string[]` +- **默认值:** `[]` -A list of paths to snapshot serializer modules for snapshot testing, useful if you want add custom snapshot serializers. See [Custom Serializer](/guide/snapshot#custom-serializer) for more information. +快照测试的快照序列化器模块路径列表,适用于想要添加自定义快照序列化器的场景。更多内容请参阅 [自定义序列化器](/guide/snapshot#custom-serializer)。 diff --git a/config/stricttags.md b/config/stricttags.md index 254923c4..c6b6ac69 100644 --- a/config/stricttags.md +++ b/config/stricttags.md @@ -1,21 +1,20 @@ --- -title: strictTags | Config +title: strictTags | 配置 outline: deep --- - - # strictTags 4.1.0 {#stricttags} -- **Type:** `boolean` -- **Default:** `true` -- **CLI:** `--strict-tags`, `--no-strict-tags` +- **类型:** `boolean` +- **默认值:** `true` +- **命令行终端:** `--strict-tags`, `--no-strict-tags` -Should Vitest throw an error if test has a [`tag`](/config/tags) that is not defined in the config to avoid silently doing something surprising due to mistyped names (applying the wrong configuration or skipping the test due to a `--tags-filter` flag). +如果测试使用了未在配置中定义的 [`tag`](/config/tags),Vitest 是否应抛出错误,以避免因拼写错误导致意外的行为(应用错误的配置或因 +`--tags-filter` 标志而跳过测试)。 -Note that Vitest will always throw an error if `--tags-filter` flag defines a tag not present in the config. +注意,如果 `--tags-filter` 标志定义了配置中不存在的标签,Vitest 将会抛出错误。 -For example, this test will throw an error because the tag `fortnend` has a typo (it should be `frontend`): +例如,以下测试将因标签 `fortnend` 存在拼写错误(正确应为 `frontend`)而抛出错误: ::: code-group ```js [form.test.js] diff --git a/config/tags.md b/config/tags.md index 7a9fdcb7..44e26778 100644 --- a/config/tags.md +++ b/config/tags.md @@ -1,27 +1,25 @@ --- -title: tags | Config +title: tags | 配置 outline: deep --- - - # tags 4.1.0 {#tags} -- **Type:** `TestTagDefinition[]` -- **Default:** `[]` +- **类型:** `TestTagDefinition[]` +- **默认值:** `[]` -Defines all [available tags](/guide/test-tags) in your test project. By default, if test defines a name not listed here, Vitest will throw an error, but this can be configured via a [`strictTags`](/config/stricttags) option. +定义测试项目中所有 [可用标签](/guide/test-tags)。默认情况下,如果测试定义的名称未在此列出,Vitest 将抛出错误,但可通过 [`strictTags`](/config/stricttags) 选项进行配置。 -If you are using [`projects`](/config/projects), they will inherit all global tags definitions automatically. +若使用 [`projects`](/config/projects) 配置,所有全局标签定义将自动继承至子项目。 -Use [`--tags-filter`](/guide/test-tags#syntax) to filter tests by their tags. Use [`--list-tags`](/guide/cli#listtags) to print every tag in your Vitest workspace. +使用 [`--tags-filter`](/guide/test-tags#syntax) 可按标签筛选测试用例,使用 [`--list-tags`](/guide/cli#listtags) 可打印 Vitest 工作区中的所有标签。 ## name -- **Type:** `string` -- **Required:** `true` +- **类型:** `string` +- **必填:** `true` -The name of the tag. This is what you use in the `tags` option in tests. +标签名称。该名称将用于测试用例中 `tags` 选项的配置。 ```ts export default defineConfig({ @@ -35,7 +33,7 @@ export default defineConfig({ ``` ::: tip -If you are using TypeScript, you can enforce what tags are available by augmenting the `TestTags` type with a property that contains a union of strings (make sure this file is included by your `tsconfig`): +如果你正在使用 TypeScript,可以通过在 `TestTags` 类型中添加一个包含字符串联合类型的属性,来约束可用的标签(确保该文件已纳入你的 `tsconfig` 中): ```ts [vitest.shims.ts] import 'vitest' @@ -52,11 +50,11 @@ declare module 'vitest' { ``` ::: -## description +## 描述 {#description} -- **Type:** `string` +- **类型:** `string` -A human-readable description for the tag. This will be shown in UI and inside error messages when a tag is not found. +给标签添加通俗易懂描述。这将在 UI 模式中显示,以及在标签未找到时的错误信息里。 ```ts export default defineConfig({ @@ -71,12 +69,12 @@ export default defineConfig({ }) ``` -## priority +## 优先级 {#priority} -- **Type:** `number` -- **Default:** `Infinity` +- **类型:** `number` +- **默认值:** `Infinity` -Priority for merging options when multiple tags with the same options are applied to a test. Lower number means higher priority (e.g., priority `1` takes precedence over priority `3`). +合并多个标签对应的配置选项时的优先级。数字越小优先级越高(例如,优先级 `1` 高于优先级 `3`)。 ```ts export default defineConfig({ @@ -85,31 +83,31 @@ export default defineConfig({ { name: 'flaky', timeout: 30_000, - priority: 1, // higher priority + priority: 1, // 高优先级 }, { name: 'db', timeout: 60_000, - priority: 2, // lower priority + priority: 2, // 低优先级 }, ], }, }) ``` -When a test has both tags, the `timeout` will be `30_000` because `flaky` has a higher priority. +当一个测试同时拥有两个标签时,`timeout` 将是 `30_000`,因为 `flaky` 的优先级更高。 -## Test Options +## 测试选项 {#test-options} -Tags can define [test options](/api/test#test-options) that will be applied to every test marked with the tag. These options are merged with the test's own options, with the test's options taking precedence. +标签可以定义 [测试选项](/api/test#test-options),这些选项将应用于每个标记有该标签的测试。这些选项会与测试自身的选项合并,测试的选项优先级更高。 ::: warning -The [`retry.condition`](/api/test#retry) can only be a regexp because the config values need to be serialised. +[`retry.condition`](/api/test#retry) 只能是正则表达式,因为配置值需要被序列化。 -Tags also cannot apply other [tags](/api/test#tags) via these options. +标签也不能通过这些选项应用其他 [标签](/api/test#tags)。 ::: -## Example +## 示例 {#example} ```ts import { defineConfig } from 'vitest/config' diff --git a/config/teardowntimeout.md b/config/teardowntimeout.md index 1fc9365a..dfe7f8df 100644 --- a/config/teardowntimeout.md +++ b/config/teardowntimeout.md @@ -1,12 +1,12 @@ --- -title: teardownTimeout | Config +title: teardownTimeout | 配置 outline: deep --- # teardownTimeout {#teardowntimeout} -- **Type:** `number` -- **Default:** `10000` -- **CLI:** `--teardown-timeout=5000`, `--teardownTimeout=5000` +- **类型:** `number` +- **默认值:** `10000` +- **命令行终端:** `--teardown-timeout=5000`, `--teardownTimeout=5000` -Default timeout to wait for close when Vitest shuts down, in milliseconds +Vitest 进程关闭时的默认等待超时时间(单位:毫秒) diff --git a/config/testnamepattern.md b/config/testnamepattern.md index 68cadedd..3768d40b 100644 --- a/config/testnamepattern.md +++ b/config/testnamepattern.md @@ -1,14 +1,14 @@ --- -title: testNamePattern | Config +title: testNamePattern | 配置 outline: deep --- # testNamePattern {#testnamepattern} -- **类型** `string | RegExp` -- **命令行终端** `-t `, `--testNamePattern=`, `--test-name-pattern=` +- **类型:** `string | RegExp` +- **命令行终端:** `-t `, `--testNamePattern=`, `--test-name-pattern=` -运行符合全名匹配的测试。如果在此属性中添加 `OnlyRunThis`,则测试中不包含 `OnlyRunThis` 关键字的用例将会被跳过。 +运行名称完全匹配该模式的测试。如果在此属性中添加 `OnlyRunThis`,则测试中不包含 `OnlyRunThis` 关键字的用例将会被跳过。 ```js import { expect, test } from 'vitest' diff --git a/config/testtimeout.md b/config/testtimeout.md index 34ccc934..8cf3b994 100644 --- a/config/testtimeout.md +++ b/config/testtimeout.md @@ -1,5 +1,5 @@ --- -title: testTimeout | Config +title: testTimeout | 配置 outline: deep --- diff --git a/config/typecheck.md b/config/typecheck.md index cae1854a..4666c13e 100644 --- a/config/typecheck.md +++ b/config/typecheck.md @@ -1,82 +1,82 @@ --- -title: typecheck | Config +title: typecheck | 配置 outline: deep --- # typecheck {#typecheck} -Options for configuring [typechecking](/guide/testing-types) test environment. +用于配置 [类型检查](/guide/testing-types) 测试环境的选项。 ## typecheck.enabled {#typecheck-enabled} -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--typecheck`, `--typecheck.enabled` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--typecheck`, `--typecheck.enabled` -Enable typechecking alongside your regular tests. +在常规测试的同时启用类型检查。 ## typecheck.only {#typecheck-only} -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--typecheck.only` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--typecheck.only` -Run only typecheck tests, when typechecking is enabled. When using CLI, this option will automatically enable typechecking. +仅运行类型检查测试,当类型检查启用时生效。在 CLI 中使用此选项会自动启用类型检查。 ## typecheck.checker -- **Type**: `'tsc' | 'vue-tsc' | string` -- **Default**: `tsc` +- **类型:** `'tsc' | 'vue-tsc' | string` +- **默认值:** `tsc` -What tools to use for type checking. Vitest will spawn a process with certain parameters for easier parsing, depending on the type. Checker should implement the same output format as `tsc`. +用于类型检查的工具。Vitest 将根据所选类型启动特定参数的进程以便解析,检查器需实现与 `tsc` 相同的输出格式。 -You need to have a package installed to use typechecker: +使用类型检查器前需安装对应依赖包: -- `tsc` requires `typescript` package -- `vue-tsc` requires `vue-tsc` package +- `tsc` 需要 `typescript` 包 +- `vue-tsc` 需要 `vue-tsc` 包 -You can also pass down a path to custom binary or command name that produces the same output as `tsc --noEmit --pretty false`. +你也可以传入自定义二进制文件的路径或命令名称,该命令需能生成与 `tsc --noEmit --pretty false` 相同的输出格式。 ## typecheck.include -- **Type**: `string[]` -- **Default**: `['**/*.{test,spec}-d.?(c|m)[jt]s?(x)']` +- **类型:** `string[]` +- **默认值:** `['**/*.{test,spec}-d.?(c|m)[jt]s?(x)']` -Glob pattern for files that should be treated as test files +匹配包含测试文件的 glob 规则。 ## typecheck.exclude -- **Type**: `string[]` -- **Default**: `['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**']` +- **类型:** `string[]` +- **默认值:** `['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**']` -Glob pattern for files that should not be treated as test files +匹配排除测试文件的 glob 规则。 ## typecheck.allowJs -- **Type**: `boolean` -- **Default**: `false` +- **类型:** `boolean` +- **默认值:** `false` -Check JS files that have `@ts-check` comment. If you have it enabled in tsconfig, this will not overwrite it. +检查有 `@ts-check` 注释的 JS 文件。 如果你在 tsconfig 中启用它,则不会覆盖它。 ## typecheck.ignoreSourceErrors -- **Type**: `boolean` -- **Default**: `false` +- **类型:** `boolean` +- **默认值:** `false` -Do not fail, if Vitest found errors outside the test files. This will not show you non-test errors at all. +如果 Vitest 在测试文件之外发现错误,则不失败。这不会显示非测试文件的错误。 -By default, if Vitest finds source error, it will fail test suite. +默认情况下,如果 Vitest 发现源码错误,会导致测试套件运行失败。 ## typecheck.tsconfig -- **Type**: `string` -- **Default**: _tries to find closest tsconfig.json_ +- **类型:** `string` +- **默认值:** _尝试查找最近的 tsconfig.json_ -Path to custom tsconfig, relative to the project root. +自定义 tsconfig 的路径,相对于项目根目录。 ## typecheck.spawnTimeout -- **Type**: `number` -- **Default**: `10_000` +- **类型:** `number` +- **默认值:** `10_000` -Minimum time in milliseconds it takes to spawn the typechecker. +启动类型检查器所需的最短时间(毫秒)。 diff --git a/config/ui.md b/config/ui.md index 9581d659..00fd3130 100644 --- a/config/ui.md +++ b/config/ui.md @@ -1,22 +1,20 @@ --- -title: ui | Config +title: ui | 配置 outline: deep --- - - # ui -- **Type:** `boolean` -- **Default:** `false` -- **CLI:** `--ui`, `--ui=false` +- **类型:** `boolean` +- **默认值:** `false` +- **命令行终端:** `--ui`, `--ui=false` -Enable [Vitest UI](/guide/ui). +启用 [UI 模式](/guide/ui). ::: warning -This features requires a [`@vitest/ui`](https://npmx.dev/package/@vitest/ui) package to be installed. If you do not have it already, Vitest will install it when you run the test command for the first time. +此功能需要安装 [`@vitest/ui`](https://npmx.dev/package/@vitest/ui) 包。若尚未安装,Vitest 会在首次运行测试命令时自动安装。 ::: -::: danger SECURITY ADVICE -Make sure that your UI server is not exposed to the network. Since Vitest 4.1 setting [`api.host`](/config/api) to anything other than `localhost` will disable the buttons to save the code or run any tests for security reasons, effectively making UI a readonly reporter. +::: danger 安全警告 +请确保您的 UI 模式的服务不暴露在公共网络中。自 Vitest 4.1 起,出于安全考虑,若将 [`api.host`](/config/api) 设置为非 `localhost` 地址,将自动禁用代码保存和测试运行按钮,使 UI 模式变为只读模式。 ::: diff --git a/config/unstubenvs.md b/config/unstubenvs.md index 0d309437..04c9b4b6 100644 --- a/config/unstubenvs.md +++ b/config/unstubenvs.md @@ -1,5 +1,5 @@ --- -title: unstubEnvs | Config +title: unstubEnvs | 配置 outline: deep --- @@ -8,7 +8,7 @@ outline: deep - **类型:** `boolean` - **默认值:** `false` -将在每次测试前调用 [`vi.unstubAllEnvs()`](/api/vi#vi-unstuballenvs)。 +是否应在每个测试前自动调用 [`vi.unstubAllEnvs()`](/api/vi#vi-unstuballenvs)。 ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -21,5 +21,5 @@ export default defineConfig({ ``` ::: warning -Be aware that this option may cause problems with async [concurrent tests](/api/test#test-concurrent). If enabled, the completion of one test will restore all the values changed with [`vi.stubEnv`](/api/vi#vi-stubenv), including those currently being used by other tests in progress. +需要注意的是此选项可能会影响异步 [并发测试](/api/test#test-concurrent) 的正常运行。启用后,当某个测试执行完成时,会恢复所有通过 [`vi.stubEnv`](/api/vi#vi-stubenv) 修改的值,包括当前正在执行的其他测试正在使用的值。 ::: diff --git a/config/unstubglobals.md b/config/unstubglobals.md index 47c8e8ea..152fef85 100644 --- a/config/unstubglobals.md +++ b/config/unstubglobals.md @@ -1,14 +1,14 @@ --- -title: unstubGlobals | Config +title: unstubGlobals | 配置 outline: deep --- # unstubGlobals -- **Type:** `boolean` -- **Default:** `false` +- **类型:** `boolean` +- **默认值:** `false` -Should Vitest automatically call [`vi.unstubAllGlobals()`](/api/vi#vi-unstuballglobals) before each test. +是否应在每个测试前自动调用 [`vi.unstubAllGlobals()`](/api/vi#vi-unstuballglobals)。 ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -21,5 +21,6 @@ export default defineConfig({ ``` ::: warning -Be aware that this option may cause problems with async [concurrent tests](/api/test#test-concurrent). If enabled, the completion of one test will restore all global values that were changed with [`vi.stubGlobal`](/api/vi#vi-stubglobal), including those currently being used by other tests in progress. + +需要注意的是此选项可能会影响异步 [并发测试](/api/test#test-concurrent) 的正常运行。启用后,当某个测试执行完成时,会恢复所有通过 [`vi.stubGlobal`](/api/vi#vi-stubglobal) 修改的全局值,包括当前正在执行的其他测试正在使用的值。 ::: diff --git a/config/update.md b/config/update.md index 29f2b602..3b46f2cd 100644 --- a/config/update.md +++ b/config/update.md @@ -1,15 +1,13 @@ --- -title: update | Config +title: update | 配置 outline: deep --- - - # update {#update} -- **Type:** `boolean | 'new' | 'all' | 'none'` -- **Default:** `false` -- **CLI:** `-u`, `--update`, `--update=false`, `--update=new`, `--update=none` +- **类型:** `boolean | 'new' | 'all' | 'none'` +- **默认值:** `false` +- **命令行终端:** `-u`, `--update`, `--update=false`, `--update=new`, `--update=none` Define snapshot update behavior. diff --git a/config/vmmemorylimit.md b/config/vmmemorylimit.md index 118d9bb1..3205f294 100644 --- a/config/vmmemorylimit.md +++ b/config/vmmemorylimit.md @@ -1,35 +1,35 @@ --- -title: vmMemoryLimit | Config +title: vmMemoryLimit | 配置 outline: deep --- # vmMemoryLimit -- **Type:** `string | number` -- **Default:** `1 / CPU Cores` +- **类型:** `string | number` +- **默认值:** `1 / CPU 核心` -This option affects only `vmForks` and `vmThreads` pools. +此选项仅影响 `vmForks` 和 `vmThreads` 线程池。 -Specifies the memory limit for workers before they are recycled. This value heavily depends on your environment, so it's better to specify it manually instead of relying on the default. +指定工作线程被回收之前的内存限制。该值在很大程度上取决于你的运行环境,因此最好手动指定它,而不是依赖默认值。 ::: tip -The implementation is based on Jest's [`workerIdleMemoryLimit`](https://jestjs.io/docs/configuration#workeridlememorylimit-numberstring). - -The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: - -- `<= 1` - The value is assumed to be a percentage of system memory. So 0.5 sets the memory limit of the worker to half of the total system memory -- `\> 1` - Assumed to be a fixed byte value. Because of the previous rule if you wanted a value of 1 byte (I don't know why) you could use 1.1. -- With units - - `50%` - As above, a percentage of total system memory - - `100KB`, `65MB`, etc - With units to denote a fixed memory limit. - - `K` / `KB` - Kilobytes (x1000) - - `KiB` - Kibibytes (x1024) - - `M` / `MB` - Megabytes - - `MiB` - Mebibytes - - `G` / `GB` - Gigabytes - - `GiB` - Gibibytes +该实现基于 Jest 的 [`workerIdleMemoryLimit`](https://jestjs.io/docs/configuration#workeridlememorylimit-numberstring)。 + +可以通过多种不同的方式指定限制,无论结果是什么,`Math.floor` 都用于将其转换为整数值: + +- `<= 1` - 该值假定为系统内存的百分比。所以 0.5 将 worker 的内存限制设置为系统总内存的一半。 +- `\> 1` - 假设是固定字节值。由于之前的规则,如果你想要 1 字节的值(我不知道为什么),你可以使用 1.1。 +- 有单位时 + - `50%` - 如上,占系统总内存的百分比 + - `100KB`, `65MB`, 等 - 用单位表示固定的内存限制 + - `K` / `KB` - 千字节 (x1000) + - `KiB` - 千字节 (x1024) + - `M` / `MB`- 千字节 + - `MiB` - 兆字节 + - `G` / `GB` - 千兆字节 + - `GiB` - 千兆字节 ::: ::: warning -Percentage based memory limit [does not work on Linux CircleCI](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) workers due to incorrect system memory being reported. +基于百分比的内存限制 [在 Linux CircleCI 环境下无效](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677),因该系统会误报内存总量。 ::: diff --git a/config/watch.md b/config/watch.md index 83a2b894..3822895c 100644 --- a/config/watch.md +++ b/config/watch.md @@ -1,5 +1,5 @@ --- -title: watch | Config +title: watch | 配置 outline: deep --- diff --git a/config/watchtriggerpatterns.md b/config/watchtriggerpatterns.md index 2041def7..56d6a3f5 100644 --- a/config/watchtriggerpatterns.md +++ b/config/watchtriggerpatterns.md @@ -1,15 +1,15 @@ --- -title: watchTriggerPatterns | Config +title: watchTriggerPatterns | 配置 outline: deep --- # watchTriggerPatterns 3.2.0 -- **Type:** `WatcherTriggerPattern[]` +- **类型:** `WatcherTriggerPattern[]` -Vitest reruns tests based on the module graph which is populated by static and dynamic `import` statements. However, if you are reading from the file system or fetching from a proxy, then Vitest cannot detect those dependencies. +Vitest 基于由静态和动态 `import` 语句填充的模块依赖图来重新运行测试。但是,如果你从文件系统读取或从代理获取,Vitest 无法检测这些依赖关系。 -To correctly rerun those tests, you can define a regex pattern and a function that returns a list of test files to run. +要触发相关测试重新运行,你可以定义一个正则表达式模式和一个返回要运行的测试文件列表的函数。 ```ts import { defineConfig } from 'vitest/config' @@ -20,7 +20,7 @@ export default defineConfig({ { pattern: /^src\/(mailers|templates)\/(.*)\.(ts|html|txt)$/, testsToRun: (id, match) => { - // relative to the root value + // 相对于根路径 return `./api/tests/mailers/${match[2]}.test.ts` }, }, @@ -30,5 +30,5 @@ export default defineConfig({ ``` ::: warning -Returned files should be either absolute or relative to the root. Note that this is a global option, and it cannot be used inside of [project](/guide/projects) configs. +返回的文件应该是绝对路径或相对于根目录的相对路径。注意这是一个全局选项,不能在 [project](/guide/projects) 配置中使用。 ::: diff --git a/guide/coverage.md b/guide/coverage.md index be90e0a7..23c497ec 100644 --- a/guide/coverage.md +++ b/guide/coverage.md @@ -241,7 +241,7 @@ export default defineConfig({ ``` ::: -## 自定义覆盖率的报告器 {#custom-coverage-reporter} +## 自定义代码覆盖率报告器 {#custom-coverage-reporter} 我们可以通过在 `test.coverage.reporter` 中传递软件包名称或绝对路径来使用自定义覆盖报告器: diff --git a/guide/snapshot.md b/guide/snapshot.md index 0119a8bf..4a5dadb8 100644 --- a/guide/snapshot.md +++ b/guide/snapshot.md @@ -120,7 +120,7 @@ test('button looks correct', async () => { 它会捕获屏幕截图并与参考图像进行比较,以检测意外的视觉变化。在 [视觉回归测试指南](/guide/browser/visual-regression-testing)中了解更多内容。 -## 自定义序列化程序 {#custom-serializer} +## 自定义序列化器 {#custom-serializer} 你可以添加自己的逻辑来修改快照的序列化方式。像 Jest 一样,Vitest 默认有内置的 JavaScript 类型、HTML 元素、ImmutableJS 和 React 元素提供了默认的序列化程序。 diff --git a/package.json b/package.json index 4d840d19..2e7a429f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "docs-cn", "type": "module", - "version": "4.1.0", + "version": "4.1.2", "private": true, "packageManager": "pnpm@9.7.1", "scripts": {