Skip to content
4 changes: 2 additions & 2 deletions api/browser/assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ interface ExpectPollOptions {
message?: string
}
```

<!-- TODO: translation -->
::: tip
`expect.element` 是 `expect.poll(() => element)`的简写,工作方式完全相同。
Like [`expect.poll`](/api/expect#poll), `expect.element` retries DOM assertions until they pass or the timeout is reached. When it receives a locator, Vitest resolves it with [`locator.findElement()`](/api/browser/locators#findelement) before running the DOM assertion. The `timeout` option applies to the whole retry operation. The `interval` option controls how often failed DOM assertions are retried, but locator resolution uses `findElement`'s own increasing retry intervals.

`toHaveTextContent` 以及其他所有断言在常规的 `expect` 中仍然可用,但没有内置的重试机制:

Expand Down
16 changes: 15 additions & 1 deletion api/browser/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,23 @@ const frame = page.frameLocator(
await frame.getByText('Hello World').click() // ✅
await frame.click() // ❌ 不可用
```
<!-- TODO: translation -->
::: danger IMPORTANT
By default `frameLocator` does not support querying elements with `expect.element()` in cross-origin iframes. Interactive methods, such as `.click()` work fine. This is different behaviour than Playwright.

```ts
const frame = page.frameLocator(page.getByTestId('cross-origin-iframe'))
const button = frame.getByRole('button', { name: 'Submit' })

await button.click() // Interactive methods work fine ✅
await expect.element(button).toBeVisible() // Querying elements does not work ❌
```

If you need to work with cross-origin iframes, you'll need to pass `args: ["--disable-web-security"]` in [`launchOptions`](/config/browser/playwright.html#launchoptions). Or alternatively create a custom [browser command](/api/browser/commands.html#custom-commands) that accesses the iframe on server side where it's available.
:::

::: danger IMPORTANT
目前,`frameLocator` 方法仅支持 `playwright` 提供者。
At the moment, the `frameLocator` method is only supported by the `playwright` provider.

