# Vitest


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

[`Vitest`](https://AnswerDotAI.github.io/fastcdp/vitest.html#vitest)
owns the test runner and its hidden page, which has no visible tab or
window. It connects to CDP Chrome on port 9223 unless you pass an
existing [`CDP`](https://AnswerDotAI.github.io/fastcdp/core.html#cdp)
connection. It never launches or quits Chrome.

Install `vite-plus`, `@vitest/browser`, and `fastcdp-vitest` in your
JavaScript project. Import `fastcdp` from `fastcdp-vitest` in
`vite.config.js` and configure Browser Mode with `provider: fastcdp()`
and one `{ browser: 'chromium' }` instance. Run `vp test` or
`vp test watch` directly (the provider spawns `fastcdp-vitest-bridge`
automatically), or drive runs from Python with
[`Vitest`](https://AnswerDotAI.github.io/fastcdp/vitest.html#vitest).

Use ordinary `vitest-browser-svelte` rendering, Vitest locators and
`expect.element`. Clicks, filling, typing, modifier shortcuts and Tab
use native Chrome input. Holding non-modifier keys and unsupported
action options raise errors. The provider does not install or launch a
browser.

`run` accepts the same filename filters as `vp test`. It returns
Vitest’s native JSON report (`testResults`, `numPassedTests`, and so on)
with `returncode` and combined `success`. Runner output is in `output`.
Repeating `run` reuses the owned tab. The last component remains
available for inspection until `close`.

``` python
from fastcore.test import test_eq, expect_fail
```

## Running Vitest from Python

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/fastcdp/blob/main/fastcdp/vitest.py#L36"
target="_blank" style="float:right; font-size:smaller">source</a>

### Vitest

``` python
def Vitest(
    root:str | pathlib.Path='.', # JavaScript project containing the Vitest config and dependencies
    cdp:fastcdp.core.CDP=None, # Existing connection; otherwise connect to CDP Chrome on 9223
):
```

*Run browser tests with fastcdp; retain the last test page until
`close`.*

[`Vitest`](https://AnswerDotAI.github.io/fastcdp/vitest.html#vitest)
connects to CDP Chrome on port 9223 on entry unless you supply an
existing [`CDP`](https://AnswerDotAI.github.io/fastcdp/core.html#cdp)
connection. `close` always closes its hidden test tab, and closes the
CDP connection only if
[`Vitest`](https://AnswerDotAI.github.io/fastcdp/vitest.html#vitest)
created it; Chrome itself keeps running.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/fastcdp/blob/main/fastcdp/vitest.py#L63"
target="_blank" style="float:right; font-size:smaller">source</a>

### Vitest.run

``` python
async def run(
    *filters:str, # Standard Vitest test-file filters
    env:dict=None, # Additional environment, e.g. the app's Rustygate URL
    timeout:float=60, # Seconds to wait for `vp test`; shutdown gets another five seconds
):
```

*Return structured Vitest results, including failed assertions and
nonzero exit status.*

[`Vitest.run`](https://AnswerDotAI.github.io/fastcdp/vitest.html#vitest.run)
opens a token-protected local
[`ExtChannel`](https://AnswerDotAI.github.io/fastcdp/ext.html#extchannel),
passes its WebSocket URL to `vp test` via `FASTCDP_VITEST`, and collects
Vitest’s JSON report from a temporary directory. If `vp test` exceeds
`timeout`, `run` terminates the subprocess (falling back to `kill` after
five seconds) and still captures its combined stdout and stderr in
`self.output`.

Drive a project from Python with `async with Vitest(...)`:

``` python
from fastcdp.vitest import Vitest

async with Vitest('/path/to/svelte-project') as vt:
    result = await vt.run()
    result
    await vt.page.screenshot()
```

## Browser actions and input

`_node` locates the Vitest test iframe matching `msg.testPath`, runs
`__fastcdp_find` inside it with `timeout` and `strict` options, resolves
the returned DOM node to a `backendNodeId`, and releases the remote
object handle.

`_keyboard` translates Vitest user-event keyboard descriptors into
native Chrome key events. It normalizes `\n` and `\r` to `Enter`, tracks
held modifier keys (`Alt`, `Control`, `Meta`, `Shift`) across calls, and
releases remaining modifiers when `auto_close=True`.

A small stub page lets us exercise modifier chords, newline
normalization, and `auto_close` without launching Chrome:

``` python
class _StubPage:
    def __init__(self): self.calls = []
    async def press(self, key, **kw): self.calls.append((key, kw))

def _act(key, *, release_self=True, release_prev=False, repeat=1):
    return dict(keyDef=dict(key=key), releaseSelf=release_self, releasePrevious=release_prev, repeat=repeat)

vt = Vitest()
vt.page = _StubPage()
res = await vt._keyboard([_act('Control', release_self=False), _act('a'), _act('\n')])
test_eq(res, dict(unreleased=['Control']))
test_eq(vt.page.calls, [
    ('Control', dict(down=True, alt=False, ctrl=True, meta=False, shift=False)),
    ('a', dict(alt=False, ctrl=True, meta=False, shift=False)),
    ('Enter', dict(alt=False, ctrl=True, meta=False, shift=False)),
])
```

Passing `auto_close=True` releases any modifiers still held from earlier
actions, and attempting to hold a non-modifier key raises `ValueError`:

``` python
vt.page.calls.clear()
test_eq(await vt._keyboard([], unreleased=res['unreleased'], auto_close=True), dict(unreleased=[]))
test_eq(vt.page.calls, [('Control', dict(down=False, alt=False, ctrl=False, meta=False, shift=False))])

with expect_fail(ValueError, contains='Holding non-modifier keys'): await vt._keyboard([_act('a', release_self=False)])
```

`_action` handles each provider command: `open` creates one hidden
background tab (with caching disabled) and navigates it to the Vitest
URL, while `viewport`, `keyboard`, `cleanup`, `tab`, `click`, `hover`,
`fill`, `clear`, `type`, and `screenshot` drive that page over CDP.
Unknown actions raise `ValueError`:

``` python
vt.page.calls.clear()
await vt._action(dict2obj(dict(action='tab', shift=True)))
test_eq(vt.page.calls, [('Tab', dict(shift=True))])

with expect_fail(ValueError, contains='Unsupported fastcdp action'): await vt._action(dict2obj(dict(action='unknown')))
```

## Direct CLI bridge

[`_serve_bridge`](https://AnswerDotAI.github.io/fastcdp/vitest.html#_serve_bridge)
binds a free local
[`ExtChannel`](https://AnswerDotAI.github.io/fastcdp/ext.html#extchannel),
prints its WebSocket URL to stdout, and stops cleanly on `SIGINT`,
`SIGTERM`, or stdin EOF so the bridge never outlives a terminated parent
Vitest process.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/fastcdp/blob/main/fastcdp/vitest.py#L217"
target="_blank" style="float:right; font-size:smaller">source</a>

### bridge_main

``` python
def bridge_main(
    port:int=None, # Chrome CDP debug port (default: FASTCDP_PORT env or 9223)
):
```

*Run the fastcdp WebSocket bridge for direct `vp test` runs and print
its URL to stdout.*

When you run `vp test` or `vp test watch` directly without Python
driving the run, the `fastcdp-vitest` provider spawns
`fastcdp-vitest-bridge`
([`bridge_main`](https://AnswerDotAI.github.io/fastcdp/vitest.html#bridge_main)).
It connects to CDP Chrome on `--port` (defaulting to `FASTCDP_PORT` or
`9223`), opens an
[`ExtChannel`](https://AnswerDotAI.github.io/fastcdp/ext.html#extchannel),
prints its WebSocket URL to stdout, and exits on `SIGINT`, `SIGTERM`, or
stdin EOF so it never outlives the parent Vitest process.
