Skip to content

Testing

wybthon.testing

testing

Render components in plain CPython and query them like a user would.

wybthon.testing mounts views into an in-memory DOM through the real reconciler, kernel protocol, scheduler, and event delegation. Nothing is mocked: the commands a test applies are exactly the commands the browser kernel applies.

from wybthon.testing import cleanup, fire, render


def test_counter():
    screen = render(Counter(label="Clicks"))
    fire.click(screen.get_by_role("button", name="+"))
    assert screen.get_by_text("Clicks: 1")
    cleanup()

Queries come in three forms, as in Testing Library:

  • get_by_* returns the single match and raises when there are none or several;
  • query_by_* returns the match or None;
  • get_all_by_* returns every match (raising when there are none).

They search by visible text, ARIA role (with an optional accessible name), label text, and data-testid. fire dispatches events through Wybthon's delegated handlers and flushes the resulting updates, so assertions see the settled DOM.

Use render as a context manager to unmount automatically, or call cleanup at the end of each test (an autouse pytest fixture is a convenient place).

Full-stack code tests the same way:

  • connect_server makes the components a test renders call their server functions the way the browser does, through the wire protocol and the server's argument validation, in-process.
  • Client sends HTTP requests to an ASGI app (wybthon.asgi.create_app) without a network, for pages, form posts, and HTTP handlers.

Classes:

Name Description
TestNode

An in-memory DOM node: an element, a text node, or a comment.

TestDocument

An in-memory document for the kernel's Python backend.

Screen

A rendered view and the queries that find nodes in it.

ClientResponse

A response a Client received.

Client

Send requests to an ASGI app in-process; cookies persist between requests.

Functions:

Name Description
raise_unhandled

Raise the errors rendered views logged that no Errored boundary handled.

render

Mount view into a fresh in-memory container and flush it.

cleanup

Unmount every view rendered with render that's still mounted.

reactive_scope

Own test computations and dispose them deterministically at scope exit.

tick

Drain ready asyncio continuations and flush reactive work.

wait_for

Wait for an observable condition, raising TimeoutError on failure.

connect_server

Make server function calls inside the block cross the wire, as they would in the browser.

Attributes:

Name Type Description
fire

Dispatch events: fire.click(node), fire.input(node, "text"), fire(node, "dblclick").

fire module-attribute

fire = _Fire()

Dispatch events: fire.click(node), fire.input(node, "text"), fire(node, "dblclick").

TestNode

TestNode(tag: str | None = None, text: str | None = None)

An in-memory DOM node: an element, a text node, or a comment.

It implements the subset of the DOM the kernel protocol uses, plus the properties tests read (text_content, attributes, value, checked).

Methods:

Name Description
focus

Make this node the document's active element (no events are dispatched).

blur

Clear the active element if it's this node.

click

Dispatch a click through Wybthon's delegated handlers (like fire.click).

Attributes:

Name Type Description
is_element bool

Whether this node is an element (not text or a comment).

text_content str

The concatenated text of this node and its descendants (comments excluded).

is_element property

is_element: bool

Whether this node is an element (not text or a comment).

text_content property

text_content: str

The concatenated text of this node and its descendants (comments excluded).

focus

focus() -> None

Make this node the document's active element (no events are dispatched).

blur

blur() -> None

Clear the active element if it's this node.

click

click() -> None

Dispatch a click through Wybthon's delegated handlers (like fire.click).

TestDocument

TestDocument()

An in-memory document for the kernel's Python backend.

Screen

Screen(root: Any, container: TestNode, strict: bool = True)

A rendered view and the queries that find nodes in it.

Attributes:

Name Type Description
container

The TestNode the view is mounted into.

root

The Root returned by render.

Methods:

Name Description
unmount

Dispose the view and release its container.

html

The container's inner HTML, without Wybthon's comment markers.

text

The container's text content, with whitespace collapsed.

debug

Print the rendered markup, for a look at what a failing query searched.

get_by_text

Return the one element whose text matches.

query_by_text

Return the element whose text matches, or None.

get_all_by_text

Return every element whose text matches.

get_by_role

Return the one element with this ARIA role (and accessible name).

