livewire-rust 0.1.4

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! A harness that drives a component through the same mount and update pipeline the endpoint uses,
//! without HTTP.
//!
//! Upstream's `Livewire::test()` mounts a component, changes its state, calls its actions, and
//! asserts on the result. [`Testable`] is that harness in Rust: it calls [`render::mount`] and
//! [`render::update`] directly, so a test proves the wire pipeline rather than only the method.
//!
//! ```no_run
//! # use serde_json::{json, Map};
//! # use std::sync::Arc;
//! # use livewire::ComponentRegistry;
//! # use livewire::component::Params;
//! # use livewire::testing::Testable;
//! # fn run(registry: Arc<ComponentRegistry>) -> livewire::Result<()> {
//! let mut test = Testable::mount(registry, "counter", Params::Named(Map::new()))?;
//! test.assert_set("count", json!(0));
//! # Ok(())
//! # }
//! ```
//!
//! # What a test needs
//!
//! Mounting renders a view and signs a snapshot, so it reads the framework's request context:
//! call it inside a request or a framework test. Session- and auth-backed fields need a real HTTP
//! request, which this harness does not create; they hydrate to their defaults.

use std::sync::Arc;

use serde_json::{Map, Value};

use crate::component::Result;
use crate::component::{Call, Params};
use crate::error::LivewireError;
use crate::registry::ComponentRegistry;
use crate::render::{self, Rendered, Updated};

/// A component mounted for a test, with its latest markup, snapshot, and effects.
#[derive(Debug)]
pub struct Testable {
    registry: Arc<ComponentRegistry>,
    rendered: Rendered,
    updated: Option<Updated>,
}

impl Testable {
    /// Mounts `name` with `params`, as `livewire(name, params)` does in a page.
    ///
    /// # Errors
    ///
    /// Fails when the component is not registered in `registry`, when the caller's component fails
    /// to mount, or when its view renders no single root element.
    pub fn mount(registry: Arc<ComponentRegistry>, name: &str, params: Params) -> Result<Self> {
        let rendered = render::mount(&registry, name, params, None, Map::new())?;

        Ok(Self {
            registry,
            rendered,
            updated: None,
        })
    }

    /// Sets one wire-public field, by its name or by a dotted path, and renders again.
    ///
    /// # Errors
    ///
    /// Fails when the field is unknown or locked, or when the value does not fit its type.
    pub async fn set(&mut self, path: &str, value: Value) -> Result<&mut Self> {
        self.apply(Map::from_iter([(path.to_owned(), value)]), Vec::new()).await
    }

    /// Calls one action, and applies its effects.
    ///
    /// # Errors
    ///
    /// Fails when the action is unknown, when a parameter does not fit its type, or when the
    /// action itself reports an error.
    pub async fn call(&mut self, method: &str, params: Params) -> Result<&mut Self> {
        let call = Call {
            method: method.to_owned(),
            params,
            metadata: Map::new(),
        };

        self.apply(Map::new(), vec![call]).await
    }

    /// Calls `$refresh`, which re-renders the component without running a method.
    ///
    /// # Errors
    ///
    /// Fails as [`Testable::call`] does.
    pub async fn refresh(&mut self) -> Result<&mut Self> {
        self.call("$refresh", Params::default()).await
    }

    async fn apply(&mut self, updates: Map<String, Value>, calls: Vec<Call>) -> Result<&mut Self> {
        let updated = render::update(&self.registry, &self.snapshot().clone(), updates, calls, None).await?;

        if let Some(snapshot) = &updated.snapshot {
            self.rendered.snapshot = snapshot.clone();
        }
        self.rendered.effects = updated.effects.clone();
        self.rendered.html = updated
            .effects
            .get("html")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned();
        self.updated = Some(updated);

        Ok(self)
    }

    /// The component's current markup.
    #[must_use]
    pub fn html(&self) -> &str {
        &self.rendered.html
    }

    /// The component's current signed snapshot.
    #[must_use]
    pub fn snapshot(&self) -> &crate::snapshot::Snapshot {
        &self.rendered.snapshot
    }

    /// The effects of the latest update, or of the mount when no update ran.
    #[must_use]
    pub fn effects(&self) -> &Map<String, Value> {
        &self.rendered.effects
    }

    /// The values the latest update's calls returned, one slot per call.
    #[must_use]
    pub fn returns(&self) -> Value {
        self.rendered
            .effects
            .get("returns")
            .cloned()
            .unwrap_or(Value::Array(Vec::new()))
    }

