Lines
0 %
Functions
Branches
100 %
// -- -*- mode: rust -*-
//! Real htmx events against a faked XHR: a failed request from a form whose
//! `hx-target` is an outer panel with `hx-swap="outerHTML"` must put the error
//! inside the form's result box and leave the panel intact, repeatedly.
use nomisync_frontend::htmx::setup_htmx_validation;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use wasm_bindgen_test::*;
use web_sys::Element;
wasm_bindgen_test_configure!(run_in_browser);
const HTMX: &str = include_str!("../../static/scripts/htmx.min.js");
const FAKE_XHR: &str = r#"
(() => {
const Real = window.XMLHttpRequest;
window.XMLHttpRequest = class extends Real {
open() {}
setRequestHeader() {}
send() {
const body = '<div class="error-alert">bad input</div>';
const props = {
status: 422,
response: body,
responseText: body,
responseURL: location.href,
};
for (const [key, value] of Object.entries(props)) {
Object.defineProperty(this, key, { value });
}
this.getAllResponseHeaders = () => "content-type: text/html\r\n";
this.getResponseHeader = (name) =>
name.toLowerCase() === "content-type" ? "text/html" : null;
setTimeout(() => this.onload(), 0);
})()
"#;
fn global_eval(source: &str) -> Result<JsValue, JsValue> {
js_sys::Function::new_with_args("src", "return (0, eval)(src)")
.call1(&JsValue::NULL, &source.into())
fn swapped() -> Result<JsFuture, JsValue> {
let promise = js_sys::eval(
"new Promise(r => document.addEventListener('htmx:afterSwap', r, { once: true }))",
)?;
Ok(JsFuture::from(promise.dyn_into::<js_sys::Promise>()?))
async fn fail_once(form: &Element) -> Result<(), JsValue> {
let done = swapped()?;
let init = web_sys::EventInit::new();
init.set_bubbles(true);
init.set_cancelable(true);
form.dispatch_event(&web_sys::Event::new_with_event_init_dict("submit", &init)?)?;
done.await?;
Ok(())
#[wasm_bindgen_test]
async fn failed_form_request_lands_in_its_result_box() -> Result<(), JsValue> {
global_eval(HTMX)?;
global_eval(FAKE_XHR)?;
setup_htmx_validation();
let document = web_sys::window()
.and_then(|w| w.document())
.ok_or("no document")?;
let host = document.create_element("div")?;
host.set_inner_html(
r##"<div id="panel"><form hx-post="/fail" hx-target="#panel" hx-swap="outerHTML">
<div class="result-box"></div></form></div>"##,
);
document.body().ok_or("no body")?.append_child(&host)?;
global_eval("htmx.process")?
.dyn_into::<js_sys::Function>()?
.call1(&JsValue::NULL, &host)?;
let form = host.query_selector("form")?.ok_or("form missing")?;
for _ in 0..2 {
fail_once(&form).await?;
let panel = host.query_selector("#panel")?.ok_or("panel replaced")?;
let result_box = panel
.query_selector("form .result-box")?
.ok_or("result box replaced")?;
assert!(result_box.inner_html().contains("bad input"));
assert!(result_box.class_list().contains("error-message"));
host.remove();