wasm_bindgen_test/rt/
browser.rs

1//! Support for printing status information of a test suite in a browser.
2//!
3//! Currently this is quite simple, rendering the same as the console tests in
4//! node.js. Output here is rendered in a `pre`, however.
5
6use alloc::format;
7use alloc::string::String;
8use js_sys::Error;
9use wasm_bindgen::prelude::*;
10
11/// Implementation of `Formatter` for browsers.
12///
13/// Routes all output to a `pre` on the page currently. Eventually this probably
14/// wants to be a pretty table with colors and folding and whatnot.
15pub struct Browser {
16    pre: Element,
17}
18
19#[wasm_bindgen]
20extern "C" {
21    type HTMLDocument;
22    #[wasm_bindgen(thread_local_v2, js_name = document)]
23    static DOCUMENT: HTMLDocument;
24    #[wasm_bindgen(method, structural)]
25    fn getElementById(this: &HTMLDocument, id: &str) -> Element;
26
27    type Element;
28    #[wasm_bindgen(method, getter = textContent, structural)]
29    fn text_content(this: &Element) -> String;
30    #[wasm_bindgen(method, setter = textContent, structural)]
31    fn set_text_content(this: &Element, text: &str);
32
33    type BrowserError;
34    #[wasm_bindgen(method, getter, structural)]
35    fn stack(this: &BrowserError) -> JsValue;
36}
37
38impl Browser {
39    /// Creates a new instance of `Browser`, assuming that its APIs will work
40    /// (requires `Node::new()` to have return `None` first).
41    pub fn new() -> Browser {
42        let pre = DOCUMENT.with(|document| document.getElementById("output"));
43        pre.set_text_content("");
44        Browser { pre }
45    }
46}
47
48impl super::Formatter for Browser {
49    fn writeln(&self, line: &str) {
50        let mut html = self.pre.text_content();
51        html.extend(line.chars().chain(Some('\n')));
52        self.pre.set_text_content(&html);
53    }
54
55    fn stringify_error(&self, err: &JsValue) -> String {
56        // TODO: this should be a checked cast to `Error`
57        let err = Error::from(err.clone());
58        let name = String::from(err.name());
59        let message = String::from(err.message());
60        let err = BrowserError::from(JsValue::from(err));
61        let stack = err.stack();
62
63        let header = format!("{}: {}", name, message);
64        let stack = match stack.as_string() {
65            Some(stack) => stack,
66            None => return header,
67        };
68
69        // If the `stack` variable contains the name/message already, this is
70        // probably a chome-like error which is already rendered well, so just
71        // return this info
72        if stack.contains(&header) {
73            return stack;
74        }
75
76        // Fallback to make sure we don't lose any info
77        format!("{}\n{}", header, stack)
78    }
79}