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 api/advanced/runner.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export default class Runner {
:::

::: tip
快照支持和其他功能是依赖于测试运行器的。如果你想保留这些功能,可以从 `vitest/runners` 导入 `VitestTestRunner` 并将你的测试运行器继承该类。如果你想扩展基准测试功能,它还提供了 `NodeBenchmarkRunner`。
快照支持和其他功能是依赖于测试运行器的。如果你想保留这些功能,可以从 `vitest` 导入 `TestRunner` 并将你的测试运行器继承该类。如果你想扩展基准测试功能,它还提供了 `NodeBenchmarkRunner`。
:::

## Tasks {#tasks}
Expand Down
55 changes: 53 additions & 2 deletions api/browser/locators.md
Original file line number Diff line number Diff line change
Expand Up @@ -1052,6 +1052,56 @@ function all(): Locator[]
在内部,此方法调用 `.elements` 并使用 [`page.elementLocator`](/api/browser/context#page) 包装每个元素。

- [更多内容请参阅 `locator.elements()`](#elements)
<!-- TODO: translation -->
### serialize

```ts
function serialize(): SerializedLocator
```

Returns a JSON-serializable representation of the locator. The returned object has two fields:

- [`selector`](#selector): the provider-specific selector string used to query the element at runtime.
- `locator`: a human-readable description of the locator (e.g. `getByRole('button')`), used for error messages and tracing. Equivalent to calling [`asLocator()`](#aslocator).

This is primarily intended for forwarding a locator to a [browser command](/api/browser/commands), which runs in Node and cannot receive a live `Locator` instance:

```ts
import { commands, page } from 'vitest/browser'

await commands.myCommand(page.getByRole('button').serialize())
```

::: tip
Vitest automatically serializes any `Locator` argument passed to a command, so calling `serialize()` explicitly is rarely necessary. You can also use `JSON.stringify(locator)` (it calls [`toJSON`](#tojson) internally), which produces the same result.
:::

### toJSON

```ts
function toJSON(): SerializedLocator
```

Alias of [`serialize`](#serialize). Defined so that `JSON.stringify(locator)` and structured-clone-based transports return a `SerializedLocator` object.

### asLocator

```ts
function asLocator(): string
```

Returns a human-readable description of the locator using the JavaScript locator syntax (e.g. `getByRole('button', { name: 'Submit' })`). This is the same string exposed as the `locator` field of [`serialize()`](#serialize) and is used in error messages and traces.

```ts
import { page } from 'vitest/browser'

const button = page.getByRole('button', { name: 'Submit' })
button.asLocator() // "getByRole('button', { name: 'Submit' })"
```

::: tip
Use [`selector`](#selector) when you need the provider-specific string to forward to a [browser command](/api/browser/commands). Use `asLocator()` only for diagnostic output. The returned string is not meant to be re-used to query elements.
:::

## Properties

Expand All @@ -1064,8 +1114,9 @@ function all(): Locator[]

```ts [commands.ts]
import type { BrowserCommand } from 'vitest/node'
import type { SerializedLocator } from '@vitest/browser'

const test: BrowserCommand<string> = function test(context, selector) {
const test: BrowserCommand<SerializedLocator> = function test(context, { selector }) {
// playwright
await context.iframe.locator(selector).click()
// webdriverio
Expand All @@ -1079,7 +1130,7 @@ import { commands, page } from 'vitest/browser'

test('works correctly', async () => {
await commands.test(page.getByText('Hello').selector) // ✅
// Vitest 会自动将其解包为字符串
// Vitest 会自动将其解包为 SerializedLocator 对象
await commands.test(page.getByText('Hello')) // ✅
})
```
Expand Down
33 changes: 13 additions & 20 deletions api/describe.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,19 @@ describe.concurrent('suite', () => {
test.concurrent('concurrent test 3', async () => { /* ... */ })
})
```
<!-- TODO: translation -->
Set `concurrent` to `false` to opt out of concurrency inherited from a parent suite or [`sequence.concurrent`](/config/sequence#sequence-concurrent):

```ts
describe.concurrent('suite', () => {
test('concurrent test', async () => { /* ... */ })

describe('sequential suite', { concurrent: false }, () => {
test('sequential test 1', async () => { /* ... */ })
test('sequential test 2', async () => { /* ... */ })
})
})
```

`.skip`、`.only` 和 `.todo` 适用于并发测试套件。以下所有组合都有效:

Expand All @@ -230,26 +243,6 @@ describe.concurrent('suite', () => {
})
```

## describe.sequential

- **别名:** `suite.sequential`

测试套件中的 `describe.sequential` 会将所有测试标记为顺序执行。该特性适用于需要在 `describe.concurrent` 并发测试套件中按顺序运行测试,或使用 `--sequence.concurrent` 命令行选项。

```ts
import { describe, test } from 'vitest'

describe.concurrent('suite', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })

describe.sequential('', () => {
test('sequential test 1', async () => { /* ... */ })
test('sequential test 2', async () => { /* ... */ })
})
})
```

## describe.shuffle

- **别名:** `suite.shuffle`
Expand Down
10 changes: 5 additions & 5 deletions api/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ beforeEach(async () => {
```

此处,`beforeEach` 确保每个测试都会添加用户。

`beforeEach` 还可以返回一个可选的清理函数(等价于 [`afterEach`](#aftereach)):
<!-- TODO: translation -->
`beforeEach` can also return an optional cleanup function. It's similar to [`afterEach`](#aftereach). The only difference is that it's executed after all other `afterEach` hooks:

```ts
import { beforeEach } from 'vitest'
Expand All @@ -44,7 +44,7 @@ beforeEach(async () => {
// 在每次测试运行前调用一次
await prepareSomething()

// 清理函数,在每次测试运行后调用一次
// 清理函数,在每次测试运行后调用一次,在 afterEach 钩子之后执行
return async () => {
await resetSomething()
}
Expand Down Expand Up @@ -103,7 +103,7 @@ beforeAll(async () => {

此处,`beforeAll` 确保在测试运行前完成模拟数据的初始化。

`beforeAll` 还可以返回一个可选的清理函数(等价于 [`afterAll`](#afterall)):
`beforeAll` 还可以返回一个可选的清理函数(等价于 [`afterAll`](#afterall))。唯一区别在于该钩子会在所有其他 `afterAll` 钩子执行完毕后运行

```ts
import { beforeAll } from 'vitest'
Expand All @@ -112,7 +112,7 @@ beforeAll(async () => {
// 在所有测试运行之前调用一次
await startMocking()

// 清理函数,在所有测试运行之后调用一次
// 清理函数,在所有测试运行结束后调用一次,在所有 afterAll 钩子之后执行
return async () => {
await stopMocking()
}
Expand Down
39 changes: 7 additions & 32 deletions api/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,14 @@ describe(
- **别名:** [`test.concurrent`](#test-concurrent)

是否与测试套件中其他并发测试并行运行。
<!-- TODO: translation -->
Set `concurrent` to `false` to opt out of concurrency inherited from [`describe.concurrent`](/api/describe#describe-concurrent) or [`sequence.concurrent`](/config/sequence#sequence-concurrent):

### sequential

- **类型:** `boolean`
- **默认值:** `true`
- **别名:** [`test.sequential`](#test-sequential)

是否按顺序运行测试。如果同时指定了 `concurrent` 和 `sequential`,`concurrent` 优先生效。
```ts
test('runs sequentially', { concurrent: false }, async () => {
// ...
})
```

### skip

Expand Down Expand Up @@ -453,31 +453,6 @@ test.concurrent('test 2', async ({ expect }) => {

注意,如果测试是同步的,Vitest 仍会按顺序运行它们。

## test.sequential

- **别名:** `it.sequential`

`test.sequential` 将测试标记为顺序执行。适用于在 `describe.concurrent` 或 `--sequence.concurrent` 命令选项下按顺序运行测试的场景。
```ts
import { describe, test } from 'vitest'

// 配置项 { sequence: { concurrent: true } } 开启时
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })

test.sequential('sequential test 1', async () => { /* ... */ })
test.sequential('sequential test 2', async () => { /* ... */ })

// 在并发测试套件内
describe.concurrent('suite', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })

test.sequential('sequential test 1', async () => { /* ... */ })
test.sequential('sequential test 2', async () => { /* ... */ })
})
```

## test.todo

- **别名:** `it.todo`
Expand Down
2 changes: 1 addition & 1 deletion config/attachmentsdir.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ outline: deep
# attachmentsDir

- **类型:** `string`
- **默认值:** `'.vitest-attachments'`
- **默认值:** `'.vitest/attachments'`

用于存储 [`context.annotate`](/guide/test-context#annotate) 所创建附件的目录路径(相对于项目根目录)。
4 changes: 4 additions & 0 deletions config/browser/expect.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ export default defineConfig({

[`attachmentsDir`](/config/attachmentsdir) 配置项提供的值,如果未配置则使用其默认值。

- `project: TestProject` <Version type="experimental">4.1.6</Version> <Experimental />

The [`TestProject`](/api/advanced/test-project) the test belongs to.

例如,以下示例按浏览器分组存储截图:

```ts
Expand Down
11 changes: 11 additions & 0 deletions config/coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,14 @@ export default defineConfig({
- **命令行终端:** `--coverage.changed`, `--coverage.changed=<commit/branch>`

仅收集自指定提交或分支以来更改的文件的代码覆盖率。设置为 `true` 时,使用已暂存和未暂存的更改。
<!-- TODO: translation -->
## coverage.autoAttachSubprocess <Version>5.0.0</Version> {#coverage-autoattachsubprocess}

- **Type:** `boolean`
- **Default:** `false`
- **Available for providers:** `'v8'`
- **CLI:** `--coverage.autoAttachSubprocess`

Track coverage of the `node:child_process` and `node:worker_threads` spawned during test run.

Note that this option has some performance overhead as its using [`NODE_V8_COVERAGE`](https://nodejs.org/api/cli.html#node-v8-coveragedir) internally. This triggers Node to write lots of unnecessary files on file system.
16 changes: 8 additions & 8 deletions config/reporters.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ interface UserConfig {

type ConfigReporter = string | Reporter | [string, object?]
```

- **默认值:** [`'default'`](/guide/reporters#default-reporter)(当 `process.env.GITHUB_ACTIONS === 'true'` 时为 <code>[['default'](/guide/reporters#default-reporter), ['github-actions'](/guide/reporters#github-actions-reporter)]</code>)
- **命令行终端:**
- `--reporter=tap` 用于单个报告器
- `--reporter=verbose --reporter=github-actions` 用于多个报告器
<!-- TODO: translation -->
- **Default:** [`'default'`](/guide/reporters#default-reporter). See [Default Reporters](/guide/reporters#default-reporters) for environment-specific behavior.
- **CLI:**
- `--reporter=tap` for a single reporter
- `--reporter=verbose --reporter=github-actions` for multiple reporters

此选项定义在 Vitest 测试运行期间可用的单个报告器或报告器列表。

Expand Down Expand Up @@ -49,14 +49,14 @@ type ConfigReporter = string | Reporter | [string, object?]

::: code-group
```js [vitest.config.js]
import { defineConfig } from 'vitest/config'
import { configDefaults, defineConfig } from 'vitest/config'

export default defineConfig({
test: {
reporters: [
'default',
...configDefaults.reporters,
// 条件报告器
process.env.CI ? 'github-actions' : {},
...(process.env.CI ? ['html'] : []),
// 来自 npm 包的自定义报告器
// 选项将以元组形式向下传递
[
Expand Down
4 changes: 2 additions & 2 deletions guide/browser/visual-regression-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,10 +276,10 @@ Reference screenshot:
tests/__screenshots__/button.test.ts/button-chromium-darwin.png

Actual screenshot:
tests/.vitest-attachments/button.test.ts/button-chromium-darwin-actual.png
tests/.vitest/attachments/button.test.ts/button-chromium-darwin-actual.png

Diff image:
tests/.vitest-attachments/button.test.ts/button-chromium-darwin-diff.png
tests/.vitest/attachments/button.test.ts/button-chromium-darwin-diff.png
```

### 如何解读差异图 {#understanding-the-diff-image}
Expand Down
9 changes: 8 additions & 1 deletion guide/cli-generated.md
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,13 @@ Coverage reporters to use. Visit [`coverage.reporter`](/config/coverage#coverage
- **配置:** [coverage.htmlDir](/config/coverage#coverage-htmldir)

UI 模式和 HTML 报告器中提供的 HTML 覆盖率输出目录。
<!-- TODO: translation -->
### coverage.autoAttachSubprocess

- **CLI:** `--coverage.autoAttachSubprocess`
- **Config:** [coverage.autoAttachSubprocess](/config/coverage#coverage-autoattachsubprocess)

Track coverage of the `node:child_process` and `node:worker_threads` spawned during test run. Supported only by `v8` provider. (default: false)

### mode

Expand Down Expand Up @@ -865,7 +872,7 @@ UI 模式和 HTML 报告器中提供的 HTML 覆盖率输出目录。
- **命令行终端:** `--attachmentsDir <dir>`
- **配置:** [attachmentsDir](/config/attachmentsdir)

`context.annotate` 方法所生成附件的存储目录 (默认值: `.vitest-attachments`)
`context.annotate` 方法所生成附件的存储目录 (默认值: `.vitest/attachments`)

### run

Expand Down
4 changes: 2 additions & 2 deletions guide/improving-performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: blob-attachments-${{ matrix.shardIndex }}
path: .vitest-attachments/**
path: .vitest/**
include-hidden-files: true
retention-days: 1

Expand Down Expand Up @@ -222,7 +222,7 @@ jobs:
- name: Download attachments from GitHub Actions Artifacts
uses: actions/download-artifact@v4
with:
path: .vitest-attachments
path: .vitest
pattern: blob-attachments-*
merge-multiple: true

Expand Down
Loading
Loading