query_by_role

Return the element with this role (and name), or None.

get_all_by_role

Return every element with this role (and name).

get_by_label_text

Return the one form control labelled by text.

query_by_label_text

Return the form control labelled by text, or None.

get_by_test_id

Return the one element with data-testid equal to test_id.

query_by_test_id

Return the element with this data-testid, or None.

get_all_by_test_id

Return every element with this data-testid.

unmount

unmount(*, check: bool = True) -> None

Dispose the view and release its container.

Raises an error a rendered view logged that no Errored boundary handled, unless check is false.

html

html() -> str

The container's inner HTML, without Wybthon's comment markers.

text

text() -> str

The container's text content, with whitespace collapsed.

debug

debug() -> None

Print the rendered markup, for a look at what a failing query searched.

get_by_text

get_by_text(text: str | Pattern[str], *, exact: bool = True) -> TestNode

Return the one element whose text matches.

query_by_text

query_by_text(text: str | Pattern[str], *, exact: bool = True) -> TestNode | None

Return the element whose text matches, or None.

get_all_by_text

get_all_by_text(text: str | Pattern[str], *, exact: bool = True) -> list[TestNode]

Return every element whose text matches.

get_by_role

get_by_role(role: str, *, name: str | Pattern[str] | None = None) -> TestNode

Return the one element with this ARIA role (and accessible name).

query_by_role

query_by_role(role: str, *, name: str | Pattern[str] | None = None) -> TestNode | None

Return the element with this role (and name), or None.

get_all_by_role

get_all_by_role(role: str, *, name: str | Pattern[str] | None = None) -> list[TestNode]

Return every element with this role (and name).

get_by_label_text

get_by_label_text(text: str | Pattern[str]) -> TestNode

Return the one form control labelled by text.

query_by_label_text

query_by_label_text(text: str | Pattern[str]) -> TestNode | None

Return the form control labelled by text, or None.

get_by_test_id

get_by_test_id(test_id: str) -> TestNode

Return the one element with data-testid equal to test_id.

query_by_test_id

query_by_test_id(test_id: str) -> TestNode | None

Return the element with this data-testid, or None.

get_all_by_test_id

get_all_by_test_id(test_id: str) -> list[TestNode]

Return every element with this data-testid.

ClientResponse

ClientResponse(status: int, headers: dict[str, str], cookies: list[str], body: bytes)

A response a Client received.

Attributes:

Name Type Description
status

The status code.

headers

Header values by lowercase name (repeated headers joined with ,, except set-cookie, which is in cookies).

cookies

Every set-cookie value.

body

The body.

Methods:

Name Description
json

The body parsed as JSON.

text property

text: str

The body as text.

json

json() -> Any

The body parsed as JSON.

Client

Client(app: Any, *, host: str = 'testserver')

Send requests to an ASGI app in-process; cookies persist between requests.

from wybthon.asgi import create_app
from wybthon.testing import Client

def test_home_page():
    client = Client(create_app("tests/fixture_app"))
    page = client.get("/")
    assert page.status == 200 and "Todos" in page.text

Methods:

Name Description
request_async

Send a request from a running event loop.

request

Send a request and wait for the whole response.

get

GET path, as a browser loading a page would (it accepts HTML).

post_form

Post a form the way a browser without JavaScript does.

request_async async

request_async(method: str, path: str, *, body: bytes = b'', headers: dict[str, str] | None = None) -> ClientResponse

Send a request from a running event loop.

request

request(method: str, path: str, *, body: bytes = b'', headers: dict[str, str] | None = None) -> ClientResponse

Send a request and wait for the whole response.

get

get(path: str, *, headers: dict[str, str] | None = None) -> ClientResponse

GET path, as a browser loading a page would (it accepts HTML).

post_form

post_form(path: str, fields: dict[str, str] | list[tuple[str, str]], *, referer: str = '/') -> ClientResponse

Post a form the way a browser without JavaScript does.

raise_unhandled

raise_unhandled() -> None

Raise the errors rendered views logged that no Errored boundary handled.

render, every fire call, and leaving a render block call this, so a test fails on an error a component, binding, or effect raised instead of passing against whatever the view managed to show. Several errors are raised together as an ExceptionGroup.