交互方法(如 `click` 或 `fill`)在 iframe 内的元素上始终可用,但使用 `expect.element` 进行断言时要求 iframe 具有[同源策略](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)。
:::
Expand Down
6 changes: 4 additions & 2 deletions api/expect.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,13 @@ test('expect.soft test', () => {

```ts
interface ExpectPoll extends ExpectStatic {
(actual: () => T, options?: { interval?: number; timeout?: number; message?: string }): Promise<Assertions<T>>
(actual: (options: { signal: AbortSignal }) => T, options?: { interval?: number; timeout?: number; message?: string }): Promise<Assertions<Awaited<T>>>
}
```
<!-- TODO: translation -->
`expect.poll` reruns the _assertion_ until it is succeeded. You can configure how often Vitest retries and how long it waits by setting `interval` and `timeout` options. The `timeout` applies to the whole polling operation, including pending callback and async matcher execution.

`expect.poll` 重新运行断言,直到成功为止。你可以通过设置 `interval` 和 `timeout` 选项来配置 Vitest 应重新运行 `expect.poll` 回调的次数。
The callback receives an `AbortSignal` that is aborted when the poll timeout is reached.

如果在 `expect.poll` 回调中抛出错误,Vitest 将重试直到超时为止。

Expand Down
4 changes: 3 additions & 1 deletion api/mock.md
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,9 @@ MyClass.mock.instances[0] === a
若构造函数显式返回值,该值不会存入 `instances`,而会出现在 `results` 中:

```js
const Spy = vi.fn(() => ({ method: vi.fn() }))
const Spy = vi.fn(function () {
return { method: vi.fn() }
})
const a = new Spy()

Spy.mock.instances[0] !== a
Expand Down
49 changes: 49 additions & 0 deletions config/browser/locators.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,52 @@ outline: deep
const locator = page.getByText('Hello, World', { exact: true })
await locator.click()
```
<!-- TODO: translation -->
## browser.locators.errorFormat <Version>5.0.0</Version> {#browser-locators-errorformat}

- **Type:** `'html' | 'aria' | 'all'`
- **Default:** `'all'`

Controls what Vitest prints when a locator cannot find an element. Vitest prints information for the DOM subtree where the locator search ran, or `document.body` for page-level locators.

- `'html'` prints that DOM subtree as HTML using [`utils.prettyDOM`](/api/browser/context#prettydom).
- `'aria'` prints that DOM subtree as an [ARIA snapshot](/guide/browser/aria-snapshots), which focuses on accessible roles, names, and state.
- `'all'` prints the ARIA snapshot first, followed by the HTML output.

```ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
test: {
browser: {
enabled: true,
locators: {
errorFormat: 'aria',
},
},
},
})
```

For example, `all` displays a following error:

```html
VitestBrowserElementError: Cannot find element with locator: getByRole('button', { name: 'Save' })

ARIA tree:
- main:
- heading "Settings" [level=1]
- button "Cancel"

HTML:
<body>
<main>
<h1>
Settings
</h1>
<button>
Cancel
</button>
</main>
</body>
```
52 changes: 52 additions & 0 deletions guide/common-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,55 @@ test('rejects for missing user', async () => {
await expect(fetchUser(123)).rejects.toThrow('User 123 not found')
})
```
<!-- TODO: translation -->
## Package fails to load in Vitest but works in your app

Some packages work in an app build but fail in Vitest because they are only valid after a bundler has rewritten or resolved them. When Vitest externalizes a dependency, Node.js loads it directly, so Node's ESM and package rules apply. See Node.js documentation on [ECMAScript modules](https://nodejs.org/docs/latest/api/esm.html) and [packages](https://nodejs.org/docs/latest/api/packages.html) for the precise rules.

Common examples include packages that:

- ship ESM syntax in `.js` files without `"type": "module"`
- use extensionless relative imports in ESM files
- have incorrect `exports`, `imports`, `main`, or `module` entries
- mix CommonJS and ESM entry points in a way that only works after bundling
- import CSS or other non-JavaScript files that are expected to be handled by a bundler

You might see errors such as:

- `Cannot find module './relative-path' imported from ...`
- `Unexpected token 'export'`
- `Cannot use import statement outside a module`
- `Module ... seems to be an ES Module but shipped in a CommonJS package.`
- `Unknown file extension ".css"`

When possible, fix the package so Node.js can load it directly: add `"type": "module"` for ESM `.js` files, use `.mjs`, include explicit file extensions in ESM imports, and make sure `exports` points to files Node.js can load.

If you cannot fix the package itself, inline it so Vite handles it instead of passing it to Node.js as an external dependency. Inline the whole dependency chain that leads to the invalid package. If your source imports `wrapper-package`, and `wrapper-package` imports `broken-package`, inline both packages:

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

export default defineConfig({
test: {
server: {
deps: {
inline: ['wrapper-package', 'broken-package'],
},
},
},
})
```

You can also use Vite's [`ssr.resolve.noExternal`](https://vite.dev/config/ssr-options#ssr-resolve-noexternal) for the same purpose. Vitest merges `ssr.resolve.noExternal` into [`server.deps.inline`](/config/server#server-deps-inline), so this is useful when the dependency also needs to be bundled by Vite in SSR builds:

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

export default defineConfig({
ssr: {
resolve: {
noExternal: ['wrapper-package', 'broken-package'],
},
},
})
```
4 changes: 2 additions & 2 deletions guide/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ bun add -D vitest

:::

:::tip 提示
Vitest 需要 Vite >=v6.0.0 和 Node >=v20.0.0
:::tip
Vitest 需要 Vite >=v6.4.0 and 和 >=v22.12.0
:::

如果在 `package.json` 中安装一份 `vitest` 的副本,可以使用上面列出的方法之一。然而,如果更倾向于直接运行 `vitest` ,可以使用 `npx vitest`( `npx` 会随着 npm 和 Node.js 一起被安装)。
Expand Down
Loading