Skip to content

docs(en): merge docs-cn/sync-docs into docs-cn/dev @ d26d535a #683

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
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
11 changes: 11 additions & 0 deletions .vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,13 @@ import {
groupIconMdPlugin,
groupIconVitePlugin,
} from 'vitepress-plugin-group-icons'
<<<<<<< HEAD
import { tabsMarkdownPlugin } from 'vitepress-plugin-tabs'
import { version } from '../package.json'
=======
import llmstxt from 'vitepress-plugin-llms'
import { version } from '../../package.json'
>>>>>>> d26d535abd4748e0ec0863ff3d1a0a6a7f5eb3a7
import { teamMembers } from './contributors'
import {
bluesky,
Expand Down Expand Up @@ -79,6 +84,7 @@ export default ({ mode }: { mode: string }) => {
'qwik': 'logos:qwik-icon',
},
}),
llmstxt(),
],
},
markdown: {
Expand Down Expand Up @@ -283,6 +289,11 @@ export default ({ mode }: { mode: string }) => {
link: '/guide/browser/multiple-setups',
docFooterText: 'Multiple Setups | Browser Mode',
},
{
text: 'Visual Regression Testing',
link: '/guide/browser/visual-regression-testing',
docFooterText: 'Visual Regression Testing | Browser Mode',
},
],
},
{
Expand Down
8 changes: 7 additions & 1 deletion advanced/runner.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,20 @@ export default CustomRunner
```

::: warning
<<<<<<< HEAD
Vitest 还会将 `ViteNodeRunner` 的实例作为 `__vitest_executor` 属性注入。你可以使用它来处理 `importFile` 方法中的文件(这是 `TestRunner` 和 `BenchmarkRunner` 的默认行为)。

`ViteNodeRunner` 暴露了 `executeId` 方法,该方法用于在友好的 Vite 环境中导入测试文件。这意味着它会在运行时解析导入并转换文件内容,以便 Node 能够理解。
=======
Vitest also injects an instance of `ModuleRunner` from `vite/module-runner` as `moduleRunner` property. You can use it to process files in `importFile` method (this is default behavior of `TestRunner` and `BenchmarkRunner`).

`ModuleRunner` exposes `import` method, which is used to import test files in a Vite-friendly environment. Meaning, it will resolve imports and transform file content at runtime so that Node can understand it:
>>>>>>> d26d535abd4748e0ec0863ff3d1a0a6a7f5eb3a7

```ts
export default class Runner {
async importFile(filepath: string) {
await this.__vitest_executor.executeId(filepath)
await this.moduleRunner.import(filepath)
}
}
```
Expand Down
30 changes: 25 additions & 5 deletions config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,8 +227,13 @@ Vite 将处理内联模块。这可能有助于处理以 ESM 格式传送 `.js`

#### deps.optimizer {#deps-optimizer}

<<<<<<< HEAD
- **类型:** `{ ssr?, web? }`
- **参考:** [依赖优化选项](https://cn.vitejs.dev/config/dep-optimization-options.html)
=======
- **Type:** `{ ssr?, client? }`
- **See also:** [Dep Optimization Options](https://vitejs.dev/config/dep-optimization-options.html)
>>>>>>> d26d535abd4748e0ec0863ff3d1a0a6a7f5eb3a7

启用依赖优化。如果你有很多测试,这可能会提高它们的性能。

Expand All @@ -239,7 +244,11 @@ Vite 将处理内联模块。这可能有助于处理以 ESM 格式传送 `.js`
- 你的 `alias` 配置现在在捆绑包中得到处理
- 测试中的代码更接近于它在浏览器中的运行方式

<<<<<<< HEAD
请注意,只有 `deps.experimentalOptimizer?.[mode].include` 选项中的包会被捆绑(一些插件会自动填充它,比如 Svelte)。 你可以在 [Vite](https://cn.vitejs.dev/config/dep-optimization-options.html) 文档中阅读有关可用选项的更多信息。默认情况,Vitest 的 `experimentalOptimizer.web` 用在 `jsdom` 和 `happy-dom`, 在 `node` 和 `edge` 环境下使用 `experimentalOptimizer.ssr`,但这可以在 [`transformMode`](#transformmode) 进行配置。
=======
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.
>>>>>>> d26d535abd4748e0ec0863ff3d1a0a6a7f5eb3a7

此选项还继承了你的 `optimizeDeps` 配置(对于 web 环境, Vitest 将会继承 `optimizeDeps`,对于 ssr 则是 `ssr.optimizeDeps`)。如果你在 `deps.experimentalOptimizer` 中重新定义 `include`/`exclude`/`entries` 选项,它将在运行测试时覆盖你的 `optimizeDeps`。如果它们在 `exclude` 中配置,Vitest 会自动从 `include` 中删除相同的选项。

Expand All @@ -254,21 +263,29 @@ Vite 将处理内联模块。这可能有助于处理以 ESM 格式传送 `.js`

启用依赖优化。

<<<<<<< HEAD
::: warning
此选项仅适用于 Vite 4.3.2 及更高版本。
:::
=======
#### deps.client {#deps-client}
>>>>>>> d26d535abd4748e0ec0863ff3d1a0a6a7f5eb3a7

#### deps.web <Badge type="info">0.34.2+</Badge>

<<<<<<< HEAD
#### deps.web
=======
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.
>>>>>>> d26d535abd4748e0ec0863ff3d1a0a6a7f5eb3a7

- **类型:** `{ transformAssets?, ... }`

当转换模式设置为 `web` 时应用于外部文件的选项。默认情况下,`jsdom` 和 `happy-dom` 使用 `web` 模式,而 `node` 和 `edge` 环境使用 `ssr` 转换模式,因此这些选项不会影响这些环境中的文件。

通常,`node_modules` 内的文件是外部化的,但这些选项也会影响 [`server.deps.external`](#server-deps-external) 中的文件。

#### deps.web.transformAssets
#### deps.client.transformAssets

- **类型:** `boolean`
- **默认值:** `true`
Expand All @@ -281,7 +298,7 @@ Vitest 是否应该像 Vite 在浏览器中一样处理静态资源(.png、.sv
目前,此选项适用于 [`vmThreads`](#vmthreads) 和 [`vmForks`](#vmForks) 池。
:::

#### deps.web.transformCss
#### deps.client.transformCss

- **类型:** `boolean`
- **默认值:** `true`
Expand All @@ -294,7 +311,7 @@ Vitest 是否应该像 Vite 在浏览器中一样处理静态资源(.css, .scs
目前,此选项仅适用于 [`vmThreads`](#vmthreads) 和 [`vmForks`](#vmForks) 池。
:::

#### deps.web.transformGlobPattern
#### deps.client.transformGlobPattern

- **类型:** `RegExp | RegExp[]`
- **默认值:** `[]`
Expand Down Expand Up @@ -556,7 +573,7 @@ import type { Environment } from 'vitest'

export default <Environment>{
name: 'custom',
transformMode: 'ssr',
viteEnvironment: 'ssr',
setup() {
// custom setup
return {
Expand Down Expand Up @@ -616,7 +633,7 @@ In CI, or when run from a non-interactive shell, "watch" mode is not the default

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.

To correctly rerun those tests, you can define a regex pattern and a function that retuns a list of test files to run.
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'
Expand Down Expand Up @@ -1681,6 +1698,7 @@ test('doNotRun', () => {

将在每次测试前调用 [`vi.unstubAllGlobals`](/api/#vi-unstuballglobals)。

<<<<<<< HEAD
### testTransformMode {#testtransformmode}

- **类型:** `{ web?, ssr? }`
Expand Down Expand Up @@ -1717,6 +1735,8 @@ export default defineConfig({
})
```

=======
>>>>>>> d26d535abd4748e0ec0863ff3d1a0a6a7f5eb3a7
### snapshotFormat<NonProjectOption />

- **类型:** `PrettyFormatOptions`
Expand Down
218 changes: 218 additions & 0 deletions guide/browser/assertion-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,12 @@ function toHaveSelection(selection?: string): Promise<void>
这在检查元素内是否选择了文本或部分文本时非常有用。该元素可以是文本类型的输入框、`textarea`,或者是任何包含文本的其他元素,例如段落、`span`、`div` 等。

::: warning
<<<<<<< HEAD
预期的选择是一个字符串,它不允许检查选择范围的索引。
=======
The expected selection is a string, it does not allow to check for
selection range indices.
>>>>>>> d26d535abd4748e0ec0863ff3d1a0a6a7f5eb3a7
:::

```html
Expand Down Expand Up @@ -1000,3 +1005,216 @@ await expect.element(queryByTestId('parent')).toHaveSelection('ected text')
await expect.element(queryByTestId('prev')).not.toHaveSelection()
await expect.element(queryByTestId('next')).toHaveSelection('ne')
```

## toMatchScreenshot <Badge type="warning">experimental</Badge>

```ts
function toMatchScreenshot(
options?: ScreenshotMatcherOptions,
): Promise<void>
function toMatchScreenshot(
name?: string,
options?: ScreenshotMatcherOptions,
): Promise<void>
```

::: tip
The `toMatchScreenshot` assertion can be configured globally in your
[Vitest config](/guide/browser/config#browser-expect-tomatchscreenshot).
:::

This assertion allows you to perform visual regression testing by comparing
screenshots of elements or pages against stored reference images.

When differences are detected beyond the configured threshold, the test fails.
To help identify the changes, the assertion generates:

- The actual screenshot captured during the test
- The expected reference screenshot
- A diff image highlighting the differences (when possible)

::: warning Screenshots Stability
The assertion automatically retries taking screenshots until two consecutive
captures yield the same result. This helps reduce flakiness caused by
animations, loading states, or other dynamic content. You can control this
behavior with the `timeout` option.

However, browser rendering can vary across:

- Different browsers and browser versions
- Operating systems (Windows, macOS, Linux)
- Screen resolutions and pixel densities
- GPU drivers and hardware acceleration
- Font rendering and system fonts

It is recommended to read the
[Visual Regression Testing guide](/guide/browser/visual-regression-testing) to
implement this testing strategy efficiently.
:::

::: tip
When a screenshot comparison fails due to **intentional changes**, you can
update the reference screenshot by pressing the `u` key in watch mode, or by
running tests with the `-u` or `--update` flags.
:::

```html
<button data-testid="button">Fancy Button</button>
```

```ts
// basic usage, auto-generates screenshot name
await expect.element(getByTestId('button')).toMatchScreenshot()

// with custom name
await expect.element(getByTestId('button')).toMatchScreenshot('fancy-button')

// with options
await expect.element(getByTestId('button')).toMatchScreenshot({
comparatorName: 'pixelmatch',
comparatorOptions: {
allowedMismatchedPixelRatio: 0.01,
},
})

// with both name and options
await expect.element(getByTestId('button')).toMatchScreenshot('fancy-button', {
comparatorName: 'pixelmatch',
comparatorOptions: {
allowedMismatchedPixelRatio: 0.01,
},
})
```

### Options

- `comparatorName: "pixelmatch" = "pixelmatch"`

The name of the algorithm/library used for comparing images.

Currently, [`"pixelmatch"`](https://github.com/mapbox/pixelmatch) is the only
supported comparator.

- `comparatorOptions: object`

These options allow changing the behavior of the comparator. What properties
can be set depends on the chosen comparator algorithm.

Vitest has set default values out of the box, but they can be overridden.

- [`"pixelmatch"` options](#pixelmatch-comparator-options)

::: warning
**Always explicitly set `comparatorName` to get proper type inference for
`comparatorOptions`**.

Without it, TypeScript won't know which options are valid:

```ts
// ❌ TypeScript can't infer the correct options
await expect.element(button).toMatchScreenshot({
comparatorOptions: {
// might error when new comparators are added
allowedMismatchedPixelRatio: 0.01,
},
})

// ✅ TypeScript knows these are pixelmatch options
await expect.element(button).toMatchScreenshot({
comparatorName: 'pixelmatch',
comparatorOptions: {
allowedMismatchedPixelRatio: 0.01,
},
})
```
:::

- `screenshotOptions: object`

The same options allowed by
[`locator.screenshot()`](/guide/browser/locators.html#screenshot), except for:

- `'base64'`
- `'path'`
- `'save'`
- `'type'`

- `timeout: number = 5_000`

Time to wait until a stable screenshot is found.

Setting this value to `0` disables the timeout, but if a stable screenshot
can't be determined the process will not end.

#### `"pixelmatch"` comparator options

The following options are available when using the `"pixelmatch"` comparator:

- `allowedMismatchedPixelRatio: number | undefined = undefined`

The maximum allowed ratio of differing pixels between the captured screenshot
and the reference image.

Must be a value between `0` and `1`.

For example, `allowedMismatchedPixelRatio: 0.02` means the test will pass
if up to 2% of pixels differ, but fail if more than 2% differ.

- `allowedMismatchedPixels: number | undefined = undefined`

The maximum number of pixels that are allowed to differ between the captured
screenshot and the stored reference image.

If set to `undefined`, any non-zero difference will cause the test to fail.

For example, `allowedMismatchedPixels: 10` means the test will pass if 10 or
fewer pixels differ, but fail if 11 or more differ.

- `threshold: number = 0.1`

Acceptable perceived color difference between the same pixel in two images.

Value ranges from `0` (strict) to `1` (very lenient). Lower values mean small
differences will be detected.

The comparison uses the [YIQ color space](https://en.wikipedia.org/wiki/YIQ).

- `includeAA: boolean = false`

If `true`, disables detection and ignoring of anti-aliased pixels.

- `alpha: number = 0.1`

Blending level of unchanged pixels in the diff image.

Ranges from `0` (white) to `1` (original brightness).

- `aaColor: [r: number, g: number, b: number] = [255, 255, 0]`

Color used for anti-aliased pixels in the diff image.

- `diffColor: [r: number, g: number, b: number] = [255, 0, 0]`

Color used for differing pixels in the diff image.

- `diffColorAlt: [r: number, g: number, b: number] | undefined = undefined`

Optional alternative color for dark-on-light differences, to help show what's
added vs. removed.

If not set, `diffColor` is used for all differences.

- `diffMask: boolean = false`

If `true`, shows only the diff as a mask on a transparent background, instead
of overlaying it on the original image.

Anti-aliased pixels won't be shown (if detected).

::: warning
When both `allowedMismatchedPixels` and `allowedMismatchedPixelRatio` are set,
the more restrictive value is used.

For example, if you allow 100 pixels or 2% ratio, and your image has 10,000
pixels, the effective limit would be 100 pixels instead of 200.
:::
Loading