Skip to content

docs(en): merge docs-cn/sync-docs into docs-cn/dev @ c62ef0f5 #682

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 5 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'
>>>>>>> c62ef0f548755866177d35b4928353aede76147f
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
2 changes: 1 addition & 1 deletion config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,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
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.
>>>>>>> c62ef0f548755866177d35b4928353aede76147f
:::

```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.
:::
8 changes: 8 additions & 0 deletions guide/browser/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ outline: deep

### 文件处理

<<<<<<< HEAD
在浏览器端的测试中,你可以通过 `readFile` 、`writeFile` 和 `removeFile` 这些 API 来操作文件。从 Vitest 3.2 版本起,所有文件路径都会相对于 [项目](/guide/projects) 根目录解析(默认为 `process.cwd()`,除非你手动修改过)。在此之前,路径是以测试文件所在位置作为基准进行解析的。
=======
You can use the `readFile`, `writeFile`, and `removeFile` APIs to handle files in your browser tests. Since Vitest 3.2, all paths are resolved relative to the [project](/guide/projects) root (which is `process.cwd()`, unless overridden manually). Previously, paths were resolved relative to the test file.
>>>>>>> c62ef0f548755866177d35b4928353aede76147f

默认情况下,Vitest 使用 `utf-8` 编码,但你可以使用选项覆盖它。

Expand Down Expand Up @@ -162,7 +166,11 @@ Vitest 在上下文对象上公开了一些 `webdriverio` 特有属性。

- `browser` 是 `WebdriverIO.Browser` API.

<<<<<<< HEAD
Vitest 通过在调用命令前调用 `browser.switchToFrame` 自动将 `webdriver` 上下文切换到测试 iframe,因此 `$` 和 `$` 方法将引用 iframe 内的元素,而不是 orchestrator 中的元素,但非 Webdriver API 仍将引用 parent frame 上下文。
=======
Vitest automatically switches the `webdriver` context to the test iframe by calling `browser.switchFrame` before the command is called, so `$` and `$$` methods refer to the elements inside the iframe, not in the orchestrator, but non-webdriver APIs will still refer to the parent frame context.
>>>>>>> c62ef0f548755866177d35b4928353aede76147f

::: tip
如果我们使用的是 TypeScript,请记得在您的 [setup 文件](/config/#setupfile)或 [config 文件](/config/)中引用 `@vitest/browser/providers/webdriverio` ,以便获得自动补全功能。
Expand Down
Loading