Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<!-- 感谢你的贡献! -->

### 在提交PR之前,请确保您执行以下操作:
- [ ] 曾阅读过[翻译须知](https://github.com/vitest-dev/docs-cn/issues/391)。
- [ ] 曾阅读过 [翻译须知](https://github.com/vitest-dev/docs-cn/issues/391)。
- [ ] 检查是否已经有PR以同样的方式解决问题,以避免创建重复。
- [ ] 在此PR中描述正在解决的问题,或引用它解决的问题(例如:`fixes #123`)。

Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/autofix.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ jobs:
timeout-minutes: 10

steps:
- uses: actions/checkout@v5
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0

- name: Use Node.js lts/*
uses: actions/setup-node@v4
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: lts/*

Expand Down
2 changes: 1 addition & 1 deletion .vitepress/scripts/cli-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ const template = options.map((option) => {
const cli = option.cli
const [page, ...hash] = (title.startsWith('browser.') ? title.slice(8) : title).toLowerCase().split('.')
const config = skipConfig.has(title) ? '' : `[${title}](${title.includes('browser.') ? '/config/browser/' : '/config/'}${page}${hash.length ? `#${[page, ...hash].join('-')}` : ''})`
// eslint-disable-next-line e18e/prefer-static-regex

return `### ${title}\n\n- **CLI:** ${cli}\n${config ? `- **Config:** ${config}\n` : ''}\n${option.description.replace(/https:\/\/vitest\.dev\//g, '/')}\n`
}).join('\n')

Expand Down
2 changes: 1 addition & 1 deletion advanced/pool.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 自定义运行池
# 自定义运行池 <Badge type="danger">advanced</Badge> {#custom-pool}

::: warning
这是一个高级且非常底层的 API。如果你只是想 [运行测试](/guide/),你可能不需要这个。它主要由库作者使用。
Expand Down
4 changes: 2 additions & 2 deletions api/advanced/metadata.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 任务元数据 <Badge type="danger">高级</Badge>
# 任务元数据 <Badge type="danger">高级</Badge> {#task-metadata}

如果你正在开发自定义报告器或使用 Vitest Node.js API,你可能会发现将在各种上下文中执行的测试中的数据传递给报告器或自定义 Vitest 处理程序很有用。

Expand Down Expand Up @@ -42,7 +42,7 @@ Vitest 使用不同的方法与 Node.js 进程进行通信。

该属性也会出现在每个测试的 `json` 报告中,因此请确保数据可以序列化为 JSON。

另外,请确保在设置[错误属性](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#error_types)之前序列化它们。
另外,请确保在设置 [错误属性](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#error_types) 之前序列化它们。
:::

当测试运行完成时,你还可以从 Vitest 状态获取此信息:
Expand Down
10 changes: 7 additions & 3 deletions api/advanced/plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ outline: deep
Vitest 自 3.1 版起支持 `configureVitest` [插件](https://cn.vite.dev/guide/api-plugin) hook。

::: code-group

```ts [only vitest]
import type { Vite, VitestPluginContext } from 'vitest/node'

Expand All @@ -26,6 +27,7 @@ export function plugin(): Vite.Plugin {
}
}
```

```ts [vite and vitest]
/// <reference types="vitest/config" />

Expand All @@ -43,14 +45,16 @@ export function plugin(): Plugin {
}
}
```

:::

::: tip TypeScript
Vitest 通过 `Vite` namespace 重新导出所有仅 Vite 类型的导入,我们可以使用它来保持版本同步。但是,如果我们正在为 Vite 和 Vitest 编写插件,则可以继续使用 `vite` 入口点的 `Plugin` 类型。只需确保我们在某处引用了 `vitest/config` ,以便正确增强 `configureVitest` 即可:
Vitest 通过 `Vite` namespace 重新导出所有仅 Vite 类型的导入,我们可以使用它来保持版本同步。但是,如果我们正在为 Vite 和 Vitest 编写插件,则可以继续使用 `vite` 入口点的 `Plugin` 类型。只需确保我们在某处引用了 `vitest/config`,以便正确增强 `configureVitest` 即可:

```ts
/// <reference types="vitest/config" />
```

:::

与 [`reporter.onInit`](/api/advanced/reporters#oninit) 不同,此 hooks 在 Vitest 生命周期的早期运行,允许我们更改 `coverage` 和 `reporters` 等配置。更值得注意的变化是,如果我们的插件是在项目中定义而不是在全局配置中定义的,我们可以从 [工作区项目](/guide/projects) 操作全局配置。
Expand All @@ -59,7 +63,7 @@ Vitest 通过 `Vite` namespace 重新导出所有仅 Vite 类型的导入,我

### project

该插件所属的当前[测试项目](./test-project)。
该插件所属的当前 [测试项目](./test-project)。

::: warning 浏览器模式
请注意,如果我们依赖浏览器功能,则 `project.browser` 字段尚未设置。请改用 [`reporter.onBrowserInit`](./reporters#onbrowserinit) 事件。
Expand All @@ -75,7 +79,7 @@ vitest.config.reporters.push([['my-reporter', {}]])
```

::: warning 配置已解析完成
请注意,Vitest 已经解析了配置,因此某些类型可能与通常的用户配置不同。这也意味着某些属性将不会再次解析,例如 `setupFile` 。如果我们要添加新文件,请确保先解析它。
请注意,Vitest 已经解析了配置,因此某些类型可能与通常的用户配置不同。这也意味着某些属性将不会再次解析,例如 `setupFile`。如果我们要添加新文件,请确保先解析它。

此时尚未创建记者,因此修改 `vitest.reporters` 将不起作用,因为它将被覆盖。如果我们需要注入自己的记者,请修改配置。
:::
Expand Down
6 changes: 6 additions & 0 deletions api/advanced/reporters.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ function onInit(vitest: Vitest): Awaitable<void>
请注意,我们还可以通过 [`project`](/api/advanced/test-project) 属性从测试用例、套件和测试模块中访问 `vitest` 实例,但在此方法中存储对 `vitest` 的引用也可能有用。

::: details 示例

```ts
import type { Reporter, TestSpecification, Vitest } from 'vitest/node'

Expand All @@ -78,6 +79,7 @@ class MyReporter implements Reporter {

export default new MyReporter()
```

:::

## onBrowserInit {#onbrowserinit}
Expand All @@ -101,6 +103,7 @@ function onTestRunStart(
如果 Vitest 没有找到任何要运行的测试文件,此事件将以空数组调用,然后 [`onTestRunEnd`](#ontestrunend) 将立即被调用。

::: details 示例

```ts
import type { Reporter, TestSpecification } from 'vitest/node'

Expand All @@ -112,6 +115,7 @@ class MyReporter implements Reporter {

export default new MyReporter()
```

:::

## onTestRunEnd
Expand Down Expand Up @@ -139,6 +143,7 @@ function onTestRunEnd(
如果 Vitest 没有找到任何要运行的测试文件,此事件将以空的模块和错误数组调用,状态将取决于 [`config.passWithNoTests`](/config/passwithnotests) 的值。

::: details 示例

```ts
import type {
Reporter,
Expand Down Expand Up @@ -175,6 +180,7 @@ class MyReporter implements Reporter {

export default new MyReporter()
```

:::

## onCoverage
Expand Down
5 changes: 3 additions & 2 deletions api/advanced/runner.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 运行器 API <Badge type="danger">advanced</Badge>
# 运行器 API <Badge type="danger">advanced</Badge> {#runner-api}

::: warning 注意
这是高级 API。如果你只需要 [运行测试](/guide/),你可能不需要这个。它主要被库的作者使用。
Expand Down Expand Up @@ -138,6 +138,7 @@ export default class Runner {
}
}
```

:::

::: warning
Expand Down Expand Up @@ -229,7 +230,7 @@ interface Test<ExtraContext = object> extends TaskBase {
}
```

每个任务都可以有一个 `result` 字段。只有当在套件回调或 `beforeAll`/`afterAll` 回调中抛出错误,阻止了测试的收集时,套件才会有这个字段。测试在它们的回调被调用后总是有这个字段——`state` 和 `errors` 字段根据结果的存在与否而存在。如果在 `beforeEach` 或 `afterEach` 回调中抛出了错误,抛出的错误将出现在 `task.result.errors` 中。
每个任务都可以有一个 `result` 字段。只有当在套件回调或 `beforeAll`/`afterAll` 回调中抛出错误,阻止了测试的收集时,套件才会有这个字段。测试在它们的回调被调用后总是有这个字段—— `state` 和 `errors` 字段根据结果的存在与否而存在。如果在 `beforeEach` 或 `afterEach` 回调中抛出了错误,抛出的错误将出现在 `task.result.errors` 中。

```ts
export interface TaskResult {
Expand Down
3 changes: 2 additions & 1 deletion api/advanced/test-case.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ test('the validation works correctly', ({ task }) => {
task.meta.decorated = false
})
```

如果测试尚未运行完毕,元数据将是一个空对象,除非它定义了静态元数据:

```ts
Expand All @@ -157,7 +158,7 @@ test('the validation works correctly', { meta: { decorated: true } })
function result(): TestResult
```

测试结果。如果测试尚未完成或刚刚开始收集,等于 `TestResultPending`
测试结果。如果测试尚未完成或刚刚开始收集,等于 `TestResultPending`:

```ts
export interface TestResultPending {
Expand Down
1 change: 1 addition & 0 deletions api/advanced/test-collection.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ for (const child of module.children) {
console.log(child.type, child.name)
}
```

:::

## size
Expand Down
5 changes: 3 additions & 2 deletions api/advanced/test-module.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ describe('the validation works correctly', (task) => {
```

:::tip
如果元数据是在收集过程中附加的(在 `test` 函数之外),那么它将在自定义报告器中的['onTestModuleCollectd'](./reporters#onTestModuleCollected) 挂钩中可用。
如果元数据是在收集过程中附加的(在 `test` 函数之外),那么它将在自定义报告器中的 ['onTestModuleCollectd'](./reporters#onTestModuleCollected) 挂钩中可用。
:::

## diagnostic
Expand Down Expand Up @@ -126,8 +126,9 @@ interface ImportDuration {
这是 Vite 的 [`DevEnvironment`](https://cn.vite.dev/guide/api-environment),用于转换测试模块中的所有文件。

::: details 历史

- `v4.0.15`: 作为实验性功能添加
:::
:::

## toTestSpecification <Version>4.1.0</Version> {#totestspecification}

Expand Down
11 changes: 10 additions & 1 deletion api/advanced/test-project.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ title: TestProject
名称是由用户分配或由 Vitest 解析的唯一字符串。如果用户没有提供名称,Vitest 会尝试加载项目根目录中的 `package.json` 并从中获取 `name` 属性。如果没有 `package.json`,Vitest 默认使用文件夹的名称。内联项目使用数字作为名称(转换为字符串)。

::: code-group

```ts [node.js]
import { createVitest } from 'vitest/node'

Expand All @@ -24,6 +25,7 @@ vitest.projects.map(p => p.name) === [
'custom'
]
```

```ts [vitest.config.js]
import { defineConfig } from 'vitest/config'

Expand All @@ -48,6 +50,7 @@ export default defineConfig({
},
})
```

:::

::: info
Expand All @@ -74,6 +77,7 @@ const config: SerializedConfig = vitest.projects[0].serializedConfig
```ts
project.serializedConfig === project.serializedConfig // ❌
```

:::

## globalConfig
Expand Down Expand Up @@ -120,6 +124,7 @@ function provide<T extends keyof ProvidedContext & string>(
除了 [`config.provide`](/config/provide) 字段外,还提供了一种向测试提供自定义值的方法。所有值在存储之前都通过 [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone) 进行验证,但 `providedContext` 上的值本身不会被克隆。

::: code-group

```ts [node.js]
import { createVitest } from 'vitest/node'

Expand All @@ -128,10 +133,12 @@ const project = vitest.projects.find(p => p.name === 'custom')
project.provide('key', 'value')
await vitest.start()
```

```ts [test.spec.js]
import { inject } from 'vitest'
const value = inject('key')
```

:::

这些值可以动态提供。测试中提供的值将在下次运行时更新。
Expand All @@ -144,6 +151,7 @@ export default function setup({ provide }) {
provide('wsPort', 3000)
}
```

:::

## getProvidedContext
Expand Down Expand Up @@ -240,7 +248,7 @@ Vitest 使用 [fast-glob](https://npmx.dev/package/fast-glob) 来查找测试文
- `test.include`、`test.exclude` 用于查找常规测试文件
- `test.includeSource`、`test.exclude` 用于查找源代码中的测试
- `test.typecheck.include`、`test.typecheck.exclude` 用于查找类型检查测试
:::
:::

## matchesTestGlob

Expand Down Expand Up @@ -286,6 +294,7 @@ const dynamicExample = await project.import('./example.js')

dynamicExample !== staticExample // ✅
```

:::

::: info
Expand Down
3 changes: 3 additions & 0 deletions api/advanced/test-specification.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,14 @@ It's possible to have multiple pools in a single test project with [`typecheck.e
请注意,如果这些行中的至少一行没有测试,整个测试套件将会失败。以下是一个正确的 `testLines` 配置示例:

::: code-group

```ts [script.js]
const specification = project.createSpecification(
resolve('./example.test.ts'),
[3, 8, 9],
)
```

```ts:line-numbers{3,8,9} [example.test.js]
import { test, describe } from 'vitest'
Expand All @@ -75,6 +77,7 @@ describe('a group of tests', () => { // [!code error]
test.skip('skipped test')
})
```

:::

## testNamePattern <Version>4.1.0</Version> {#testnamepattern}
Expand Down
Loading
Loading