wasm_bindgen_test/rt/
worker.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 Worker {}
16
17#[wasm_bindgen]
18extern "C" {
19    type WorkerError;
20    #[wasm_bindgen(method, getter, structural)]
21    fn stack(this: &WorkerError) -> JsValue;
22
23    #[wasm_bindgen(js_name = "__wbg_test_output_writeln")]
24    fn write_output_line(data: JsValue);
25}
26
27impl Worker {
28    /// Attempts to create a new formatter for web worker
29    pub fn new() -> Worker {
30        Worker {}
31    }
32}
33
34impl super::Formatter for Worker {
35    fn writeln(&self, line: &str) {
36        write_output_line(JsValue::from(String::from(line)));
37    }
38
39    fn stringify_error(&self, err: &JsValue) -> String {
40        // TODO: this should be a checked cast to `Error`
41        let error = Error::from(err.clone());
42        let name = String::from(error.name());
43        let message = String::from(error.message());
44        let err = WorkerError::from(err.clone());
45        let stack = err.stack();
46
47        let header = format!("{}: {}", name, message);
48        let stack = match stack.as_string() {
49            Some(stack) => stack,
50            None => return header,
51        };
52
53        // If the `stack` variable contains the name/message already, this is
54        // probably a chome-like error which is already rendered well, so just
55        // return this info
56        if stack.contains(&header) {
57            return stack;
58        }
59
60        // Fallback to make sure we don't lose any info
61        format!("{}\n{}", header, stack)
62    }
63}