    /// Whether the component asked the browser to leave it alone.
    #[must_use]
    pub fn skipped(&self) -> bool {
        self.updated.as_ref().is_some_and(|updated| updated.skip)
    }

    /// Asserts that the markup shows `text`, ignoring the markers a rendered block leaves.
    ///
    /// # Panics
    ///
    /// Panics with the markup when `text` does not appear.
    #[track_caller]
    pub fn assert_see(&self, text: &str) {
        let visible = without_markers(&self.rendered.html);

        assert!(visible.contains(text), "the markup does not show {text:?}:\n{visible}");
    }

    /// Asserts that the markup does not show `text`, ignoring the markers a rendered block leaves.
    ///
    /// # Panics
    ///
    /// Panics with the markup when `text` does appear.
    #[track_caller]
    pub fn assert_dont_see(&self, text: &str) {
        let visible = without_markers(&self.rendered.html);

        assert!(!visible.contains(text), "the markup still shows {text:?}:\n{visible}");
    }

    /// Asserts a wire-public field's value, by its name or by a dotted path.
    ///
    /// # Panics
    ///
    /// Panics when the field holds another value or is absent from the snapshot.
    #[track_caller]
    pub fn assert_set(&self, path: &str, expected: Value) {
        let mut segments = path.split('.');
        let mut actual = segments.next().and_then(|first| self.rendered.snapshot.data.get(first));
        for segment in segments {
            actual = actual.and_then(|value| value.get(segment));
        }
        let actual = actual.cloned();

        assert_eq!(
            actual,
            Some(expected),
            "the snapshot's {path:?} does not hold that value"
        );
    }

    /// Asserts that the latest update dispatched `event` to the browser.
    ///
    /// # Panics
    ///
    /// Panics when no dispatch effect names `event`.
    #[track_caller]
    pub fn assert_dispatched(&self, event: &str) {
        let dispatched = self
            .rendered
            .effects
            .get("dispatch")
            .and_then(Value::as_array)
            .is_some_and(|events| {
                events
                    .iter()
                    .any(|sent| sent.get("name").and_then(Value::as_str) == Some(event))
            });

        assert!(
            dispatched,
            "the update did not dispatch {event:?}: {:?}",
            self.rendered.effects
        );
    }

    /// Asserts that the latest update asked the browser to leave, either to `url` or anywhere.
    ///
    /// # Panics
    ///
    /// Panics when no redirect effect names that URL.
    #[track_caller]
    pub fn assert_redirected_to(&self, url: &str) {
        let redirect = self.rendered.effects.get("redirect").and_then(Value::as_str);

        assert_eq!(redirect, Some(url), "the update did not redirect to {url:?}");
    }

    /// Asserts that the update failed, without panicking on the error, for a test of a guard.
    ///
    /// # Panics
    ///
    /// Panics when the update succeeded.
    pub async fn assert_update_fails(&mut self, updates: Map<String, Value>) -> LivewireError {
        match self.apply(updates, Vec::new()).await {
            Ok(_) => panic!("the update succeeded, but the test expects it to fail"),
            Err(error) => error,
        }
    }
}

/// The markup with the comment markers a rendered block wraps around its own source removed, so a
/// test can assert on the text a reader sees.
fn without_markers(html: &str) -> String {
    let mut visible = String::with_capacity(html.len());
    let mut rest = html;

    while let Some(start) = rest.find("<!--[if ") {
        visible.push_str(&rest[..start]);
        let after = &rest[start..];

        let Some(end) = after.find("]>") else {
            visible.push_str(after);
            rest = "";
            break;
        };

        // Both the opener and its closing `<![endif]-->` are chrome, not text.
        rest = &after[end + 2..];
    }

    visible.push_str(rest);

    visible.replace("<![endif]-->", "")
}

#[cfg(test)]
mod tests {
    use super::without_markers;

    #[test]
    fn the_markers_around_a_block_are_removed() {
        assert_eq!(
            without_markers("Ada<!--[if BLOCK]><![endif]--> — subscribed<!--[if ENDBLOCK]><![endif]-->"),
            "Ada — subscribed"
        );
        assert_eq!(without_markers("plain"), "plain");
        assert_eq!(without_markers(""), "");
        // A comment that is not a marker stays, since the page may show it on purpose.
        assert_eq!(without_markers("a<!-- note -->b"), "a<!-- note -->b");
    }
}