Skip to main content

livewire/
testing.rs

1//! A harness that drives a component through the same mount and update pipeline the endpoint uses,
2//! without HTTP.
3//!
4//! Upstream's `Livewire::test()` mounts a component, changes its state, calls its actions, and
5//! asserts on the result. [`Testable`] is that harness in Rust: it calls [`render::mount`] and
6//! [`render::update`] directly, so a test proves the wire pipeline rather than only the method.
7//!
8//! ```no_run
9//! # use serde_json::{json, Map};
10//! # use std::sync::Arc;
11//! # use livewire::ComponentRegistry;
12//! # use livewire::component::Params;
13//! # use livewire::testing::Testable;
14//! # fn run(registry: Arc<ComponentRegistry>) -> livewire::Result<()> {
15//! let mut test = Testable::mount(registry, "counter", Params::Named(Map::new()))?;
16//! test.assert_set("count", json!(0));
17//! # Ok(())
18//! # }
19//! ```
20//!
21//! # What a test needs
22//!
23//! Mounting renders a view and signs a snapshot, so it reads the framework's request context:
24//! call it inside a request or a framework test. Session- and auth-backed fields need a real HTTP
25//! request, which this harness does not create; they hydrate to their defaults.
26
27use std::sync::Arc;
28
29use serde_json::{Map, Value};
30
31use crate::component::Result;
32use crate::component::{Call, Params};
33use crate::error::LivewireError;
34use crate::registry::ComponentRegistry;
35use crate::render::{self, Rendered, Updated};
36
37/// A component mounted for a test, with its latest markup, snapshot, and effects.
38#[derive(Debug)]
39pub struct Testable {
40    registry: Arc<ComponentRegistry>,
41    rendered: Rendered,
42    updated: Option<Updated>,
43}
44
45impl Testable {
46    /// Mounts `name` with `params`, as `livewire(name, params)` does in a page.
47    ///
48    /// # Errors
49    ///
50    /// Fails when the component is not registered in `registry`, when the caller's component fails
51    /// to mount, or when its view renders no single root element.
52    pub fn mount(registry: Arc<ComponentRegistry>, name: &str, params: Params) -> Result<Self> {
53        let rendered = render::mount(&registry, name, params, None, Map::new())?;
54
55        Ok(Self {
56            registry,
57            rendered,
58            updated: None,
59        })
60    }
61
62    /// Sets one wire-public field, by its name or by a dotted path, and renders again.
63    ///
64    /// # Errors
65    ///
66    /// Fails when the field is unknown or locked, or when the value does not fit its type.
67    pub async fn set(&mut self, path: &str, value: Value) -> Result<&mut Self> {
68        self.apply(Map::from_iter([(path.to_owned(), value)]), Vec::new()).await
69    }
70
71    /// Calls one action, and applies its effects.
72    ///
73    /// # Errors
74    ///
75    /// Fails when the action is unknown, when a parameter does not fit its type, or when the
76    /// action itself reports an error.
77    pub async fn call(&mut self, method: &str, params: Params) -> Result<&mut Self> {
78        let call = Call {
79            method: method.to_owned(),
80            params,
81            metadata: Map::new(),
82        };
83
84        self.apply(Map::new(), vec![call]).await
85    }
86
87    /// Calls `$refresh`, which re-renders the component without running a method.
88    ///
89    /// # Errors
90    ///
91    /// Fails as [`Testable::call`] does.
92    pub async fn refresh(&mut self) -> Result<&mut Self> {
93        self.call("$refresh", Params::default()).await
94    }
95
96    async fn apply(&mut self, updates: Map<String, Value>, calls: Vec<Call>) -> Result<&mut Self> {
97        let updated = render::update(&self.registry, &self.snapshot().clone(), updates, calls, None).await?;
98
99        if let Some(snapshot) = &updated.snapshot {
100            self.rendered.snapshot = snapshot.clone();
101        }
102        self.rendered.effects = updated.effects.clone();
103        self.rendered.html = updated
104            .effects
105            .get("html")
106            .and_then(Value::as_str)
107            .unwrap_or_default()
108            .to_owned();
109        self.updated = Some(updated);
110
111        Ok(self)
112    }
113
114    /// The component's current markup.
115    #[must_use]
116    pub fn html(&self) -> &str {
117        &self.rendered.html
118    }
119
120    /// The component's current signed snapshot.
121    #[must_use]
122    pub fn snapshot(&self) -> &crate::snapshot::Snapshot {
123        &self.rendered.snapshot
124    }
125
126    /// The effects of the latest update, or of the mount when no update ran.
127    #[must_use]
128    pub fn effects(&self) -> &Map<String, Value> {
129        &self.rendered.effects
130    }
131
132    /// The values the latest update's calls returned, one slot per call.
133    #[must_use]
134    pub fn returns(&self) -> Value {
135        self.rendered
136            .effects
137            .get("returns")
138            .cloned()
139            .unwrap_or(Value::Array(Vec::new()))
140    }
141
142    /// Whether the component asked the browser to leave it alone.
143    #[must_use]
144    pub fn skipped(&self) -> bool {
145        self.updated.as_ref().is_some_and(|updated| updated.skip)
146    }
147
148    /// Asserts that the markup shows `text`, ignoring the markers a rendered block leaves.
149    ///
150    /// # Panics
151    ///
152    /// Panics with the markup when `text` does not appear.
153    #[track_caller]
154    pub fn assert_see(&self, text: &str) {
155        let visible = without_markers(&self.rendered.html);
156
157        assert!(visible.contains(text), "the markup does not show {text:?}:\n{visible}");
158    }
159
160    /// Asserts that the markup does not show `text`, ignoring the markers a rendered block leaves.
161    ///
162    /// # Panics
163    ///
164    /// Panics with the markup when `text` does appear.
165    #[track_caller]
166    pub fn assert_dont_see(&self, text: &str) {
167        let visible = without_markers(&self.rendered.html);
168
169        assert!(!visible.contains(text), "the markup still shows {text:?}:\n{visible}");
170    }
171
172    /// Asserts a wire-public field's value, by its name or by a dotted path.
173    ///
174    /// # Panics
175    ///
176    /// Panics when the field holds another value or is absent from the snapshot.
177    #[track_caller]
178    pub fn assert_set(&self, path: &str, expected: Value) {
179        let mut segments = path.split('.');
180        let mut actual = segments.next().and_then(|first| self.rendered.snapshot.data.get(first));
181        for segment in segments {
182            actual = actual.and_then(|value| value.get(segment));
183        }
184        let actual = actual.cloned();
185
186        assert_eq!(
187            actual,
188            Some(expected),
189            "the snapshot's {path:?} does not hold that value"
190        );
191    }
192
193    /// Asserts that the latest update dispatched `event` to the browser.
194    ///
195    /// # Panics
196    ///
197    /// Panics when no dispatch effect names `event`.
198    #[track_caller]
199    pub fn assert_dispatched(&self, event: &str) {
200        let dispatched = self
201            .rendered
202            .effects
203            .get("dispatch")
204            .and_then(Value::as_array)
205            .is_some_and(|events| {
206                events
207                    .iter()
208                    .any(|sent| sent.get("name").and_then(Value::as_str) == Some(event))
209            });
210
211        assert!(
212            dispatched,
213            "the update did not dispatch {event:?}: {:?}",
214            self.rendered.effects
215        );
216    }
217
218    /// Asserts that the latest update asked the browser to leave, either to `url` or anywhere.
219    ///
220    /// # Panics
221    ///
222    /// Panics when no redirect effect names that URL.
223    #[track_caller]
224    pub fn assert_redirected_to(&self, url: &str) {
225        let redirect = self.rendered.effects.get("redirect").and_then(Value::as_str);
226
227        assert_eq!(redirect, Some(url), "the update did not redirect to {url:?}");
228    }
229
230    /// Asserts that the update failed, without panicking on the error, for a test of a guard.
231    ///
232    /// # Panics
233    ///
234    /// Panics when the update succeeded.
235    pub async fn assert_update_fails(&mut self, updates: Map<String, Value>) -> LivewireError {
236        match self.apply(updates, Vec::new()).await {
237            Ok(_) => panic!("the update succeeded, but the test expects it to fail"),
238            Err(error) => error,
239        }
240    }
241}
242
243/// The markup with the comment markers a rendered block wraps around its own source removed, so a
244/// test can assert on the text a reader sees.
245fn without_markers(html: &str) -> String {
246    let mut visible = String::with_capacity(html.len());
247    let mut rest = html;
248
249    while let Some(start) = rest.find("<!--[if ") {
250        visible.push_str(&rest[..start]);
251        let after = &rest[start..];
252
253        let Some(end) = after.find("]>") else {
254            visible.push_str(after);
255            rest = "";
256            break;
257        };
258
259        // Both the opener and its closing `<![endif]-->` are chrome, not text.
260        rest = &after[end + 2..];
261    }
262
263    visible.push_str(rest);
264
265    visible.replace("<![endif]-->", "")
266}
267
268#[cfg(test)]
269mod tests {
270    use super::without_markers;
271
272    #[test]
273    fn the_markers_around_a_block_are_removed() {
274        assert_eq!(
275            without_markers("Ada<!--[if BLOCK]><![endif]--> — subscribed<!--[if ENDBLOCK]><![endif]-->"),
276            "Ada — subscribed"
277        );
278        assert_eq!(without_markers("plain"), "plain");
279        assert_eq!(without_markers(""), "");
280        // A comment that is not a marker stays, since the page may show it on purpose.
281        assert_eq!(without_markers("a<!-- note -->b"), "a<!-- note -->b");
282    }
283}