render

render(view: Any, *, strict: bool = True) -> Screen

Mount view into a fresh in-memory container and flush it.

An error a component, binding, or effect raises that no Errored boundary handles fails the test: it's raised from render, from the fire call that caused it, or when the with block ends.

Parameters:

Name Type Description Default
view Any

Anything wybthon.render accepts: a component call, an element, a list, or a reactive expression.

required
strict bool

Pass False to only log such errors, for a test about how a view behaves after one.

True

Returns:

Type Description
Screen

A Screen for querying the result.

cleanup

cleanup(*, check: bool = False) -> None

Unmount every view rendered with render that's still mounted.

With check, then raise the errors the views logged that no boundary handled, as the pytest plugin does after every test; otherwise they're dropped.

reactive_scope

reactive_scope() -> Iterator[Owner]

Own test computations and dispose them deterministically at scope exit.

tick async

tick(rounds: int = 2) -> None

Drain ready asyncio continuations and flush reactive work.

wait_for async

wait_for(predicate: Callable[[], bool], *, timeout: float = 1, interval: float = 0.001) -> None

Wait for an observable condition, raising TimeoutError on failure.

connect_server

connect_server(app: Any = None, *, base: str = '/') -> Iterator[None]

Make server function calls inside the block cross the wire, as they would in the browser.

With no app, each call is handled in-process by the server-side handler: arguments are encoded, validated against the function's annotations, and the result decoded, exactly as over HTTP. With an ASGI app (such as wybthon.asgi.create_app(...)), each call is a request to it.

def test_add_todo():
    with connect_server(), render(TodoPage()) as screen:
        fire.input(screen.get_by_role("textbox"), "Write tests")
        fire.submit(screen.get_by_role("form"))
        ...

What's in this module

wybthon.testing renders components in plain CPython, through the real reconciler, kernel protocol, scheduler, and event delegation, into an in-memory DOM. Nothing is mocked, so a passing test exercises the same commands the browser kernel applies. The queries follow Testing Library's conventions.

Name Description
render render(view) -> Screen: mount a view (a VNode or a zero-arg callable) into a fresh in-memory document.
Screen Queries plus html(), text(), and unmount(); also a context manager that unmounts on exit.
fire Dispatch events through delegated handlers and flush: fire.click(node), fire.input(node, value), fire.change(node, value=None, checked=None), fire.submit(form), fire.key_down(node, key), fire.focus(node), fire.blur(node), or fire(node, "dblclick", **payload).
cleanup Unmount everything render mounted; call it after each test, or from an autouse fixture.
TestNode, TestDocument The in-memory DOM the screen renders into.
reactive_scope, tick, wait_for Helpers for testing reactive code and async updates outside a component.
Query Finds Variants
get_by_text(text, *, exact=True) Elements by visible text, or a compiled regex query_by_text, get_all_by_text
get_by_role(role, *, name=None) Elements by ARIA role and accessible name query_by_role, get_all_by_role
get_by_label_text(text) Form controls by their label query_by_label_text
get_by_test_id(test_id) Elements by data-testid query_by_test_id, get_all_by_test_id

get_by_* raises unless exactly one element matches, query_by_* returns the match or None, and get_all_by_* returns every match.

import pytest

from wybthon import component, create_signal, html
from wybthon.testing import cleanup, fire, render


@component
def Counter(label: str = "Count"):
    count, set_count = create_signal(0)

    def increment():
        set_count(lambda n: n + 1)

    return html(t"<div><p>{label}: {count()}</p><button onclick={increment}>+</button></div>")


@pytest.fixture(autouse=True)
def _cleanup():
    yield
    cleanup()


def test_counter():
    screen = render(Counter(label="Clicks"))
    fire.click(screen.get_by_role("button", name="+"))
    assert screen.get_by_text("Clicks: 1")
    assert screen.html() == "<div><p>Clicks: 1</p><button>+</button></div>"

Templates in test modules are compiled by Wybthon's pytest plugin, so they behave exactly as they do in the application; see Guides: Testing. For a script outside pytest, use wyb run script.py.

See also