Testing a page without a browser
A test that clicks and types on a page without a browser, reads the signals and the elements afterwards, and checks the calls and the navigation the events asked for. The page also lists what only a browser test reaches.
Clicking and typing without a browser
pub fn simulate(&self) -> Simulation<'_, S>Page::simulate returns a Simulation that starts from the page's initial values. Its events run the statements the page attached to them, such as count.set(count + 1), on the server's evaluator, and recompute each Page::computed signal where the runtime does: between the steps of a then chain and after the event. It panics where Page::render does, so a page with two elements that share an id fails here too.
The test below clicks a counter's button twice, types a note, and clicks Save. The page's handler and its routes are as in Testing handlers, and a test of a page handler calls the handler first to get the Page.
use hypersig::html::{button, div, input, p};
use hypersig::{Action, NodeRef, Page, Patches, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Counter {
count: i32,
note: String,
saving: bool,
}
hypersig::routes! {
fn actions(Router<()>);
action SAVE: Action<Counter, (i32, String)> = post "/save" => save;
}
hypersig::node_ref!(const ADD: NodeRef<Counter>);
hypersig::node_ref!(const NOTE: NodeRef<Counter>);
hypersig::node_ref!(const SHOWN: NodeRef<Counter>);
hypersig::node_ref!(const STORE: NodeRef<Counter>);
let (count, note) = (Counter::count(), Counter::note());
let page = Page::new("Counter", Counter { count: 0, note: String::new(), saving: false })
.child(
div()
.child(p().node_ref(SHOWN).bind_text(count.to_text()))
.child(button().node_ref(ADD).on_click(count.set(count + 1)).text("Add"))
.child(input().node_ref(NOTE).bind(note))
.child(
button()
.node_ref(STORE)
.on_click(SAVE.call_with((count, note)).indicator(Counter::saving()))
.text("Save"),
),
);
let mut browser = page.simulate();
browser.click(ADD);
browser.click(ADD);
browser.input(NOTE, "twice");
assert_eq!(browser.value_of(count), 2);
assert_eq!(browser.element(SHOWN).text(), "2");
// The call is recorded with the arguments it sends, and never answered.
let effects = browser.click(STORE);
assert_eq!(effects.calls(&SAVE), [(2, "twice".to_owned())]);
assert!(browser.value_of(Counter::saving()));The events
pub fn click(&mut self, target: impl Target<S>) -> Effects<S>
pub fn input(&mut self, target: impl Target<S>, text: &str) -> Effects<S>
pub fn change(&mut self, target: impl Target<S>, text: &str) -> Effects<S>
pub fn submit(&mut self, target: impl Target<S>) -> Effects<S>
pub fn pause(&mut self) -> Effects<S>| Method | What it runs |
|---|---|
click | The on_click of the element or the closest element around it, as a click bubbles. A bound checkbox or radio is then checked, and the on_input and on_change around it run. A <button> inside a <form>, unless its type is button or reset, then submits the form. A button that names its form with form_owner is not followed to it. |
input | One input event: the control's bind reads text as the runtime does, then the closest on_input runs. on_change does not, because the browser fires change when the visitor leaves the field. |
change | input as above, then change, on which a bind_select reads text as the JSON of an option's value, and the closest on_change runs. It stands for picking an option or leaving a field. |
submit | The closest on_submit from a <form> up |
pause | Each statement given to on_debounced, once, as the browser runs it when the visitor stops typing |
input reads text as a number control does in the browser: text that holds no number leaves the signal alone, and an i32 or i64 is truncated. A date control leaves its signal alone for text that holds no YYYY-MM-DD date, and an emptied Option control sets None. Each event panics where it runs nothing: a click with no on_click on the element or around it, typing into a control that has neither a bind nor an on_input around it, typing into a checkbox or a radio, which click checks, and submit on an element that is not a <form>.
Naming an element
A test names the element by the NodeRef, DialogRef, FileInput, or Id the page put on it, each of which implements the sealed trait Target<S>. A renamed handle fails to compile in the test too. A list's template carries the same NodeRef on every item, and testing::nth picks the indexth of them, from 0, in document order.
pub fn nth<T>(target: T, index: usize) -> Nth<T>A NodeRef<S> is a Target<S> only for the page whose signals are S, so a test cannot click a handle of another page:
use hypersig::html::button;
use hypersig::{NodeRef, Page, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Counter {
count: i32,
}
#[derive(Signals, Serialize, Deserialize)]
struct Settings {
dark: bool,
}
hypersig::node_ref!(const ADD: NodeRef<Counter>);
hypersig::node_ref!(const THEME: NodeRef<Settings>);
let page = Page::new("Counter", Counter { count: 0 })
.child(button().node_ref(ADD).on_click(Counter::count().set(1)).text("Add"));
let mut browser = page.simulate();
// error[E0277]: the trait bound `NodeRef<Settings>: hypersig::testing::Target<Counter>`
// is not satisfied
browser.click(THEME);Reading the page after the events
pub fn value_of<T: DeserializeOwned, M: FromPage>(&self, signal: Sig<S, T, M>) -> T
pub fn element(&self, target: impl Target<S>) -> Element
pub fn count(&self, target: impl Target<S>) -> usize| Method | What it returns |
|---|---|
Simulation::value_of | The value a signal holds now, read as Page::value_of reads it |
Simulation::element | The element as the page shows it now. It panics where no element or several carry the handle. |
Element::text | The text of the element and everything inside it, as textContent reads it |
Element::attr | The value of an attribute named by an Attr. A bound attribute holds the value its expression gives now, and one set with attr_when or disabled holds "" while it is on. A bound control's own value is the attribute attr::VALUE, apart from a <textarea>, whose text it is. |
Element::is_visible | false where a show on the element or around it is false |
Simulation::count | How many elements the page shows now that carry the handle: once per list item, and 0 for an element inside a when that is false |
The test below checks a list: count sees one DONE per item and no HINT while editing is false, and nth clicks the second item.
use hypersig::html::{button, each_keyed, li, span, ul, when};
use hypersig::testing::nth;
use hypersig::{NodeRef, Page, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Todo {
id: i32,
title: String,
done: bool,
}
#[derive(Signals, Serialize, Deserialize)]
struct List {
todos: Vec<Todo>,
editing: bool,
}
hypersig::node_ref!(const DONE: NodeRef<List>);
hypersig::node_ref!(const MARK: NodeRef<List>);
hypersig::node_ref!(const HINT: NodeRef<List>);
let todos = vec![
Todo { id: 1, title: "Tea".to_owned(), done: false },
Todo { id: 2, title: "Milk".to_owned(), done: false },
];
let page = Page::new("Todos", List { todos, editing: false })
.child(ul().child(each_keyed(List::todos(), |todo| todo.at(Todo::id()), |todo| {
li().child(
button()
.node_ref(DONE)
.on_click(todo.at(Todo::done()).set(true))
.bind_text(todo.at(Todo::title())),
)
.child(span().node_ref(MARK).show(todo.at(Todo::done())).text("done"))
})))
.child(when(List::editing(), span().node_ref(HINT).text("Press Enter to save")));
let mut browser = page.simulate();
// The template puts `DONE` on every item, and a `when` that is false shows nothing.
assert_eq!(browser.count(DONE), 2);
assert_eq!(browser.count(HINT), 0);
browser.click(nth(DONE, 1));
assert_eq!(browser.element(nth(DONE, 1)).text(), "Milk");
assert!(!browser.element(nth(MARK, 0)).is_visible());
assert!(browser.element(nth(MARK, 1)).is_visible());Calls, links, and browser statements
A statement that needs the server or the browser is recorded in the Effects the event returns, and not run.
Method of Effects<S> | What it returns |
|---|---|
calls(&SAVE) | The arguments of each call to SAVE, in order, typed as the action's arguments. An Action, a StreamAction, and an Upload each work. |
navigates_to, pushes_url, replaces_url | The URL of the first Link::navigate, Link::push_url, or Link::replace_url the event ran |
runs_in_browser(FIELD.focus()) | Whether the event asked the browser to focus FIELD. It covers the statements of a NodeRef and a DialogRef and FileInput::clear, and any other statement gives false, because the simulation runs it itself. |
The simulation makes the writes the runtime makes when it sends a call, so the indicator turns true, the error signal "", and the status 0, and it never answers the call. The indicator therefore stays true, on_success and on_error do not run, and a second exclusive call to the same action is skipped. A test that needs the answer calls the handler, as Testing handlers shows. A statement that reads Expr::now, Expr::random_below, or a date in the visitor's zone makes the simulation panic, because only the browser has that value, and so does one that computes a number JSON cannot hold.
What runs only in the browser
A simulation runs only the statement of the event it fires. The statements of effect, on_signal_change, on_load, on_visible, a timer, and a key shortcut do not run, even where the browser would run one after a click changed a signal it reads. It fires only click, input, change, and submit, so a statement on a double click, focus, blur, the pointer, a key, or a custom event never runs. The runtime applying a server's answer, focus, and the page's layout are outside a Rust test too. Drive those in a browser. The repository's e2e directory starts each example and clicks through it in Chrome with Playwright, and a test of your application can follow its layout.
Next
- Reading a compile error: what the first line of a hypersig error names.
- Debugging a running page: the panics and console lines a test did not catch.