Skip to main content

yew_e2e/test_driver/
navigation.rs

1//! Where the browser is: its window, its clock, and going to a page again or
2//! in a second tab or window.
3
4use anyhow::{Context, Result, bail};
5
6use crate::driver::with_cleanup;
7use crate::{TestDriver, WINDOW};
8
9impl TestDriver {
10    /// **`epoch_ms` on the browser's own clock**: its month (from one), day,
11    /// hour and minute, for a test reading a time the page shows in the
12    /// reader's zone.
13    pub async fn local_clock(&self, epoch_ms: u64) -> Result<[u32; 4]> {
14        let read = self
15            .inner
16            .execute(
17                "const d = new Date(arguments[0]); \
18                 return [d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes()]",
19                vec![serde_json::json!(epoch_ms)],
20            )
21            .await?;
22        let parts = read.json().as_array().context("clock array")?;
23        let mut clock = [0; 4];
24
25        for (slot, part) in clock.iter_mut().zip(parts) {
26            *slot = u32::try_from(part.as_u64().context("clock part")?)?;
27        }
28
29        Ok(clock)
30    }
31
32    /// Resize the browser window.
33    pub async fn set_window_size(&self, width: u32, height: u32) -> Result<()> {
34        tracing::trace!(width, height, "Sizing the window");
35        self.inner.set_window_rect(0, 0, width, height).await?;
36        Ok(())
37    }
38
39    /// What a page that did not become what was asked for has to say for
40    /// itself, as a sentence to hang off a timeout: whether anything is
41    /// mounted, what `data-page` the body carries, what it threw, and how the
42    /// document and its bundle loaded.
43    pub async fn what_the_page_says(&self) -> Result<String> {
44        let script = "const b = document.body; \
45             if (!b) { return 'and the document has no body at all'; } \
46             const page = b.getAttribute('data-page'); \
47             const threw = b.getAttribute('data-threw'); \
48             const mounted = b.children.length; \
49             let out = page ? `; the page showing is '${page}'` \
50                 : '; nothing has claimed the page yet'; \
51             out += `, ${mounted} element(s) are mounted under the body`; \
52             if (threw) { out += `, and the page threw: ${threw}`; } \
53             out += `, the document is ${document.readyState}`; \
54             out += `, the bundle's exports are ${typeof window.wasmBindings}`; \
55             try { new WebAssembly.Module( \
56                 new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])); \
57                 out += ', an empty module still compiles'; } \
58             catch (e) { out += ', and an empty module will not compile: ' + e; } \
59             out += ', history=' + history.length; \
60             const nav = performance.getEntriesByType('navigation')[0]; \
61             if (nav) { out += `, the document was answered after \
62                 ${Math.max(0, Math.round(nav.responseEnd))}ms`; } \
63             for (const got of performance.getEntriesByType('resource')) { \
64                 if (!/\\.(wasm|js)(\\?|$)/.test(got.name)) { continue; } \
65                 out += `, ${got.name.split('/').pop()} was fetched in \
66                     ${Math.round(got.duration)}ms`; } \
67             return out;";
68
69        let told = self.inner.execute(script, Vec::new()).await?;
70        Ok(told.json().as_str().unwrap_or_default().to_owned())
71    }
72
73    /// Reload the page, which is the only way to ask what the *server* holds.
74    /// A test watching for errors goes on watching the reloaded page.
75    pub async fn reload(&self) -> Result<()> {
76        tracing::trace!("Reloading the page");
77        self.inner.refresh().await?;
78        self.rewatch().await
79    }
80
81    /// Open the page again with `query` in the address. A test watching for
82    /// errors goes on watching the reopened page.
83    pub async fn reopen_with(&self, query: &str) -> Result<()> {
84        tracing::trace!(query, "Reopening the page");
85
86        let mut url = self.inner.current_url().await?;
87        url.set_query(Some(query));
88        self.inner.goto(url.as_str()).await?;
89        self.rewatch().await
90    }
91
92    /// Run `run` in a second tab showing the page this one shows, then close
93    /// it and come back. The tab is sized as every test's first one is, and
94    /// `run` is what waits for the page to come up. A test watching for errors
95    /// goes on watching in the second tab, and what the page there threw fails
96    /// it as it would the test; a test that never asked for the watch is left
97    /// unwatched there too.
98    pub async fn in_second_tab(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
99        self.in_second_context(true, run).await
100    }
101
102    /// The same in a second window.
103    pub async fn in_second_window(&self, run: impl AsyncFnOnce() -> Result<()>) -> Result<()> {
104        self.in_second_context(false, run).await
105    }
106
107    async fn in_second_context(
108        &self,
109        tab: bool,
110        run: impl AsyncFnOnce() -> Result<()>,
111    ) -> Result<()> {
112        let original = self.inner.window().await?;
113        let url = self.inner.current_url().await?;
114        let opened = if tab {
115            self.inner.new_tab().await?
116        } else {
117            self.inner.new_window().await?
118        };
119
120        let result = async {
121            self.inner.switch_to_window(opened.clone()).await?;
122            self.set_window_size(WINDOW.0, WINDOW.1).await?;
123            self.inner.goto(url.as_str()).await?;
124            self.rewatch().await?;
125            run().await?;
126            match self.error_seen().await? {
127                Some(threw) => bail!("the page threw: {threw}"),
128                None => Ok(()),
129            }
130        }
131        .await;
132
133        let cleanup = async {
134            self.inner.switch_to_window(opened).await?;
135            self.inner.close_window().await?;
136            self.inner.switch_to_window(original).await?;
137            Ok(())
138        }
139        .await;
140
141        match result {
142            Ok(()) => cleanup,
143            Err(error) => Err(with_cleanup(error, cleanup)),
144        }
145    }
146}