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